]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/ocaml/mathql_interpreter/mQIMySql.ml
- MySQL mode added to the interpreter
[helm.git] / helm / ocaml / mathql_interpreter / mQIMySql.ml
index f5d30d1ed47128c8836de0c419a4f75862f70c7a..af50af8ff45fdf2b33626b3152cdfef119f9fb0b 100644 (file)
 (*  AUTOR: Ferruccio Guidi <fguidi@cs.unibo.it>
  *)
 
-type connection = Mysql.dbd
+let init () =
+   try Mysql.quick_connect
+       ~host:"mowgli.cs.unibo.it" ~database:"mowgli" ~user:"helm" ()
+   with _ -> raise (Failure "mqi_connecion")
 
-let init connection_string =
-   try
-    Some
-     (Mysql.quick_connect
-       ~host:"mowgli.cs.unibo.it" ~database:"mowgli" ~user:"helm" ())
-   with _ -> raise (Failure ("MQIPostgres.init: " ^ connection_string))
+let close c = Mysql.disconnect c
 
-let close = function
-   |  None   -> ()
-   |  Some c -> Mysql.disconnect c
-
-let exec c q = match c with
-   | None   -> []
-   | Some c ->
-      Mysql.map
-       ~f:(function a ->
-         List.map
-          (function
-              None -> raise (Failure ("NULL found in a table"))
-            | Some v -> v
-          ) (Array.to_list a)
-       ) (Mysql.exec c q)
-   
 let quote s =
    let rec quote_aux s =
       try
@@ -60,3 +42,43 @@ let quote s =
       with Not_found -> s
    in
    "'" ^ quote_aux s ^ "'"
+
+let exec c q = 
+   let g = function None -> "" | Some v -> v in
+   let f a = List.map g (Array.to_list a) in
+   Mysql.map ~f:f (Mysql.exec c q), q
+
+let exec c table cols ct cfl =
+   let rec iter f sep = function
+      | []           -> ""
+      | [head]       -> f head 
+      | head :: tail -> f head ^ sep ^ iter f sep tail
+   in
+   let pg_cols = iter (fun x -> x) ", " cols in
+   let pg_msval v = iter quote ", " v in
+   let pg_con (pat, col, v) = 
+      if col <> "" then 
+         let f s = col ^ " regexp " ^ quote ("^" ^ s ^ "$") in
+         if pat then "(" ^ iter f " or " v ^ ")"
+        else match v with 
+           | [s] -> "binary " ^ col ^ " = " ^ (quote s)     
+           | v   -> "binary " ^ col ^ " in (" ^ pg_msval v ^ ")"
+      else "1"
+   in
+   let pg_cons l = iter pg_con " and " l in
+   let pg_cons_not l = "not (" ^ pg_cons l ^ ")" in
+   let pg_cons_not_l ll = iter pg_cons_not " and " ll in
+   let pg_where = match ct, cfl with
+      | [], []  -> ""
+      | lt, []  -> " where " ^ pg_cons lt
+      | [], llf -> " where " ^ pg_cons_not_l llf
+      | lt, llf -> " where " ^ pg_cons lt ^ " and " ^ pg_cons_not_l llf
+   in
+   if cols = [] then
+      let r, q = exec c ("select count (source) from " ^ table ^ pg_where) in
+      match r with
+         | [[s]] when int_of_string s > 0 -> [[]], q
+        | _                              -> [], q
+   else
+      exec c ("select " ^ pg_cols ^ " from " ^ table ^ pg_where ^ 
+            " order by " ^ List.hd cols ^ " asc")