From 830e7c5d27d161b91402414e6ecd49f1ed818bfb Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Fri, 27 Mar 2026 08:48:05 +0100 Subject: Initial commit --- lib/query/common.ml | 0 lib/query/create.ml | 251 ++++++++++++++++++++++++++++++++++++++++++++ lib/query/dune | 11 ++ lib/query/encoder.ml | 268 +++++++++++++++++++++++++++++++++++++++++++++++ lib/query/insert.ml | 146 ++++++++++++++++++++++++++ lib/query/insert.mli | 12 +++ lib/query/intf.ml | 151 ++++++++++++++++++++++++++ lib/query/query.ml | 9 ++ lib/query/query.mli | 21 ++++ lib/query/tests/create.t | 150 ++++++++++++++++++++++++++ lib/query/tests/dune | 11 ++ lib/query/tests/insert.t | 213 +++++++++++++++++++++++++++++++++++++ 12 files changed, 1243 insertions(+) create mode 100644 lib/query/common.ml create mode 100644 lib/query/create.ml create mode 100644 lib/query/dune create mode 100644 lib/query/encoder.ml create mode 100644 lib/query/insert.ml create mode 100644 lib/query/insert.mli create mode 100644 lib/query/intf.ml create mode 100644 lib/query/query.ml create mode 100644 lib/query/query.mli create mode 100644 lib/query/tests/create.t create mode 100644 lib/query/tests/dune create mode 100644 lib/query/tests/insert.t (limited to 'lib/query') diff --git a/lib/query/common.ml b/lib/query/common.ml new file mode 100644 index 0000000..e69de29 diff --git a/lib/query/create.ml b/lib/query/create.ml new file mode 100644 index 0000000..ec1fb21 --- /dev/null +++ b/lib/query/create.ml @@ -0,0 +1,251 @@ +open StdLabels +module Ast = Configuration.Ast + +let ( |>::? ) : 'a list -> 'a option -> 'a list = + fun lst opt -> match opt with None -> lst | Some v -> v :: lst + +let ( let* ) = Lwt.bind + +let get_field_query : _ Model.Field.t -> string option = + fun field -> + let ty = + match Model.Field.type_ field with + | T (MultiReference _) -> None + | T Integer -> Some "INTEGER" + | T (MonoReference _) -> Some "INTEGER" + | T Text -> Some "VARCHAR" + in + Option.map + (fun t -> + String.concat ~sep:" " [ "\"" ^ Model.Field.name field ^ "\""; t ]) + ty + +type foreign = { + src_table : string; + src_column : string; + dst_table : string; + dst_column : string; +} +(** Foreign key between a column referencing a content and the referenced value +*) + +(* +ALTER TABLE question +ADD FOREIGN KEY (best_a_id) +REFERENCES answer(a_id); +*) + +let get_foreign_statement : string -> _ Model.Content.t -> string = + fun property content -> + "FOREIGN KEY(\"" ^ property ^ "\") REFERENCES " ^ Model.Content.id content + ^ "(\"id\")" + +(** Create the dedicated table required for multivaluated fields *) +let create_external_reference_table : + Caqti_lwt.connection -> + Model.Reference.t Model.Content.t -> + foreign list -> + Model.Reference.t Model.Field.t -> + foreign list Lwt.t = + fun db content acc field -> + match Model.Field.type_ field with + | Model.Field.(T Integer) + | Model.Field.(T Text) + | Model.Field.(T (MonoReference _)) -> + Lwt.return acc + | Model.Field.(T (MultiReference reference)) -> + let buff = Buffer.create 16 in + let format = Format.formatter_of_buffer buff in + let target = Model.Reference.get reference.Model.Typ.t in + let fields = + [ + "\"id\" INTEGER PRIMARY KEY"; + "\"parent\" INTEGER NOT NULL"; + "\"target\" INTEGER NOT NULL"; + get_foreign_statement "parent" content; + get_foreign_statement "target" target; + ] + in + let () = + Format.fprintf format "CREATE TABLE \"%s.%s\"@; @[@[( %a@] )@]" + (Model.Content.id content) (Model.Field.name field) + (Format.pp_print_list + ~pp_sep:(fun f () -> + Format.pp_print_break f 0 0; + Format.pp_print_string f ", ") + Format.pp_print_string) + fields + in + Format.pp_print_flush format (); + let request_str = Buffer.contents buff in + let request = + Caqti_request.Infix.( + (Caqti_type.unit ->. Caqti_type.unit) ~oneshot:true) + request_str + in + let module Db = (val db) in + let* result = Db.exec request () in + let* () = Caqti_lwt.or_fail result in + Lwt.return acc + +(** Generate the create table for a content *) +let rec create_table : + Caqti_lwt.connection -> + foreign list * Model.Reference.t Model.Content.t list -> + _ Model.Content.t -> + (foreign list * Model.Reference.t Model.Content.t list) Lwt.t = + fun db (alter_queries, created) content -> + (* The foreign keys are added at the end of the query, and need to be + defined first *) + let alter_queries = + match Model.Content.parent content with + | None -> alter_queries + | Some p -> + { + src_table = Model.Content.id content; + src_column = "parent"; + dst_table = Model.Content.id p; + dst_column = "id"; + } + :: alter_queries + in + + let content_fields = List.of_seq (Model.Content.fields content) in + + (* Collect all the target contents already created in the database, and add + the foreign key constraint *) + let init_foreign = + match Model.Content.parent content with + | Some parent -> [ get_foreign_statement "parent" parent ] + | None -> [] + in + let foreign, alter_queries = + List.fold_left content_fields ~init:(init_foreign, alter_queries) + ~f:(fun (foreign, alter_queries) field -> + match Model.Field.type_ field with + | T (MonoReference reference) -> ( + let dst = Model.Reference.get reference.Model.Typ.t in + let column = Model.Field.name field in + match List.mem ~set:created dst with + | true -> + let foreign = get_foreign_statement column dst :: foreign in + (foreign, alter_queries) + | false -> + (* If the table does not exists yet, add the constraint in the + ALTER TABLE list. + + This list will be processed later, once all the table are + created *) + let alter_queries = + { + src_table = Model.Content.id content; + src_column = column; + dst_table = Model.Content.id dst; + dst_column = "id"; + } + :: alter_queries + in + (foreign, alter_queries)) + | _ -> (foreign, alter_queries)) + in + + let fields = + "\"id\" INTEGER PRIMARY KEY" + (* Identify each field in each of the sections *) + :: List.fold_left content_fields ~init:foreign ~f:(fun acc field -> + match get_field_query field with None -> acc | Some q -> q :: acc) + |>::? Option.map + (* We don’t care about the parent, we just want to + know there is one in order to add the column *) + (fun _ -> "\"parent\" INTEGER NOT NULL") + (Model.Content.parent content) + in + let buff = Buffer.create 128 in + let format = Format.formatter_of_buffer buff in + let () = + Format.fprintf format "CREATE TABLE \"%s\"@; @[@[( %a@] )@]" + (Model.Content.id content) + (Format.pp_print_list + ~pp_sep:(fun f () -> + Format.pp_print_break f 0 0; + Format.pp_print_string f ", ") + Format.pp_print_string) + fields + in + Format.pp_print_flush format (); + let request_str = Buffer.contents buff in + let request = + Caqti_request.Infix.((Caqti_type.unit ->. Caqti_type.unit) ~oneshot:true) + request_str + in + let module Db = (val db) in + let* result = Db.exec request () in + let* () = Caqti_lwt.or_fail result in + (* Create the externals tables holding the multivaluated fields *) + let* acc = + Lwt_list.fold_left_s + (create_external_reference_table db content) + alter_queries content_fields + in + let created = content :: created in + (* Create the subcontent *) + let* acc = + Lwt_list.fold_left_s (create_table db) (acc, created) + (Model.Content.subcontents content) + in + Lwt.return acc + +(** Modify the table and add the foreign key in case of cyclic references *) +let add_foreign_statement : Caqti_lwt.connection -> foreign list -> unit Lwt.t = + fun db foreigns -> + let request_str = + "ALTER TABLE ? ADD CONSTRAINT FOREIGN KEY(?) REFERENCES ?(?)" + in + let request = + Caqti_request.Infix.( + (Caqti_type.(t4 string string string string) ->. Caqti_type.unit) + ~oneshot:true) + request_str + in + let module Db = (val db) in + let* () = + Lwt_list.iter_s + (fun foreign -> + let* result = + Db.exec request + ( foreign.src_table, + foreign.src_column, + foreign.dst_table, + foreign.dst_column ) + in + Caqti_lwt.or_fail result) + foreigns + in + Lwt.return_unit + +let create : Caqti_lwt.connection -> Configuration.Ast.setting -> unit Lwt.t = + fun db conf -> + let module Db = (val db) in + let contents = Configuration.Ast.root_contents conf in + let* foreign, _ = + Lwt_list.fold_left_s + (fun acc content -> + match Model.Content.parent content with + | Some _ -> + (* Ignore the subcontents, they will be created just after the + parent *) + Lwt.return acc + | None -> create_table db acc content) + ([], []) contents + in + match Caqti_driver_info.dialect_tag Db.driver_info with + | `Sqlite -> + (* There is no way to add a foreign key to an existing table in sqlite, + so we just stop the table creation here. + + https://www.sqlite.org/foreignkeys.html#fk_schemacommands + https://www.sqlite.org/omitted.html + *) + ignore foreign; + Lwt.return_unit + | `Pgsql | `Mysql | _ -> add_foreign_statement db foreign diff --git a/lib/query/dune b/lib/query/dune new file mode 100644 index 0000000..b9a862a --- /dev/null +++ b/lib/query/dune @@ -0,0 +1,11 @@ +(library + (name query) + (libraries + caqti + caqti-lwt + caqti-lwt.unix + lwt.unix + lwt + uri + model + configuration)) diff --git a/lib/query/encoder.ml b/lib/query/encoder.ml new file mode 100644 index 0000000..624931a --- /dev/null +++ b/lib/query/encoder.ml @@ -0,0 +1,268 @@ +(** Encode the values in order to build a request All of the modules are used to + build query, either when generating placeholders in the query, giving values + to the request, or column name. *) + +open StdLabels +open Intf + +module Map (T : Encoder) = struct + let rec f : type a. a tuple -> a T.t = + fun t -> + match t with + | T0 -> T.unit + | T1 t1 -> T.f t1 + | T2 (t1, t2) -> T.t2 (T.f t1) (T.f t2) + | T3 (t1, t2, t3) -> T.t3 (T.f t1) (T.f t2) (T.f t3) + | T4 (t1, t2, t3, t4) -> T.t4 (T.f t1) (T.f t2) (T.f t3) (T.f t4) + | T5 (t1, t2, t3, t4, t5) -> + T.t5 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) + | T6 (t1, t2, t3, t4, t5, t6) -> + T.t6 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) + | T7 (t1, t2, t3, t4, t5, t6, t7) -> + T.t7 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) (T.f t7) + | T8 (t1, t2, t3, t4, t5, t6, t7, t8) -> + T.t8 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) (T.f t7) + (T.f t8) + | T9 (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> + T.t9 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) (T.f t7) + (T.f t8) (T.f t9) + | T10 (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) -> + T.t10 (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) (T.f t7) + (T.f t8) (T.f t9) (T.f t10) + | T_N (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t_n) -> + let tl = f t_n in + T.t_n (T.f t1) (T.f t2) (T.f t3) (T.f t4) (T.f t5) (T.f t6) (T.f t7) + (T.f t8) (T.f t9) (T.f t10) tl +end + +module Fold (T : sig + type 'a t + + val f : 'a t -> 'any data -> 'a t +end) = +struct + let rec f : type a. 'acc -> a tuple -> 'acc = + fun init t -> + match t with + | T0 -> init + | T1 t1 -> T.f init t1 + | T2 (t1, t2) -> T.f (T.f init t1) t2 + | T3 (t1, t2, t3) -> T.f (T.f (T.f init t1) t2) t3 + | T4 (t1, t2, t3, t4) -> T.f (T.f (T.f (T.f init t1) t2) t3) t4 + | T5 (t1, t2, t3, t4, t5) -> T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5 + | T6 (t1, t2, t3, t4, t5, t6) -> + T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6 + | T7 (t1, t2, t3, t4, t5, t6, t7) -> + T.f (T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6) t7 + | T8 (t1, t2, t3, t4, t5, t6, t7, t8) -> + T.f + (T.f (T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6) t7) + t8 + | T9 (t1, t2, t3, t4, t5, t6, t7, t8, t9) -> + T.f + (T.f + (T.f (T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6) t7) + t8) + t9 + | T10 (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10) -> + T.f + (T.f + (T.f + (T.f + (T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6) + t7) + t8) + t9) + t10 + | T_N (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, tl) -> + let init' = + T.f + (T.f + (T.f + (T.f + (T.f (T.f (T.f (T.f (T.f (T.f init t1) t2) t3) t4) t5) t6) + t7) + t8) + t9) + t10 + in + f init' tl +end + +let rec list_to_tup : f:('a -> t_type) -> 'a list -> t = + fun ~f lst -> + match lst with + | [] -> T T0 + | elem_0 :: [] -> + let (TT v0) = f elem_0 in + T (T1 v0) + | [ elem_0; elem_1 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + T (T2 (v0, v1)) + | [ elem_0; elem_1; elem_2 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + T (T3 (v0, v1, v2)) + | [ elem_0; elem_1; elem_2; elem_3 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + T (T4 (v0, v1, v2, v3)) + | [ elem_0; elem_1; elem_2; elem_3; elem_4 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + T (T5 (v0, v1, v2, v3, v4)) + | [ elem_0; elem_1; elem_2; elem_3; elem_4; elem_5 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + T (T6 (v0, v1, v2, v3, v4, v5)) + | [ elem_0; elem_1; elem_2; elem_3; elem_4; elem_5; elem_6 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + let (TT v6) = f elem_6 in + T (T7 (v0, v1, v2, v3, v4, v5, v6)) + | [ elem_0; elem_1; elem_2; elem_3; elem_4; elem_5; elem_6; elem_7 ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + let (TT v6) = f elem_6 in + let (TT v7) = f elem_7 in + T (T8 (v0, v1, v2, v3, v4, v5, v6, v7)) + | [ elem_0; elem_1; elem_2; elem_3; elem_4; elem_5; elem_6; elem_7; elem_8 ] + -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + let (TT v6) = f elem_6 in + let (TT v7) = f elem_7 in + let (TT v8) = f elem_8 in + T (T9 (v0, v1, v2, v3, v4, v5, v6, v7, v8)) + | [ + elem_0; + elem_1; + elem_2; + elem_3; + elem_4; + elem_5; + elem_6; + elem_7; + elem_8; + elem_9; + ] -> + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + let (TT v6) = f elem_6 in + let (TT v7) = f elem_7 in + let (TT v8) = f elem_8 in + let (TT v9) = f elem_9 in + T (T10 (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9)) + | elem_0 :: elem_1 :: elem_2 :: elem_3 :: elem_4 :: elem_5 :: elem_6 :: elem_7 + :: elem_8 :: elem_9 :: tl -> + (* In this pattern, we are sure tl is not empty, otherwise we would have + matched the previous case *) + let (TT v0) = f elem_0 in + let (TT v1) = f elem_1 in + let (TT v2) = f elem_2 in + let (TT v3) = f elem_3 in + let (TT v4) = f elem_4 in + let (TT v5) = f elem_5 in + let (TT v6) = f elem_6 in + let (TT v7) = f elem_7 in + let (TT v8) = f elem_8 in + let (TT v9) = f elem_9 in + let (T tl) = list_to_tup ~f tl in + T (T_N (v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, tl)) + +module CaqtiRequest = Map (struct + include Caqti_type + + let t_n = Caqti_type.t11 + + let f : type a. a data -> a Caqti_type.t = function + | { content = Text; _ } -> Caqti_type.option @@ Caqti_type.string + | { content = Integer; _ } -> Caqti_type.option @@ Caqti_type.int64 + | { content = MultiReference _; _ } -> Caqti_type.option @@ Caqti_type.int64 + | { content = MonoReference _; _ } -> Caqti_type.option @@ Caqti_type.int64 +end) + +module DefaultEncoder = struct + let unit = () + let t2 a b = (a, b) + let t3 a b c = (a, b, c) + let t4 a b c d = (a, b, c, d) + let t5 a b c d e = (a, b, c, d, e) + let t6 a b c d e f = (a, b, c, d, e, f) + let t7 a b c d e f g = (a, b, c, d, e, f, g) + let t8 a b c d e f g h = (a, b, c, d, e, f, g, h) + let t9 a b c d e f g h i = (a, b, c, d, e, f, g, h, i) + let t10 a b c d e f g h i j = (a, b, c, d, e, f, g, h, i, j) + let t_n a b c d e f g h i j k = (a, b, c, d, e, f, g, h, i, j, k) +end + +module ConcatParam = struct + let sep = "," + let unit = "" + let t2 a b = String.concat ~sep [ a; b ] + let t3 a b c = String.concat ~sep [ a; b; c ] + let t4 a b c d = String.concat ~sep [ a; b; c; d ] + let t5 a b c d e = String.concat ~sep [ a; b; c; d; e ] + let t6 a b c d e f = String.concat ~sep [ a; b; c; d; e; f ] + let t7 a b c d e f g = String.concat ~sep [ a; b; c; d; e; f; g ] + let t8 a b c d e f g h = String.concat ~sep [ a; b; c; d; e; f; g; h ] + let t9 a b c d e f g h i = String.concat ~sep [ a; b; c; d; e; f; g; h; i ] + + let t10 a b c d e f g h i j = + String.concat ~sep [ a; b; c; d; e; f; g; h; i; j ] + + let t_n a b c d e f g h i j k = + String.concat ~sep [ a; b; c; d; e; f; g; h; i; j; k ] +end + +module EncodeInsert = Map (struct + type 'a t = string + + let f : type a. a data -> a t = function + | { content = Text; _ } -> "?" + | { content = Integer; _ } -> "?" + | { content = MonoReference _; _ } -> "?" + | { content = MultiReference _; _ } -> + failwith "Cannot encode multireference field" + + include ConcatParam +end) + +module InsertTableName = Map (struct + type 'a t = string + + let f : type a. a data -> a t = function + | { name = column; content = Text; _ } -> column + | { name = column; content = Integer; _ } -> column + | { name = column; content = MultiReference _; _ } -> column + | { name = column; content = MonoReference _; _ } -> column + + include ConcatParam +end) diff --git a/lib/query/insert.ml b/lib/query/insert.ml new file mode 100644 index 0000000..39c32d0 --- /dev/null +++ b/lib/query/insert.ml @@ -0,0 +1,146 @@ +(** Generate the insert queries for the different database *) + +exception TypeMismatch +(** Exception raised when the given type does not match the value *) + +(** Transform the list of fields from the model into a tuple with the type of + each field associated with *) +let collect_fields : + ?init_fields:Model.Reference.t Model.Field.t list -> + ?filter:('a Model.Field.t -> bool) -> + 'a Model.Content.t -> + Intf.t = + fun ?(init_fields = []) ?filter content -> + let field_seq = + match filter with + | None -> Model.Content.fields content + | Some f -> Model.Content.fields content |> Seq.filter f + in + + let fields = init_fields @ List.of_seq field_seq in + + Encoder.list_to_tup fields ~f:(fun field -> + let name = Model.Field.name field in + let (Model.Field.T content) = Model.Field.type_ field in + TT { name; content }) + +(** Insert a row. This syntax use RETURNING ID to get the value we just inserted +*) +let insert_returning : + Caqti_lwt.connection -> + Model.Reference.t Model.Content.t -> + (string -> Model.Reference.t Model.Typ.value) -> + int64 Lwt.t = + fun db content provider -> + let module Db = (val db) in + let module CaqtiValues = Encoder.Map (struct + include Encoder.DefaultEncoder + + type 'a t = 'a + + let f : type a. a Intf.data -> a t = + fun Intf.{ name; content } -> + let result = provider name in + (* Check the value given by the provider and ensure it’s match + the expected type *) + match (content, result) with + | _, None -> + (* The provider does not have any value for this property, use the + default value*) + Model.Typ.default_value content + | _, V (field_type', value) -> ( + match Model.Typ.eq content field_type' with + | Some Equal -> Some value + | None -> raise TypeMismatch) + end) in + let init_fields = + match Model.Content.parent content with + | None -> [] + | Some _ -> Model.Field.[ create (T Integer) [] ~required:true "parent" ] + in + + (* Remove the mulivaluated content fields from the request because they are + not inserted in the table directly *) + let (T t) = + collect_fields content + ~filter:(fun field -> + let (T ty) = Model.Field.type_ field in + match ty with Model.Typ.MultiReference _ -> false | _ -> true) + ~init_fields + in + let insert_template = + match t with Intf.T0 -> "" | _ -> "(" ^ Encoder.EncodeInsert.f t ^ ")" + and columns = + match t with + | Intf.T0 -> "DEFAULT" + | _ -> "(" ^ Encoder.InsertTableName.f t ^ ")" + in + + let buff = Buffer.create 16 in + let format = Format.formatter_of_buffer buff in + let () = + Format.fprintf format "INSERT INTO \"%s\" %s VALUES %s RETURNING ID" + (Model.Content.id content) columns insert_template + in + Format.pp_print_flush format (); + let types_param = Encoder.CaqtiRequest.f t in + let request = + Caqti_request.Infix.((types_param ->! Caqti_type.int64) ~oneshot:true) + (Buffer.contents buff) + in + let ( let* ) = Lwt.bind in + let values = CaqtiValues.f t in + + (* The insert request is returning the ID. That’s why we call it with the + fuction [find] even if it is not a real find in the database. *) + let* id_result = Db.find request values in + let* id = Caqti_lwt.or_fail id_result in + + (* The value is created in the db, reuse the ID in order to insert the + multi-values fields in their own tables *) + let (T multi_valuated_fields) = + collect_fields content ~filter:(fun field -> + let (T ty) = Model.Field.type_ field in + match ty with Model.Typ.MultiReference _ -> true | _ -> false) + in + + let module Fold = Encoder.Fold (struct + type 'a t = 'a Lwt.t + + (** The function is called for each feature declared as multi reference. *) + let f : 'a Lwt.t -> 'b Intf.data -> 'a Lwt.t = + fun acc Intf.{ name; content } -> + ignore content; + let values = provider name in + ignore values; + let* acc = acc in + Lwt.return acc + end) in + let* () = Fold.f Lwt.return_unit multi_valuated_fields in + Lwt.return id + +(** Insert an entry for a specific content *) +let insert : + Caqti_lwt.connection -> + Model.Reference.t Model.Content.t -> + ?parent:int64 -> + (string -> Model.Reference.t Model.Typ.value) -> + int64 Lwt.t = + fun db content ?parent provider -> + let provider = + match (parent, Model.Content.parent content) with + | _, None -> provider + | None, Some _ -> + (* Raise an error right now if the parent of the subcontent is not + given *) + raise TypeMismatch + | Some v, Some _ -> ( + (* Otherwise update the provider to give a value for the parent *) + function + | "parent" -> Model.Typ.(V (Integer, v)) + | other -> provider other) + in + let module Db = (val db) in + match Caqti_driver_info.dialect_tag Db.driver_info with + | `Sqlite | `Pgsql -> insert_returning db content provider + | _ -> raise Not_found diff --git a/lib/query/insert.mli b/lib/query/insert.mli new file mode 100644 index 0000000..63e16a6 --- /dev/null +++ b/lib/query/insert.mli @@ -0,0 +1,12 @@ +(** Low level insertion in the database *) + +exception TypeMismatch +(** Exception raised when the given type does not match the value *) + +val insert : + Caqti_lwt.connection -> + Model.Reference.t Model.Content.t -> + ?parent:int64 -> + (string -> Model.Reference.t Model.Typ.value) -> + int64 Lwt.t +(** See [Query.insert] *) diff --git a/lib/query/intf.ml b/lib/query/intf.ml new file mode 100644 index 0000000..49c51db --- /dev/null +++ b/lib/query/intf.ml @@ -0,0 +1,151 @@ +type 'a data = { name : string; content : ('a, Model.Reference.t) Model.Typ.t } +(** The data is the name of the field and the type associated with *) + +type t_type = TT : 'a data -> t_type [@@unboxed] + +(** Keep a track of the number in the fields in the content. Each property in + the content is mapped as an optionnal field in the DB, as each value can be + empty. *) +type _ tuple = + | T0 : unit tuple + | T1 : 'a data -> 'a tuple + | T2 : 'a data * 'b data -> ('a * 'b) tuple + | T3 : 'a data * 'b data * 'c data -> ('a * 'b * 'c) tuple + | T4 : 'a data * 'b data * 'c data * 'd data -> ('a * 'b * 'c * 'd) tuple + | T5 : + 'a data * 'b data * 'c data * 'd data * 'e data + -> ('a * 'b * 'c * 'd * 'e) tuple + | T6 : + 'a data * 'b data * 'c data * 'd data * 'e data * 'f data + -> ('a * 'b * 'c * 'd * 'e * 'f) tuple + | T7 : + 'a data * 'b data * 'c data * 'd data * 'e data * 'f data * 'g data + -> ('a * 'b * 'c * 'd * 'e * 'f * 'g) tuple + | T8 : + 'a data + * 'b data + * 'c data + * 'd data + * 'e data + * 'f data + * 'g data + * 'h data + -> ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h) tuple + | T9 : + 'a data + * 'b data + * 'c data + * 'd data + * 'e data + * 'f data + * 'g data + * 'h data + * 'i data + -> ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i) tuple + | T10 : + 'a data + * 'b data + * 'c data + * 'd data + * 'e data + * 'f data + * 'g data + * 'h data + * 'i data + * 'j data + -> ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i * 'j) tuple + | T_N : + 'a data + * 'b data + * 'c data + * 'd data + * 'e data + * 'f data + * 'g data + * 'h data + * 'i data + * 'j data + * 'tl tuple + -> ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i * 'j * 'tl) tuple + +type t = T : _ tuple -> t [@@unboxed] + +module type Encoder = sig + type 'a t + + val f : 'a data -> 'a t + val unit : unit t + val t2 : 'a t -> 'b t -> ('a * 'b) t + val t3 : 'a t -> 'b t -> 'c t -> ('a * 'b * 'c) t + val t4 : 'a t -> 'b t -> 'c t -> 'd t -> ('a * 'b * 'c * 'd) t + val t5 : 'a t -> 'b t -> 'c t -> 'd t -> 'e t -> ('a * 'b * 'c * 'd * 'e) t + + val t6 : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + ('a * 'b * 'c * 'd * 'e * 'f) t + + val t7 : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + 'g t -> + ('a * 'b * 'c * 'd * 'e * 'f * 'g) t + + val t8 : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + 'g t -> + 'h t -> + ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h) t + + val t9 : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + 'g t -> + 'h t -> + 'i t -> + ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i) t + + val t10 : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + 'g t -> + 'h t -> + 'i t -> + 'j t -> + ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i * 'j) t + + val t_n : + 'a t -> + 'b t -> + 'c t -> + 'd t -> + 'e t -> + 'f t -> + 'g t -> + 'h t -> + 'i t -> + 'j t -> + 'k t -> + ('a * 'b * 'c * 'd * 'e * 'f * 'g * 'h * 'i * 'j * 'k) t +end diff --git a/lib/query/query.ml b/lib/query/query.ml new file mode 100644 index 0000000..4aaf467 --- /dev/null +++ b/lib/query/query.ml @@ -0,0 +1,9 @@ +(** This module provide functions used to generate SQL requests for creating or + updating contents. + + The model is not known at the compilation time, but we have all the required + informations in the configuration. Here, we create Caqti request template + matching the types given in the configuration. *) + +let insert = Insert.insert +let create = Create.create diff --git a/lib/query/query.mli b/lib/query/query.mli new file mode 100644 index 0000000..1a26383 --- /dev/null +++ b/lib/query/query.mli @@ -0,0 +1,21 @@ +val insert : + Caqti_lwt.connection -> + Model.Reference.t Model.Content.t -> + ?parent:int64 -> + (string -> Model.Reference.t Model.Typ.value) -> + int64 Lwt.t +(** Insert a new element and return the ID. + + [insert content ~parent provider] will create the content in the database. + + The parent is required if the content is a subcontent. Not providing the + parameter is a structural error in the database. + + For each field in the content, the function [provider] will be called with + the name for this property. The value returned shall match the expected type + for this property, the execption [TypeMismatch] is raised otherwise. + + This is a low-level function: there is no representation for the content + itself, and no functionnals controls are realized. *) + +val create : Caqti_lwt.connection -> Configuration.Ast.setting -> unit Lwt.t diff --git a/lib/query/tests/create.t b/lib/query/tests/create.t new file mode 100644 index 0000000..565235a --- /dev/null +++ b/lib/query/tests/create.t @@ -0,0 +1,150 @@ +Test the schema generated in the database. The tests create the database +in memory according the configuration given, then display the schema for a +specfic table. (The schema is extracted from the table, and requires the table +to be succesfully created). + +Test a single content with no field: + + $ tests -schema "entity" < { + > "content": [ + > { + > "id": "entity", + > } + > ] + > } + > EOF + CREATE TABLE "entity" + ( "id" INTEGER PRIMARY KEY ) + +Text fields or numeric fields are created as columns directly in the table: + + $ tests -schema "entity" < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "name", + > "label": {}, + > "type": "text", + > "required": true + > }, + > { + > "name": "year", + > "label": {}, + > "type": "integer" + > } + > ] + > } + > ] + > } + > ] + > } + > EOF + CREATE TABLE "entity" + ( "id" INTEGER PRIMARY KEY + , "year" INTEGER + , "name" VARCHAR ) + +A subcontent is linked to the parent: + + $ tests -schema "details" < { + > "content": [ + > { + > "id": "entity", + > "subcontent": [ + > { + > "id": "details" + > } + > ] + > } + > ] + > } + > EOF + CREATE TABLE "details" + ( "parent" INTEGER NOT NULL + , "id" INTEGER PRIMARY KEY + , FOREIGN KEY("parent") REFERENCES entity("id") ) + +A reference field is declared as a foreign key to the linked element + + $ tests -schema "entity" < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "name", + > "label": {}, + > "type": "text", + > "required": true + > }, + > { + > "name": "user_type", + > "label": {}, + > "type": { + > "content": "user_type_list", + > "multivaluated": false + > } + > } + > ] + > } + > ] + > }, + > { + > "id": "user_type_list" + > } + > ] + > } + > EOF + CREATE TABLE "entity" + ( "id" INTEGER PRIMARY KEY + , "user_type" INTEGER + , "name" VARCHAR + , FOREIGN KEY("user_type") REFERENCES user_type_list("id") ) + +When the field is multivaluated, there is no column for this property in the +table but a dedicated table is created: + + $ tests -schema "entity" "entity.user_type" < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "user_type", + > "label": {}, + > "type": { + > "content": "user_type_list", + > "multivaluated": true + > } + > } + > ] + > } + > ] + > }, + > { + > "id": "user_type_list" + > } + > ] + > } + > EOF + CREATE TABLE "entity" + ( "id" INTEGER PRIMARY KEY ) + CREATE TABLE "entity.user_type" + ( "id" INTEGER PRIMARY KEY + , "parent" INTEGER NOT NULL + , "target" INTEGER NOT NULL + , FOREIGN KEY("parent") REFERENCES entity("id") + , FOREIGN KEY("target") REFERENCES user_type_list("id") ) diff --git a/lib/query/tests/dune b/lib/query/tests/dune new file mode 100644 index 0000000..c5913da --- /dev/null +++ b/lib/query/tests/dune @@ -0,0 +1,11 @@ +; Add the test library in the path + +(env + (_ + (binaries %{project_root}/test/tests.exe))) + +; And depend of it. The binary will be available in the +; cram tests under the name "tests" + +(cram + (deps %{bin:tests})) diff --git a/lib/query/tests/insert.t b/lib/query/tests/insert.t new file mode 100644 index 0000000..236bb97 --- /dev/null +++ b/lib/query/tests/insert.t @@ -0,0 +1,213 @@ +Test the capacity to insert elements in the database according a specific +schema + +The data to insert is given in the json format. This format is a subset from the +configuration (for example we can’t have a property with the same name as a +subcontent) + +Minimal exemple, a content without any field does not have any value: + + $ tests -insert < { + > "content": [ + > { + > "id": "entity", + > "values": [ {} ] + > } + > ] + > } + > EOF + entity:1 + {} + +Ensure an error is raised if the value does not match the expected type. + +Here, the year is declared as an integer, but the value is provided as string. +This error is expected to be checked and reported. + + $ tests -insert < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "year", + > "label": {}, + > "type": "integer" + > } + > ] + > } + > ], + > "values": [ { "year": "1234", } ] + > } + > ] + > } + > EOF + Fatal error: exception Query__Insert.TypeMismatch + [2] + + $ tests -insert < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "name", + > "label": {}, + > "type": "text", + > "required": true + > }, + > { + > "name": "year", + > "label": {}, + > "type": "integer" + > } + > ] + > } + > ], + > "values": [ + > { + > "name": "name", + > "year": 1234, + > } + > ] + > } + > ] + > } + > EOF + entity:1 + {"name":"name","year":1234} + +Any value can be omitted and will be replaced by the default value: + $ tests -insert < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "year", + > "label": {}, + > "type": "integer", + > } + > ] + > } + > ], + > "values": [ {} ] + > } + > ] + > } + > EOF + entity:1 + {"year":null} + +If the field is "required" the value is still inserted: the requirement feature +is only functionnal; this shall not block the creation of the content. + + $ tests -insert < { + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "year", + > "label": {}, + > "type": "integer", + > "required": true, + > } + > ] + > } + > ], + > "values": [ {} ] + > } + > ] + > } + > EOF + entity:1 + {"year":null} + +A subcontent is linked to the parent: + + $ tests -insert < { + > "content": [ + > { + > "id": "referential", + > }, + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { + > "name": "idx", + > "label": {}, + > "type": "integer" + > }, + > { + > "name": "ref", + > "label": {}, + > "type": { + > "content": "referential", + > "multivaluated": true + > } + > } + > ] + > } + > ], + > "subcontent": [ + > { + > "id": "details", + > "section": [ + > { + > "field": [ + > { + > "name": "comment", + > "label": {}, + > "type": "text" + > }, + > ] + > } + > ], + > } + > ], + > "values": [ + > { + > "idx": 1, + > "details": [ + > {"comment": "lorem"}, + > {"comment": "ipsum"} + > ] + > }, + > { + > "idx": 2, + > "details": [ + > {"comment": "lorem 2"}, + > ] + > } + > ] + > } + > ] + > } + > EOF + entity:1 + {"idx":1} + details:1 + {"comment":"lorem","parent":1} + details:2 + {"comment":"ipsum","parent":1} + entity:2 + {"idx":2} + details:3 + {"comment":"lorem 2","parent":2} -- cgit v1.2.3