From ce13c93cf14cb71894481b0303a7058a72a6f4ce Mon Sep 17 00:00:00 2001 From: Sébastien Dailly Date: Sat, 21 Nov 2026 11:23:41 +0100 Subject: Load values from the database --- lib/model/data.ml | 24 +++ lib/model/data.mli | 45 ++++++ lib/model/model.ml | 5 +- lib/model/model.mli | 6 + lib/query/dune | 1 - lib/query/encoder.ml | 8 +- lib/query/insert.ml | 48 +++--- lib/query/insert.mli | 15 +- lib/query/query.ml | 1 + lib/query/query.mli | 35 +++-- lib/query/select.ml | 206 +++++++++++++++++++++++++ lib/query/select.mli | 30 ++++ lib/query/tests/insert.t | 387 ++++++----------------------------------------- lib/query/tests/select.t | 48 ++++++ lib/query/update.ml | 28 ++-- lib/value/data.ml | 24 --- lib/value/data.mli | 45 ------ lib/value/dune | 3 +- lib/value/tests/dune | 11 ++ lib/value/tests/load.t | 41 +++++ lib/value/value.ml | 104 +++++++++++-- lib/value/value.mli | 36 +++-- 22 files changed, 649 insertions(+), 502 deletions(-) create mode 100644 lib/model/data.ml create mode 100644 lib/model/data.mli create mode 100644 lib/query/select.ml create mode 100644 lib/query/select.mli create mode 100644 lib/query/tests/select.t delete mode 100644 lib/value/data.ml delete mode 100644 lib/value/data.mli create mode 100644 lib/value/tests/dune create mode 100644 lib/value/tests/load.t (limited to 'lib') diff --git a/lib/model/data.ml b/lib/model/data.ml new file mode 100644 index 0000000..9c44203 --- /dev/null +++ b/lib/model/data.ml @@ -0,0 +1,24 @@ +(** The data carried by a field of a value. + + [None] tells the field is empty (or left as is, on update), [V] carries a + single value together with the type of its field, and [Seq] carries a + sequence of references for a multivalued field. + + The type is parameterized over the type of the data held (['a]: the DB + representation of the field, e.g. [string option] or [int64 option]) and + over ['t], the target of the field for references — a reference is held as + an [int64] (the id of the target row), while ['t] records what it points to. + The field type {!Typ.t} stays in the model package; only the data itself + lives here. *) +type ('ocaml, 't) data = + | None + | V : ('db, 'ocaml, 't) Typ.t * 'ocaml -> ('ocaml, 't) data + +let none : ('ocaml, 't) data = None + +let v : ('db, 'ocaml, 't) Typ.t * 'ocaml -> ('ocaml, 't) data = + fun (typ, value) -> V (typ, value) + +type 't any = Any : ('ocaml, 't) data -> 't any [@@unboxed] + +let any : ('ocaml, 't) data -> 't any = fun data -> Any data diff --git a/lib/model/data.mli b/lib/model/data.mli new file mode 100644 index 0000000..6773589 --- /dev/null +++ b/lib/model/data.mli @@ -0,0 +1,45 @@ +(** The data carried by a field of a value. + + [none] tells the field is empty (or left as is, on update), and [v] carries + the value of the field together with its type — a single value, or a + sequence of references for a multivalued field. + + The type is parameterized over ['ocaml], the in-code representation of the + data held (e.g. [string option], [int64 option], or [int64 Seq.t] for a + multivalued reference), and over ['t], the target of the field for + references. The DB representation ['db] appears only inside the field type + carried by the constructors. The field type {!Typ.t} stays in the model + package; only the data itself lives here. *) + +type ('ocaml, 't) data = private + | None + | V : ('db, 'ocaml, 't) Typ.t * 'ocaml -> ('ocaml, 't) data + +val none : ('ocaml, 't) data +(** [none] tells the field is empty in the database (or left as is, on update) +*) + +val v : ('db, 'ocaml, 't) Typ.t * 'ocaml -> ('ocaml, 't) data +(** [v (typ, value)] is the value for the field, in its code representation + ['ocaml] — e.g. a single [string option], or an [int64 Seq.t] for a + multivalued reference. The field type [typ] is also reported: it ties the + payload to the field and determines the result type. Whether the value is a + sequence is carried by the type, not by a separate constructor. *) + +(** Existential pack over the held type: the data of a field whose type is not + known statically (e.g. the data of any field of a content, as returned by a + provider function). Matchable from the outside, but built with [any]. *) +type 't any = Any : ('ocaml, 't) data -> 't any [@@unboxed] + +val any : ('ocaml, 't) data -> 't any +(** Pack a typed [data] into an [any], hiding the type of the data held *) + +(** Example for inserting data — build the data of each field, then pack it: + [ + (* Function providing the data of each field to insert in the database *) + + let f : string -> Reference.target any = function + | "siret" -> any (v (Typ.Text, Some "siret")) + | "name" -> any (v (Typ.Text, Some "name")) + | _ -> any none + ] *) diff --git a/lib/model/model.ml b/lib/model/model.ml index 0f016ad..c3e5b5b 100644 --- a/lib/model/model.ml +++ b/lib/model/model.ml @@ -5,6 +5,7 @@ module Identifier = Identifier module Dsl = Dsl module Typ = Typ +module Data = Data module Reference = Reference module DataList = Data_list module Path = Path @@ -12,9 +13,9 @@ module Field = Field module Section = Section module Content = Content -(** The target of a reference field, resolved: a lazy pointer to a content, or - a static list. *) type target = Reference.target +(** The target of a reference field, resolved: a lazy pointer to a content, or a + static list. *) type list = target Data_list.t type content = target Content.t diff --git a/lib/model/model.mli b/lib/model/model.mli index a8941d9..0326eb2 100644 --- a/lib/model/model.mli +++ b/lib/model/model.mli @@ -119,6 +119,12 @@ module Reference = Reference type reference = target Typ.reference (** A reference field target: a {!target}, plus optional constraints *) +module Data = Data +(** The data carried by a field of a value: {!Data.data} (parameterized over the + in-code representation of the data held), built with the smart constructors + {!Data.none} and {!Data.v}, and {!Data.any}, the existential pack used when + the held type is not known statically. *) + module DataList = Data_list (** A static list declared in the configuration: its entries are loaded by the data provider and the list can be referenced from fields, but it is not diff --git a/lib/query/dune b/lib/query/dune index 990b572..307319a 100644 --- a/lib/query/dune +++ b/lib/query/dune @@ -9,5 +9,4 @@ uri croquette_common model - value configuration)) diff --git a/lib/query/encoder.ml b/lib/query/encoder.ml index 2174e59..5e5f402 100644 --- a/lib/query/encoder.ml +++ b/lib/query/encoder.ml @@ -291,7 +291,7 @@ module DataToCaqtiValues = Map (struct include DefaultEncoder type 'a t = 'a - type env = string -> Value.value + type env = string -> Model.target Model.Data.any let f : type a b. env -> (a, b) Intf.data -> a t = fun provider Intf.{ name; content_type } -> @@ -299,13 +299,13 @@ module DataToCaqtiValues = Map (struct (* Check the value given by the provider and ensure it’s match the expected type *) match result with - | Value.Data.Any d -> ( + | Model.Data.Any d -> ( match d with - | Value.Data.None -> + | Model.Data.None -> (* The provider does not have any value for this property, use the default value*) Model.Typ.default_value content_type - | Value.Data.V (field_type', value) -> ( + | Model.Data.V (field_type', value) -> ( (* For the single-column fields handled here, the DB and code representations coincide — match the field type to prove it *) let check (type x) (ct : (x, x, Model.target) Model.Typ.t) : x = diff --git a/lib/query/insert.ml b/lib/query/insert.ml index 703d5a9..26597d8 100644 --- a/lib/query/insert.ml +++ b/lib/query/insert.ml @@ -25,7 +25,7 @@ module MultiReferencesInsert = struct parent_id : int64; table : Model.Identifier.t; (** The table holding the row: a content table, or a list *) - provider : string -> Value.value; + provider : string -> Model.target Model.Data.any; k : (unit, Caqti.Error.t) result Lwt.t; } @@ -64,10 +64,10 @@ module MultiReferencesInsert = struct and target = Identifier.quote Identifier.target in match content_type with | Model.Typ.MultiReference _target -> ( - let (Value.Data.Any d) = provider (Model.Identifier.to_string name) in + let (Model.Data.Any d) = provider (Model.Identifier.to_string name) in match d with - | Value.Data.None -> acc - | Value.Data.V (field_type', values) -> ( + | Model.Data.None -> acc + | Model.Data.V (field_type', values) -> ( match Model.Typ.eq_ocaml content_type field_type' with | None -> raise Encoder.TypeMismatch | Some Equal -> @@ -106,7 +106,7 @@ let insert_row : table:Model.Identifier.t -> ?init_fields:Model.field list -> Model.field list -> - (string -> Value.value) -> + (string -> Model.target Model.Data.any) -> int64 Lwt.t = fun db ~table ?(init_fields = []) fields provider -> let module Db = (val db) in @@ -165,8 +165,8 @@ let insert_row : let insert_returning : Caqti_lwt.connection -> Model.content -> - (string -> Value.value) -> - Model.content Value.t Lwt.t = + (string -> Model.target Model.Data.any) -> + int64 Lwt.t = fun db content provider -> let init_fields = match Model.Content.parent content with @@ -181,15 +181,15 @@ let insert_returning : (List.of_seq (Model.Content.fields content)) provider in - Lwt.return (Value.v content id) + Lwt.return id -(** Insert an entry for a specific content *) +(** Insert an entry for a specific content, and return the id of the new row *) let insert : Caqti_lwt.connection -> Model.content -> - ?parent:Model.content Value.t -> - (string -> Value.value) -> - Model.content Value.t Lwt.t = + ?parent:Int64.t -> + (string -> Model.target Model.Data.any) -> + int64 Lwt.t = fun db content ?parent provider -> let provider = match (parent, Model.Content.parent content) with @@ -198,15 +198,11 @@ let insert : (* Raise an error right now if the parent of the subcontent is not given *) raise Encoder.TypeMismatch - | Some v, Some _ -> ( + | Some parent_id, Some _ -> ( (* Otherwise update the provider to give a value for the parent *) - let parent_id = - match Value.get v Value.id_ref with - | Some parent_id -> parent_id - | None -> raise Encoder.TypeMismatch - in function - | "parent" -> Value.single (Model.Typ.Integer, Some parent_id) + | "parent" -> + Model.Data.any (Model.Data.v (Model.Typ.Integer, Some parent_id)) | other -> provider other) in let module Db = (val db) in @@ -215,7 +211,7 @@ let insert : insert_returning db content provider | _ -> raise Not_found -(** Insert a row in the dedicated table of a list, and return it. +(** Insert a row in the dedicated table of a list, and return its id. Like [insert], the [provider] is called with the name of each field of the list to get its value. Multivalued fields are inserted in their own @@ -223,8 +219,8 @@ let insert : let insert_list : Caqti_lwt.connection -> Model.list -> - (string -> Value.value) -> - Model.list Value.t Lwt.t = + (string -> Model.target Model.Data.any) -> + int64 Lwt.t = fun db list provider -> let module Db = (val db) in match Db.dialect with @@ -234,7 +230,7 @@ let insert_list : insert_row db ~table:list.Model.DataList.id list.Model.DataList.fields provider in - Lwt.return (Value.v list id) + Lwt.return id | _ -> raise Not_found let insert_references : @@ -242,13 +238,13 @@ let insert_references : Model.content -> Int64.t -> Model.Identifier.t -> - Value.value -> + Model.target Model.Data.any -> (Int64.t, _) Intf.data -> unit Lwt.t = fun db content content_id field_name value data -> - let provider : string -> Value.value = function + let provider : string -> Model.target Model.Data.any = function | n when String.equal n (Model.Identifier.to_string field_name) -> value - | _ -> Value.none + | _ -> Model.Data.any Model.Data.none in let acc = MultiReferencesInsert. diff --git a/lib/query/insert.mli b/lib/query/insert.mli index a0ab6e9..d3e3de9 100644 --- a/lib/query/insert.mli +++ b/lib/query/insert.mli @@ -3,18 +3,17 @@ val insert : Caqti_lwt.connection -> Model.content -> - ?parent:Model.content Value.t -> - (string -> Value.value) -> - Model.content Value.t Lwt.t + ?parent:Int64.t -> + (string -> Model.target Model.Data.any) -> + int64 Lwt.t (** See [Query.insert] *) val insert_list : Caqti_lwt.connection -> Model.list -> - (string -> Value.value) -> - Model.list Value.t Lwt.t -(** Insert a row in the dedicated table of a static list, and return it as a - value. + (string -> Model.target Model.Data.any) -> + int64 Lwt.t +(** Insert a row in the dedicated table of a static list, and return its id. The [provider] is called with the name of each field of the list to get its value, like [insert]. Multivalued fields are inserted in their dedicated @@ -25,7 +24,7 @@ val insert_references : Model.content -> Int64.t -> Model.Identifier.t -> - Value.value -> + Model.target Model.Data.any -> (Int64.t, _) Intf.data -> unit Lwt.t (** Insert a list of references for a content. This function is used during the diff --git a/lib/query/query.ml b/lib/query/query.ml index 2984ed3..8d8006c 100644 --- a/lib/query/query.ml +++ b/lib/query/query.ml @@ -9,3 +9,4 @@ let insert = Insert.insert let insert_list = Insert.insert_list let create = Create.create let update = Update.q +let select = Select.select diff --git a/lib/query/query.mli b/lib/query/query.mli index cd7287f..ae7245e 100644 --- a/lib/query/query.mli +++ b/lib/query/query.mli @@ -1,17 +1,16 @@ val insert : Caqti_lwt.connection -> Model.content -> - ?parent:Model.content Value.t -> - (string -> Value.value) -> - Model.content Value.t Lwt.t -(** Insert a new element and return it as a value. + ?parent:Int64.t -> + (string -> Model.target Model.Data.any) -> + int64 Lwt.t +(** Insert a new element in the database and return the id of the new row. - [insert db content ~parent provider] will create the content in the database - and return the inserted row as a [Value.t] (the content together with its - new id). + [insert db content ~parent provider] creates the content in the database and + returns the primary key of the inserted row. - The parent — itself a value — is required if the content is a subcontent. - Not providing the parameter will raise the error [TypeMismatch]. + The [parent] — the id of the parent row — is required if the content is a + subcontent. Not providing the parameter will raise the error [TypeMismatch]. 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 @@ -23,10 +22,9 @@ val insert : val insert_list : Caqti_lwt.connection -> Model.list -> - (string -> Value.value) -> - Model.list Value.t Lwt.t -(** Insert a row in the dedicated table of a static list, and return it as a - value. + (string -> Model.target Model.Data.any) -> + int64 Lwt.t +(** Insert a row in the dedicated table of a static list, and return its id. The [provider] is called with the name of each field of the list, like [insert]. This is the function used to populate the lists from their source. @@ -38,5 +36,14 @@ val update : Caqti_lwt.connection -> Int64.t -> Model.content -> - (string -> Value.value) -> + (string -> Model.target Model.Data.any) -> unit Lwt.t + +val select : + Caqti_lwt.connection -> + Int64.t -> + Model.content -> + Select.callback -> + unit Lwt.t +(** Read a row of a content table and call the callback once per field with the + field's named type and its value. See [Query.Select.select] *) diff --git a/lib/query/select.ml b/lib/query/select.ml new file mode 100644 index 0000000..011544c --- /dev/null +++ b/lib/query/select.ml @@ -0,0 +1,206 @@ +(** Read a row of a content table from the database, and expose each of its + fields to a callback. *) + +let ( let* ) = Lwt.bind + +type callback = { + f : + 'db 'ocaml. + ('db, 'ocaml, Model.target) Model.Typ.t Model.Typ.named * 'ocaml -> unit; +} + +(** Call the callback for one single-column field. For those fields the database + and the code representations coincide, so the column value read from the + database is also the code value. *) +let apply_field : type a b. callback -> (a, b) Intf.data -> a -> unit = + fun k Intf.{ name; content_type } value -> + match content_type with + | Model.Typ.Text -> + let named = Model.Typ.named ~name ~typ:content_type in + k.f (named, value) + | Model.Typ.Integer -> + let named = Model.Typ.named ~name ~typ:content_type in + k.f (named, value) + | Model.Typ.MonoReference _ -> + let named = Model.Typ.named ~name ~typ:content_type in + k.f (named, value) + | Model.Typ.MultiReference _ -> raise Encoder.TypeMismatch + +(** Call the callback for each field of the tuple, zipping the type descriptors + with the row read from the database *) +let rec iter_fields : type a. callback -> a Intf.tuple -> a -> unit = + fun k tup row -> + match tup with + | Intf.T0 -> ( match row with () -> ()) + | Intf.T1 d1 -> apply_field k d1 row + | Intf.T2 (d1, d2) -> + let v1, v2 = row in + apply_field k d1 v1; + apply_field k d2 v2 + | Intf.T3 (d1, d2, d3) -> + let v1, v2, v3 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3 + | Intf.T4 (d1, d2, d3, d4) -> + let v1, v2, v3, v4 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4 + | Intf.T5 (d1, d2, d3, d4, d5) -> + let v1, v2, v3, v4, v5 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5 + | Intf.T6 (d1, d2, d3, d4, d5, d6) -> + let v1, v2, v3, v4, v5, v6 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6 + | Intf.T7 (d1, d2, d3, d4, d5, d6, d7) -> + let v1, v2, v3, v4, v5, v6, v7 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6; + apply_field k d7 v7 + | Intf.T8 (d1, d2, d3, d4, d5, d6, d7, d8) -> + let v1, v2, v3, v4, v5, v6, v7, v8 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6; + apply_field k d7 v7; + apply_field k d8 v8 + | Intf.T9 (d1, d2, d3, d4, d5, d6, d7, d8, d9) -> + let v1, v2, v3, v4, v5, v6, v7, v8, v9 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6; + apply_field k d7 v7; + apply_field k d8 v8; + apply_field k d9 v9 + | Intf.T10 (d1, d2, d3, d4, d5, d6, d7, d8, d9, d10) -> + let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10 = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6; + apply_field k d7 v7; + apply_field k d8 v8; + apply_field k d9 v9; + apply_field k d10 v10 + | Intf.T_N (d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, tl) -> + let v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, vtl = row in + apply_field k d1 v1; + apply_field k d2 v2; + apply_field k d3 v3; + apply_field k d4 v4; + apply_field k d5 v5; + apply_field k d6 v6; + apply_field k d7 v7; + apply_field k d8 v8; + apply_field k d9 v9; + apply_field k d10 v10; + iter_fields k tl vtl + +(** Read the targets of a multivalued reference field from its dedicated table, + and call the callback with the sequence of targets *) +let select_multireference : + Caqti_lwt.connection -> + Model.Identifier.t -> + Int64.t -> + Model.field -> + callback -> + unit Lwt.t = + fun db table id field k -> + let module Db = (val db) in + let module Identifier = Model.Identifier in + let name = Model.Field.name field in + let (Model.Field.T content_type) = Model.Field.type_ field in + match content_type with + | Model.Typ.MultiReference _ -> + let named = Model.Typ.named ~name ~typ:content_type in + let q = + Croquette_common.Format.format_string (fun format -> + Format.fprintf format "SELECT %s FROM %s WHERE %s = ?" + (Identifier.quote Identifier.target) + (Identifier.quote (Identifier.dot table name)) + (Identifier.quote Identifier.parent)) + in + let request = Caqti.Templater.(direct T.(int64 -->* int64) q) in + let* res = Db.collect_list request id in + let* targets = Caqti_lwt.or_fail res in + k.f (named, List.to_seq targets); + Lwt.return_unit + | _ -> raise Encoder.TypeMismatch + +let select : + Caqti_lwt.connection -> Int64.t -> Model.content -> callback -> unit Lwt.t = + fun db id content k -> + let module Db = (val db) in + let module Identifier = Model.Identifier in + let table = Model.Content.id content in + (* The [parent] column of a subcontent is exposed as a field, like on + insert *) + let init_fields = + match Model.Content.parent content with + | None -> [] + | Some _ -> + [ + Model.Field.create (Model.Field.T Model.Typ.Integer) [] ~required:true + Model.Identifier.parent; + ] + in + let fields = init_fields @ List.of_seq (Model.Content.fields content) in + let is_multireference field = + match Model.Field.type_ field with + | Model.Field.T (Model.Typ.MultiReference _) -> true + | _ -> false + in + let single_fields = List.filter (fun f -> not (is_multireference f)) fields in + let multi_fields = List.filter is_multireference fields in + (* The multivalued fields are not columns of the content table, they are + read separately from their dedicated tables *) + let (T single) = + Encoder.list_to_tup single_fields ~f:(fun field -> + let name = Model.Field.name field in + let (Model.Field.T content_type) = Model.Field.type_ field in + Intf.TT { name; content_type }) + in + let* () = + match single with + | Intf.T0 -> Lwt.return_unit + | _ -> + let columns = Encoder.InsertTableName.f () single in + let row_type = Encoder.CaqtiRequest.f () single in + let q = + Croquette_common.Format.format_string (fun format -> + Format.fprintf format "SELECT %s FROM %s WHERE %s = ?" columns + (Identifier.quote table) + (Identifier.quote Identifier.id)) + in + let request = Caqti.Templater.(direct T.(int64 -->! row_type) q) in + let* res = Db.find request id in + let* row = Caqti_lwt.or_fail res in + let () = iter_fields k single row in + Lwt.return_unit + in + Lwt_list.iter_s + (fun field -> select_multireference db table id field k) + multi_fields diff --git a/lib/query/select.mli b/lib/query/select.mli new file mode 100644 index 0000000..338cef8 --- /dev/null +++ b/lib/query/select.mli @@ -0,0 +1,30 @@ +(** Read a row of a content table from the database *) + +type callback = { + f : + 'db 'ocaml. + ('db, 'ocaml, Model.target) Model.Typ.t Model.Typ.named * 'ocaml -> unit; +} +(** A callback called once per field of the selected row, with the field's named + type and its data in the code representation ['ocaml] — a pair that can be + stored in a value's dictionary and read back as typed data. + + The field is existentially typed: ['db] and ['ocaml] are universally + quantified in the record field, so a plain function works for a field of any + type: [ { f = fun (named, data) -> ... } ]. *) + +val select : + Caqti_lwt.connection -> Int64.t -> Model.content -> callback -> unit Lwt.t +(** [select db id content callback] reads the row [id] in the table of [content] + and calls [callback.f] once per field of the content, with the field's named + type and its value: + + - the single-column fields ([Text], [Integer], [MonoReference], plus the + reserved [parent] column of a subcontent) are read from the content table + — their database and code representations coincide; + - each multivalued reference field is read from its dedicated table + ([content.field]) and yields the sequence of its targets ([int64 Seq.t]). + + The [id] of the row itself is not passed to the callback: it is the [id] + argument. In the callback, each [(named, data)] pair can be stored in a + value's dictionary to make the field readable as typed data. *) diff --git a/lib/query/tests/insert.t b/lib/query/tests/insert.t index e060ad4..3dd2c94 100644 --- a/lib/query/tests/insert.t +++ b/lib/query/tests/insert.t @@ -1,31 +1,32 @@ -Test the capacity to insert elements in the database according a specific -schema +Test the capacity to insert elements in the database according to 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) +The configuration is read on the standard input, and the name of the content to +populate is given as argument. Two rows are inserted per run, with a value +generated for each field from its type and the row number (see +[Common.provider_for]): text and integer fields get a value derived from the +field name, monovalued references point to the row of id 1, and multivalued +references get two values for the first row and one for the second. -Minimal exemple, a content without any field does not have any value: +A content without any field gets an empty row: - $ tests --insert < { > "content": [ > { - > "id": "entity", - > "values": [ {} ] + > "id": "entity" > } > ] > } > EOF entity:1 {} + entity:2 + {} -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. +Text and integer fields are filled with a generated value: - $ tests --insert < { > "content": [ > { @@ -33,366 +34,66 @@ This error is expected to be checked and reported. > "section": [ > { > "field": [ - > { - > "name": "year", - > "label": {}, - > "type": "integer" - > } + > { "name": "name", "label": {}, "type": "text" }, + > { "name": "year", "label": {}, "type": "integer" } > ] > } - > ], - > "values": [ { "year": "1234", } ] - > } - > ] - > } - > EOF - Fatal error: exception Query__Encoder.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 in the -database. - - $ tests --insert < { - > "content": [ - > { - > "id": "entity", - > "section": [ - > { - > "field": [ - > { - > "name": "year", - > "label": {}, - > "type": "integer", - > "required": true, - > } - > ] - > } - > ], - > "values": [ {} ] - > } - > ] - > } - > EOF - entity:1 - {"year":null} + {"name":"name-1","year":1} + entity:2 + {"name":"name-2","year":2} -A subcontent is linked to the parent: +References are declared in the field type. A monovalued reference stores the +id of the target row in the content table, and each value of a multivalued +reference gets its own line, read back from the dedicated table: - $ tests --insert < { - > "content": [ + > "list": [ > { - > "id": "referential", - > }, - > { - > "id": "entity", - > "section": [ - > { - > "field": [ - > { - > "name": "idx", - > "label": {}, - > "type": "integer" - > }, - > ] - > } - > ], - > "subcontent": [ - > { - > "id": "details", - > "section": [ - > { - > "field": [ - > { - > "name": "comment", - > "label": {}, - > "type": "text" - > }, - > ] - > } - > ], - > } - > ], - > "values": [ - > { - > "idx": 1, - > "details": [ - > {"comment": "lorem"}, - > {"comment": "ipsum"} - > ] - > }, - > { - > "idx": 2, - > "details": [ - > {"comment": "lorem 2"}, - > ] - > } + > "id": "country_list", + > "field": [ + > { "name": "code", "label": {}, "type": "text" } > ] > } - > ] - > } - > 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} - -In this syntax, external references are declared inside the feature referencing -them. - - $ tests --insert < { + > ], > "content": [ > { - > "id": "referential", + > "id": "entity", > "section": [ > { > "field": [ + > { "name": "name", "label": {}, "type": "text" }, + > { "name": "year", "label": {}, "type": "integer" }, > { - > "name": "description", + > "name": "country", > "label": {}, - > "type": "text" + > "type": { "content": "country_list" } > }, - > ] - > } - > ], - > "values": [ - > {"description": "id2"}, - > ] - > }, - > { - > "id": "entity", - > "section": [ - > { - > "field": [ - > { - > "name": "idx", - > "label": {}, - > "type": "integer" - > }, - > { - > "name": "comment", - > "label": {}, - > "type": { - > "content": "referential", - > "multivaluated": false - > } - > } - > ] - > } - > ], - > "values": [ - > { - > "idx": 1, - > "comment": {"description": "id1"}, - > - > }, - > ] - > } - > ] - > } - > EOF - referential:2 - {"description":"id2"} - entity:1 - {"idx":1,"comment":1} - -Four contents are created for the type referential here: -- Two as contents linked referenced by the content "entity" (ids 1 and 2). -- Two as contents not referenced at all (ids 3 and 4). - - $ tests --insert < { - > "content": [ - > { - > "id": "referential", - > "section": [ - > { - > "field": [ > { - > "name": "description", + > "name": "aliases", > "label": {}, - > "type": "text" - > }, + > "type": { "content": "country_list", "multivaluated": true } + > } > ] > } - > ], - > "values": [ - > {"description": "id3"}, - > {"description": "id4"} - > ] - > }, - > { - > "id": "entity", - > "section": [ - > { - > "field": [ - > { - > "name": "idx", - > "label": {}, - > "type": "integer" - > }, - > { - > "name": "comment", - > "label": {}, - > "type": { - > "content": "referential", - > "multivaluated": true - > } - > } - > ] - > } - > ], - > "values": [ - > { - > "idx": 1, - > "comment": [ - > {"description": "id1"}, - > {"description": "id2"} - > ] - > }, > ] > } > ] > } > EOF - referential:3 - {"description":"id3"} - referential:4 - {"description":"id4"} - entity:1 - {"idx":1} entity:1 - {"comment":1} + {"name":"name-1","year":1,"country":1} entity:1 - {"comment":2} - -Subcontent are also managed in the same way. - - $ tests --insert < { - > "content": [ - > { - > "id": "entity", - > "section": [ - > { - > "field": [ ] - > } - > ], - > "subcontent": [ - > { - > "id": "details", - > "section": [ - > { - > "field": [ - > { - > "name": "reference", - > "label": {}, - > "type": { - > "content": "referential", - > "multivaluated": true - > } - > } - > ] - > } - > ], - > } - > ], - > "values": [ - > { - > "idx": 1, - > "details": [ - > { - > // Create two references here, the counter for the non-linked - > // reference is raised to 3 - > "reference": [ {}, {} ] - > } - > ] - > }, - > ] - > }, - > { - > "id": "referential", - > "values": [ {} ] - > }, - > ] - > } - > EOF + {"aliases":1} entity:1 - {} - details:1 - {"parent":1} - details:1 - {"reference":1} - details:1 - {"reference":2} - referential:3 - {} + {"aliases":2} + entity:2 + {"name":"name-2","year":2,"country":1} + entity:2 + {"aliases":2} diff --git a/lib/query/tests/select.t b/lib/query/tests/select.t new file mode 100644 index 0000000..f4a4740 --- /dev/null +++ b/lib/query/tests/select.t @@ -0,0 +1,48 @@ +Low level test of [Query.select]: two rows are inserted in the table of the +content given as argument (the configuration is read on the standard input), +then each row is read back with [Query.select]. One line is printed per field, +as received by the callback. The [id] of the row is the argument of [select]: +it is not reported by the callback. + + $ tests --select "entity" < { + > "list": [ + > { + > "id": "country_list", + > "field": [ + > { "name": "code", "label": {}, "type": "text" } + > ] + > } + > ], + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { "name": "name", "label": {}, "type": "text" }, + > { "name": "year", "label": {}, "type": "integer" }, + > { "name": "country", "label": {}, "type": { "content": "country_list" } }, + > { + > "name": "aliases", + > "label": {}, + > "type": { "content": "country_list", "multivaluated": true } + > } + > ] + > } + > ] + > } + > ] + > } + > EOF + row 1: + name = "name-1" + year = 1 + country -> 1 + aliases -> [1,2] + row 2: + name = "name-2" + year = 2 + country -> 1 + aliases -> [2] + diff --git a/lib/query/update.ml b/lib/query/update.ml index 5b53cb7..08a7551 100644 --- a/lib/query/update.ml +++ b/lib/query/update.ml @@ -1,6 +1,6 @@ (** Generate the update queries for a content *) -type provider = string -> Value.value +type provider = string -> Model.target Model.Data.any module UpdateTemplate = Encoder.Map (struct type 'a t = string @@ -22,7 +22,7 @@ end) let update_fields : Caqti_lwt.connection -> Model.content -> - (Intf.t_type * (string * Value.value)) list -> + (Intf.t_type * (string * Model.target Model.Data.any)) list -> int64 -> unit Lwt.t = fun db content fields id -> @@ -141,7 +141,9 @@ let update_mulivaluated_field : At this step, we can just use the code from the insert module. *) let remaining = ReferencesSet.(diff values (of_list remaining')) in - let v = Value.single (t, ReferencesSet.to_seq remaining) in + let v = + Model.Data.any (Model.Data.v (t, ReferencesSet.to_seq remaining)) + in Insert.insert_references db content id field_name v data_type) Lwt.return_unit fields @@ -149,7 +151,7 @@ let q : Caqti_lwt.connection -> Int64.t -> Model.content -> - (string -> Value.value) -> + (string -> Model.target Model.Data.any) -> unit Lwt.t = fun db id content provider -> let module Db = (val db) in @@ -157,15 +159,15 @@ let q : (* There is a difference between - - Value.Data.none - - Value.Data.v (typ, None) + - Model.Data.none + - Model.Data.v (typ, None) The former will be ignored in the update, and the value will remain as is. The latter will set the column to NULL in the database. *) let fields, references = Seq.fold_left (fun ((fields, references) as acc : - (Intf.t_type * (string * Value.value)) list + (Intf.t_type * (string * Model.target Model.Data.any)) list * (Model.Identifier.t * Model.target Model.Typ.multireference * int64 Seq.t) @@ -173,12 +175,12 @@ let q : let name = Model.Field.name field in let (Model.Field.T content_type) = Model.Field.type_ field in let tt = Intf.TT { name; content_type } in - let (Value.Data.Any d) = provider (Model.Identifier.to_string name) in + let (Model.Data.Any d) = provider (Model.Identifier.to_string name) in match content_type with | Model.Typ.MultiReference _ -> ( match d with - | Value.Data.None -> acc - | Value.Data.V (t, seq) -> ( + | Model.Data.None -> acc + | Model.Data.V (t, seq) -> ( match ( Model.Typ.eq content_type t, Model.Typ.eq_ocaml content_type t ) @@ -188,9 +190,9 @@ let q : | _ -> raise Encoder.TypeMismatch)) | _ -> ( match d with - | Value.Data.None -> acc - | Value.Data.V _ as dv -> - ( (tt, (Model.Identifier.to_string name, Value.Data.any dv)) + | Model.Data.None -> acc + | Model.Data.V _ as dv -> + ( (tt, (Model.Identifier.to_string name, Model.Data.any dv)) :: fields, references ))) ([], []) diff --git a/lib/value/data.ml b/lib/value/data.ml deleted file mode 100644 index f0e321e..0000000 --- a/lib/value/data.ml +++ /dev/null @@ -1,24 +0,0 @@ -(** The data carried by a field of a value. - - [None] tells the field is empty (or left as is, on update), [V] carries a - single value together with the type of its field, and [Seq] carries a - sequence of references for a multivalued field. - - The type is parameterized over the type of the data held (['a]: the DB - representation of the field, e.g. [string option] or [int64 option]) and - over ['t], the target of the field for references — a reference is held as - an [int64] (the id of the target row), while ['t] records what it points to. - The field type {!Model.Typ.t} stays in the model package; only the data - itself lives here. *) -type ('ocaml, 't) data = - | None - | V : ('db, 'ocaml, 't) Model.Typ.t * 'ocaml -> ('ocaml, 't) data - -let none : ('ocaml, 't) data = None - -let v : ('db, 'ocaml, 't) Model.Typ.t * 'ocaml -> ('ocaml, 't) data = - fun (typ, value) -> V (typ, value) - -type 't any = Any : ('ocaml, 't) data -> 't any [@@unboxed] - -let any : ('ocaml, 't) data -> 't any = fun data -> Any data diff --git a/lib/value/data.mli b/lib/value/data.mli deleted file mode 100644 index 7b7a5cc..0000000 --- a/lib/value/data.mli +++ /dev/null @@ -1,45 +0,0 @@ -(** The data carried by a field of a value. - - [none] tells the field is empty (or left as is, on update), and [v] carries - the value of the field together with its type — a single value, or a - sequence of references for a multivalued field. - - The type is parameterized over ['ocaml], the in-code representation of the - data held (e.g. [string option], [int64 option], or [int64 Seq.t] for a - multivalued reference), and over ['t], the target of the field for - references. The DB representation ['db] appears only inside the field type - carried by the constructors. The field type {!Model.Typ.t} stays in the - model package; only the data itself lives here. *) - -type ('ocaml, 't) data = private - | None - | V : ('db, 'ocaml, 't) Model.Typ.t * 'ocaml -> ('ocaml, 't) data - -val none : ('ocaml, 't) data -(** [none] tells the field is empty in the database (or left as is, on update) -*) - -val v : ('db, 'ocaml, 't) Model.Typ.t * 'ocaml -> ('ocaml, 't) data -(** [v (typ, value)] is the value for the field, in its code representation - ['ocaml] — e.g. a single [string option], or an [int64 Seq.t] for a - multivalued reference. The field type [typ] is also reported: it ties the - payload to the field and determines the result type. Whether the value is a - sequence is carried by the type, not by a separate constructor. *) - -(** Existential pack over the held type: the data of a field whose type is not - known statically (e.g. the data of any field of a content, as returned by a - provider function). Matchable from the outside, but built with [any]. *) -type 't any = Any : ('ocaml, 't) data -> 't any [@@unboxed] - -val any : ('ocaml, 't) data -> 't any -(** Pack a typed [data] into an [any], hiding the type of the data held *) - -(** Example for inserting data — build the data of each field, then pack it: - [ - (* Function providing the data of each field to insert in the database *) - - let f : string -> Model.target any = function - | "siret" -> any (v (Model.Typ.Text, Some "siret")) - | "name" -> any (v (Model.Typ.Text, Some "name")) - | _ -> any none - ] *) diff --git a/lib/value/dune b/lib/value/dune index bcfb9a8..761cdf7 100644 --- a/lib/value/dune +++ b/lib/value/dune @@ -1,4 +1,3 @@ (library (name value) - (libraries - model)) + (libraries model caqti-lwt lwt query)) diff --git a/lib/value/tests/dune b/lib/value/tests/dune new file mode 100644 index 0000000..c5913da --- /dev/null +++ b/lib/value/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/value/tests/load.t b/lib/value/tests/load.t new file mode 100644 index 0000000..e20860a --- /dev/null +++ b/lib/value/tests/load.t @@ -0,0 +1,41 @@ +High level test of [Value.load]: two rows are inserted in the table of the +content given as argument (the configuration is read on the standard input), +loaded as values with [Value.load] and printed with [Value.pp] — the primary +key and every field, as read back as typed data with [Value.get]. + + $ tests --load "entity" < { + > "list": [ + > { + > "id": "country_list", + > "field": [ + > { "name": "code", "label": {}, "type": "text" } + > ] + > } + > ], + > "content": [ + > { + > "id": "entity", + > "section": [ + > { + > "field": [ + > { "name": "name", "label": {}, "type": "text" }, + > { "name": "year", "label": {}, "type": "integer" }, + > { "name": "country", "label": {}, "type": { "content": "country_list" } }, + > { + > "name": "aliases", + > "label": {}, + > "type": { "content": "country_list", "multivaluated": true } + > } + > ] + > } + > ] + > } + > ] + > } + > EOF + row 1: + {id = 1; aliases = [1, 2]; country = 1; name = "name-1"; year = 1} + row 2: + {id = 2; aliases = [2]; country = 1; name = "name-2"; year = 2} + diff --git a/lib/value/value.ml b/lib/value/value.ml index 84bed4c..ab5b5a7 100644 --- a/lib/value/value.ml +++ b/lib/value/value.ml @@ -1,19 +1,32 @@ -module Data = Data -(** The data carried by a field: {!Data.data}, parameterized over the type of - the data held, built with the smart constructors [Data.none], [Data.v] *) - -type value = Model.target Data.any +type value = Model.target Model.Data.any (** A resolved field data: the data of a field of a content or a list, whatever the type of the data held *) -let none : value = Data.any Data.none +let none : value = Model.Data.any Model.Data.none let single : ('db, 'ocaml, Model.target) Model.Typ.t * 'ocaml -> value = - fun data -> Data.any (Data.v data) + fun data -> Model.Data.any (Model.Data.v data) + +(** The key of the fields dictionary: an existential pack over the named type of + a field, hiding its ['db] and ['ocaml] parameters *) +type key = + | Named : ('db, 'ocaml, Model.target) Model.Typ.t Model.Typ.named -> key + +module Key = struct + type t = key + + let equal : t -> t -> bool = fun (Named a) (Named b) -> Model.Typ.same a b + let hash : t -> int = fun (Named n) -> Hashtbl.hash (Model.Typ.name n) +end + +module Fields = Hashtbl.Make (Key) type 'a t = { content : 'a; (** The content or list whose table holds the row *) id : int64; (** The primary key of the row *) + fields : value Fields.t; + (** Cache of the other fields and their values, keyed by their named type + — empty by default, populating it requires reading the database *) } (** A value: one row of a content or list table in the database. @@ -21,10 +34,22 @@ type 'a t = { the row: [Model.content] for contents ([Model.content Value.t]) and [Model.list] for lists ([Model.list Value.t]). *) -let v : 'a -> int64 -> 'a t = fun content id -> { content; id } +let v : 'a -> int64 -> 'a t = + fun content id -> { content; id; fields = Fields.create 0 } + let content : 'a t -> 'a = fun t -> t.content let id : 'a t -> int64 = fun t -> t.id +let add_field : type ocaml. + 'a t -> + ('db, ocaml, Model.target) Model.Typ.t Model.Typ.named -> + ocaml -> + unit = + fun t ref data -> + let typ = Model.Typ.typ ref in + Fields.replace t.fields (Named ref) + (Model.Data.any (Model.Data.v (typ, data))) + let id_ref : Model.target Model.Typ.monoreference Model.Typ.named = Model.Typ.named ~name:Model.Identifier.id ~typ:Model.Typ.Integer @@ -33,4 +58,65 @@ let get : type ocaml. fun t ref -> match Model.Typ.provably_equal id_ref ref with | Some Type.Equal -> Some t.id - | None -> raise Not_found + | None -> ( + match Fields.find_opt t.fields (Named ref) with + | Some (Model.Data.Any (Model.Data.V (typ, payload))) -> ( + match Model.Typ.eq_ocaml (Model.Typ.typ ref) typ with + | Some Type.Equal -> payload + | None -> raise Not_found) + | _ -> raise Not_found) + +let load : Caqti_lwt.connection -> Model.content t -> unit Lwt.t = + fun db v -> + let ( let* ) = Lwt.bind in + let* () = + Query.select db v.id v.content + { f = (fun (named, data) -> add_field v named data) } + in + Lwt.return_unit + +(** Pretty-print the data of a field, whatever its type *) +let pp_data : type db ocaml. + Format.formatter -> (db, ocaml, Model.target) Model.Typ.t -> ocaml -> unit = + fun fmt typ data -> + let pp_option pp fmt data = + match data with + | Some v -> pp fmt v + | None -> Format.pp_print_string fmt "NULL" + in + match typ with + | Model.Typ.Text -> + pp_option (fun fmt s -> Format.fprintf fmt "%S" s) fmt data + | Model.Typ.Integer -> + pp_option (fun fmt i -> Format.fprintf fmt "%Ld" i) fmt data + | Model.Typ.MonoReference _ -> + pp_option (fun fmt i -> Format.fprintf fmt "%Ld" i) fmt data + | Model.Typ.MultiReference _ -> + Format.fprintf fmt "[%a]" + (Format.pp_print_list + ~pp_sep:(fun fmt () -> Format.pp_print_string fmt ", ") + (fun fmt i -> Format.fprintf fmt "%Ld" i)) + (List.of_seq data) + +let pp : Format.formatter -> 'a t -> unit = + fun fmt t -> + let fields = + Fields.fold + (fun (Named named) data acc -> (Model.Typ.name named, data) :: acc) + t.fields [] + |> List.sort (fun (n1, _) (n2, _) -> Model.Identifier.compare n1 n2) + in + let pp_field fmt (name, data) = + let (Model.Data.Any d) = data in + match d with + | Model.Data.None -> + Format.fprintf fmt "%s = NULL" (Model.Identifier.to_string name) + | Model.Data.V (typ, payload) -> + Format.fprintf fmt "%s = " (Model.Identifier.to_string name); + pp_data fmt typ payload + in + Format.fprintf fmt "{@[id = %Ld;@ %a@]}" t.id + (Format.pp_print_list + ~pp_sep:(fun fmt () -> Format.pp_print_string fmt "; ") + pp_field) + fields diff --git a/lib/value/value.mli b/lib/value/value.mli index 5c493aa..5a8984d 100644 --- a/lib/value/value.mli +++ b/lib/value/value.mli @@ -2,15 +2,9 @@ A value is one row of a content or list table in the database. *) -module Data = Data -(** The data carried by a field: {!Data.data}, parameterized over the type of - the data held, built with the smart constructors ([Data.none], [Data.v]); - and {!Data.any}, the existential pack used when the held type is not known - statically *) - -type value = Model.target Data.any +type value = Model.target Model.Data.any (** The data of a field of a content or a list, whatever the type of the data - held: an existential pack over {!Data.data} *) + held: an existential pack over {!Model.Data.data} *) val none : value (** [none]: the field is empty (or left as is, on update) *) @@ -54,6 +48,26 @@ val get : key of [v], and a multivalued reference field would yield an [int64 Seq.t]. The match between the requested named type and the readable field is proved - by {!Model.Typ.provably_equal} on name and type. Only the reserved field - [id_ref] is readable for now; the other fields are read from the database - (not implemented yet) and raise [Not_found]. *) + by {!Model.Typ.provably_equal} on name and type. The reserved field [id_ref] + is always readable; the other fields are read from the value's dictionary + (see {!add_field}) and raise [Not_found] when absent. *) + +val load : Caqti_lwt.connection -> Model.content t -> unit Lwt.t +(** [load db v] reads the row of [v] in the database (one query for the content + table, plus one per multivalued reference field) and stores each field in + [v]'s dictionary with {!add_field}, so that {!get} can then read every field + as typed data. + + The value is modified in place — the dictionary is part of its state — so + the function returns [unit]. The dictionary is empty when the value is built + with {!v}: [load] is what populates it. The primary key needs no loading — + {!get} with {!id_ref} reads it directly from the value. *) + +val pp : Format.formatter -> 'a t -> unit +(** Pretty-print a value as [{ id = …; field = …; … }]: the primary key and the + fields currently held in the value's dictionary, sorted by field name (the + dictionary is a hashtable, sorting keeps the output stable). + + The content or list the value belongs to is not printed — its type ['a] is + abstract here — and neither are the fields not loaded yet: only what {!load} + (or {!add_field}) put in the dictionary is shown. *) -- cgit v1.2.3