opam: update
[sqlgg.git] / lib / tables.ml
blob39935c9ebe84315178c5674410eef37fc3db3c0a
1 (** Global list of tables *)
3 open Printf
4 open ExtLib
6 type table = Sql.table
8 let all : table list ref = ref []
10 (** FIXME table names case sensitivity? *)
11 (* NB compares with db name *)
12 let by_name (name:Sql.table_name) = fun (n,_) -> n = name
14 (** @raise Error when no such table *)
15 let get_from tables name =
16 try
17 List.find (by_name name) tables
18 with Not_found -> failwith (sprintf "no such table %s" (Sql.show_table_name name))
20 let get name = get_from !all name
21 let get_schema name = snd (get name)
22 let check name = ignore (get name)
24 let add v =
25 let (name,_) = v in
26 match List.find_all (by_name name) !all with
27 | [] -> all := v :: !all
28 | _ -> failwith (sprintf "table %s already exists" (Sql.show_table_name name))
30 let drop name = check name; all := List.remove_if (by_name name) !all
32 let rename oldname newname =
33 let (_,t) = get oldname in
34 add (newname,t);
35 drop oldname
37 let alter name f =
38 check name;
39 let alter_schema ((n,s) as table) =
40 if n = name then
41 name, f s
42 else
43 table
45 all := List.map alter_schema !all
47 let alter_add name col pos = alter name (fun s -> Sql.Schema.add s col pos)
48 let alter_drop name col = alter name (fun s -> Sql.Schema.drop s col)
49 let alter_change name oldcol col pos = alter name (fun s -> Sql.Schema.change s oldcol col pos)
50 let rename_column name oldcol newcol = alter name (fun s -> Sql.Schema.rename s oldcol newcol)
52 let print ch tables = let out = IO.output_channel ch in List.iter (Sql.print_table out) tables; IO.flush out
53 let print_all () = print stdout !all
54 let print1 name = print stdout [get @@ Sql.make_table_name name] (* TODO allow db.name too *)
56 let reset () = all := []
58 let all () = !all