diff options
| author | Sébastien Dailly <sebastien@dailly.me> | 2026-03-30 17:56:42 +0200 |
|---|---|---|
| committer | Sébastien Dailly <sebastien@dailly.me> | 2026-04-01 09:49:08 +0200 |
| commit | 4af7d2f6ff8b38365c97a89c295710f5ed3266f5 (patch) | |
| tree | 8b641d4992eac896223c5169a8b7301205685d85 | |
| parent | 830e7c5d27d161b91402414e6ecd49f1ed818bfb (diff) | |
Manage insertion for multireferences fields
| -rw-r--r-- | lib/model/content.ml | 13 | ||||
| -rw-r--r-- | lib/model/content.mli | 3 | ||||
| -rw-r--r-- | lib/model/field.mli | 2 | ||||
| -rw-r--r-- | lib/model/typ.ml | 10 | ||||
| -rw-r--r-- | lib/query/encoder.ml | 25 | ||||
| -rw-r--r-- | lib/query/insert.ml | 125 | ||||
| -rw-r--r-- | lib/query/intf.ml | 5 | ||||
| -rw-r--r-- | lib/query/query.mli | 7 | ||||
| -rw-r--r-- | lib/query/tests/insert.t | 203 | ||||
| -rw-r--r-- | test/insert.ml | 387 |
10 files changed, 614 insertions, 166 deletions
diff --git a/lib/model/content.ml b/lib/model/content.ml index 2760715..4fe8e92 100644 --- a/lib/model/content.ml +++ b/lib/model/content.ml @@ -28,3 +28,16 @@ let fields : 'a t -> 'a Field.t Seq.t = fun t -> List.to_seq t.sections |> Seq.flat_map (fun section -> List.to_seq section.Section.fields) + +let find_target : 'a t -> string -> 'a option = + fun t name -> + let feature_opt = + Seq.find (fun f -> String.equal (Field.name f) name) (fields t) + in + + let ( let* ) = Option.bind in + let* feature : 'a Field.t = feature_opt in + let (T feature_type) = Field.type_ feature in + match feature_type with + | MonoReference t | MultiReference t -> Some t.Typ.t + | Integer | Text -> None diff --git a/lib/model/content.mli b/lib/model/content.mli index ab8d838..e972b83 100644 --- a/lib/model/content.mli +++ b/lib/model/content.mli @@ -16,3 +16,6 @@ val root : 'a t -> 'a t val fields : 'a t -> 'a Field.t Seq.t (** Iterate over the fields in the content *) + +val find_target : 'a t -> string -> 'a option +(** Get the content type pointed by the given field name *) diff --git a/lib/model/field.mli b/lib/model/field.mli index a121871..8e1432a 100644 --- a/lib/model/field.mli +++ b/lib/model/field.mli @@ -19,7 +19,7 @@ val create : 'ref t val name : _ t -> string -(** Name (identifier) for the field*) +(** Name (identifier) for the field *) val label : _ t -> textI18n val placeholder : _ t -> textI18n option diff --git a/lib/model/typ.ml b/lib/model/typ.ml index 2770885..d736be0 100644 --- a/lib/model/typ.ml +++ b/lib/model/typ.ml @@ -12,7 +12,7 @@ type ('db, 't) t = | Text : (string option, 't) t | Integer : (int64 option, 't) t | MonoReference : 't reference -> (int64 option, 't) t - | MultiReference : 't reference -> (int64 option, 't) t + | MultiReference : 't reference -> (int64, 't) t (** Multireferences properties allows only one kind of content. They are not encoded in the content table but in another table *) @@ -28,8 +28,8 @@ let map : type a. ('ref1 -> 'ref2) -> (a, 'ref1) t -> (a, 'ref2) t = let default_value : type a. (a, _) t -> a = function | Integer -> None | Text -> None - | MultiReference _ -> None | MonoReference _ -> None + | MultiReference _ -> raise Not_found let eq : type a b c. (a, c) t -> (b, c) t -> (a, b) Type.eq option = fun t1 t2 -> @@ -56,7 +56,9 @@ Example for inserting data *) type 't value = - | V : ('a option, 't) t * 'a -> 't value + | None (** None tell the field is empty in the database *) + | V : ('a option, 't) t * 'a option -> 't value (** V is the value for the field. The field type is also reported in order to give the compiler the nature of the data *) - | None (** None tell the field is empty in the database *) + | Seq : (int64, 't) t * int64 Seq.t -> 't value + (** Get a sequence of values for a multivaluated field *) diff --git a/lib/query/encoder.ml b/lib/query/encoder.ml index 624931a..2f86eab 100644 --- a/lib/query/encoder.ml +++ b/lib/query/encoder.ml @@ -203,10 +203,11 @@ module CaqtiRequest = Map (struct 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 + | { content_type = Text; _ } -> Caqti_type.option @@ Caqti_type.string + | { content_type = Integer; _ } -> Caqti_type.option @@ Caqti_type.int64 + | { content_type = MultiReference _; _ } -> Caqti_type.int64 + | { content_type = MonoReference _; _ } -> + Caqti_type.option @@ Caqti_type.int64 end) module DefaultEncoder = struct @@ -246,10 +247,10 @@ 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 _; _ } -> + | { content_type = Text; _ } -> "?" + | { content_type = Integer; _ } -> "?" + | { content_type = MonoReference _; _ } -> "?" + | { content_type = MultiReference _; _ } -> failwith "Cannot encode multireference field" include ConcatParam @@ -259,10 +260,10 @@ 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 + | { name = column; content_type = Text; _ } -> column + | { name = column; content_type = Integer; _ } -> column + | { name = column; content_type = MultiReference _; _ } -> column + | { name = column; content_type = MonoReference _; _ } -> column include ConcatParam end) diff --git a/lib/query/insert.ml b/lib/query/insert.ml index 39c32d0..b6aee0f 100644 --- a/lib/query/insert.ml +++ b/lib/query/insert.ml @@ -21,8 +21,86 @@ let collect_fields : 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 }) + let (Model.Field.T content_type) = Model.Field.type_ field in + TT { name; content_type }) + +module MultiReferencesInsert = struct + type 'a t = { + db : Caqti_lwt.connection; + parent_id : int64; + content : Model.Reference.t Model.Content.t; + provider : string -> Model.Reference.t Model.Typ.value; + k : (unit, Caqti_error.t) result Lwt.t; + } + + type request = (int64 * int64, unit, [ `Zero ]) Caqti_request.t + (** Helper for the request insert signature *) + + let ( let* ) = Lwt.bind + + let accumulate : + Caqti_lwt.connection -> + request -> + int64 -> + (unit, [> Caqti_error.t ]) result Lwt.t -> + int64 -> + (unit, [> Caqti_error.t ]) result Lwt.t = + fun db request parent k value -> + let module Db = (val db) in + let acc = + let* res = k in + match res with + | Error _ as err -> Lwt.return err + | Ok () -> + (* We have the type for each of the value, so we can create + a request directly. *) + Db.exec request (parent, value) + in + acc + + (** The function is called for each feature declared as multi reference. *) + let f : type any. 'a t -> any Intf.data -> 'a t = + fun ({ db; parent_id; provider; k; content } as acc) + Intf.{ name; content_type } -> + let module Db = (val db) in + match content_type with + | Model.Typ.MultiReference _target -> ( + let result = provider name in + match result with + | Model.Typ.None -> acc + | Model.Typ.V _ -> raise TypeMismatch + | Model.Typ.Seq (field_type', values) -> ( + match Model.Typ.eq content_type field_type' with + | None -> raise TypeMismatch + | Some Equal -> + let buff = Buffer.create 16 in + let format = Format.formatter_of_buffer buff in + let () = + Format.fprintf format + "INSERT INTO \"%s.%s\" (\"parent\", \"target\") VALUES (?, \ + ?)" + (Model.Content.id content) name + in + Format.pp_print_flush format (); + let request : request = + Caqti_request.Infix.( + Caqti_type.(t2 int64 int64 ->. Caqti_type.unit)) + (Buffer.contents buff) + in + let k = + (* Successively insert all the values in the dedicated table *) + let* res = + Seq.fold_left (accumulate db request parent_id) k values + in + let* _ = Db.deallocate request in + Lwt.return res + in + + { acc with k })) + | _ -> raise TypeMismatch +end + +module Fold = Encoder.Fold (MultiReferencesInsert) (** Insert a row. This syntax use RETURNING ID to get the value we just inserted *) @@ -39,18 +117,19 @@ let insert_returning : type 'a t = 'a let f : type a. a Intf.data -> a t = - fun Intf.{ name; content } -> + fun Intf.{ name; content_type } -> 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 -> + match result with + | Model.Typ.Seq _ -> raise TypeMismatch + | Model.Typ.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 + default value*) + Model.Typ.default_value content_type + | Model.Typ.V (field_type', value) -> ( + match Model.Typ.eq content_type field_type' with + | Some Equal -> value | None -> raise TypeMismatch) end) in let init_fields = @@ -94,7 +173,7 @@ let insert_returning : (* 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 + let* content_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 *) @@ -104,20 +183,14 @@ let insert_returning : 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 + let acc = + MultiReferencesInsert. + { db; provider; k = Lwt.return_ok (); parent_id = content_id; content } + in + let ret = Fold.f acc multi_valuated_fields in + let* k = ret.k in + let* () = Caqti_lwt.or_fail k in + Lwt.return content_id (** Insert an entry for a specific content *) let insert : @@ -137,7 +210,7 @@ let insert : | Some v, Some _ -> ( (* Otherwise update the provider to give a value for the parent *) function - | "parent" -> Model.Typ.(V (Integer, v)) + | "parent" -> Model.Typ.(V (Integer, Some v)) | other -> provider other) in let module Db = (val db) in diff --git a/lib/query/intf.ml b/lib/query/intf.ml index 49c51db..10e78b0 100644 --- a/lib/query/intf.ml +++ b/lib/query/intf.ml @@ -1,4 +1,7 @@ -type 'a data = { name : string; content : ('a, Model.Reference.t) Model.Typ.t } +type 'a data = { + name : string; + content_type : ('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] diff --git a/lib/query/query.mli b/lib/query/query.mli index 1a26383..9dcef17 100644 --- a/lib/query/query.mli +++ b/lib/query/query.mli @@ -6,14 +6,15 @@ val insert : int64 Lwt.t (** Insert a new element and return the ID. - [insert content ~parent provider] will create the content in the database. + [insert db 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. + 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 - for this property, the execption [TypeMismatch] is raised otherwise. + for this property, the exception [TypeMismatch] is raised otherwise. This is a low-level function: there is no representation for the content itself, and no functionnals controls are realized. *) diff --git a/lib/query/tests/insert.t b/lib/query/tests/insert.t index 236bb97..af74436 100644 --- a/lib/query/tests/insert.t +++ b/lib/query/tests/insert.t @@ -110,7 +110,8 @@ Any value can be omitted and will be replaced by the default value: {"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. +is only functionnal; this shall not block the creation of the content in the +database. $ tests -insert <<EOF > { @@ -155,14 +156,6 @@ A subcontent is linked to the parent: > "label": {}, > "type": "integer" > }, - > { - > "name": "ref", - > "label": {}, - > "type": { - > "content": "referential", - > "multivaluated": true - > } - > } > ] > } > ], @@ -211,3 +204,195 @@ A subcontent is linked to the parent: {"idx":2} details:3 {"comment":"lorem 2","parent":2} + +In this syntax, external references are declared inside the feature referencing +them. + + $ tests -insert <<EOF + > { + > "content": [ + > { + > "id": "referential", + > "section": [ + > { + > "field": [ + > { + > "name": "description", + > "label": {}, + > "type": "text" + > }, + > ] + > } + > ], + > "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 <<EOF + > { + > "content": [ + > { + > "id": "referential", + > "section": [ + > { + > "field": [ + > { + > "name": "description", + > "label": {}, + > "type": "text" + > }, + > ] + > } + > ], + > "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} + entity:1 + {"comment":2} + +Subcontent are also managed in the same way. + + $ tests -insert <<EOF + > { + > "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 + entity:1 + {} + details:1 + {"parent":1} + details:1 + {"reference":1} + details:1 + {"reference":2} + referential:3 + {} diff --git a/test/insert.ml b/test/insert.ml index eaa132f..70b98d6 100644 --- a/test/insert.ml +++ b/test/insert.ml @@ -14,81 +14,6 @@ let pp : Format.formatter -> t -> unit = (fun formatter (content_id, id, content) -> Format.fprintf formatter "@[<v 2>%s:%Ld@;%s@]" content_id id content)) -(** Read the values to insert in the configuration *) -module Make (S : Decoders.Decode.S) = struct - let ( let* ) = S.( let* ) - let ( let+ ) = S.( let+ ) - - type value = Model.Reference.t Model.Typ.value - - (** The values are encoded in a very simple way, depending of the nature of - the field in the json, we create a property in for text or numeric *) - let value : value S.decoder = - S.one_of - [ - ( "numeric", - S.map (fun v -> Model.Typ.(V (Integer, Int64.of_int v))) S.int ); - ("text", S.map (fun v -> Model.Typ.(V (Text, v))) S.string); - ("other", S.map (fun _ -> Model.Typ.None) S.value); - ] - - type content = Model.Reference.t Model.Content.t - type properties = (string * value) list - type content_to_insert = content * properties list - - let rec properties : - Configuration.Ast.setting -> - string -> - (content * (properties * content_to_insert list) list) S.decoder = - fun conf name -> - (* We are loading the same configuration template, the content is supposed - to exists by definition and will never be None *) - let content = Configuration.Ast.get_content conf name |> Option.get in - let* properties = - S.field_opt_or ~default:[] "values" (S.list (S.key_value_pairs value)) - in - let* subcontents = - S.field_opt_or ~default:[] "values" (S.list (subcontents conf)) - in - let to_insert = List.combine properties subcontents in - S.succeed (content, to_insert) - - and subcontents : - Configuration.Ast.setting -> content_to_insert list S.decoder = - fun conf -> - let* properties = - S.key_value_pairs_seq (fun key -> - S.one_of - [ - ( "subcontent", - fun v -> - match Configuration.Ast.get_content conf key with - | None -> Error (Decoders.Error.make "no content") - | Some subcontent -> - let res = S.list (S.key_value_pairs value) v in - let v = Result.map (fun v -> Some (subcontent, v)) res in - v ); - ("other", fun _ -> Ok None); - ]) - in - let properties = List.filter_map ~f:(fun v -> v) properties in - S.succeed properties - - let content : - Configuration.Ast.setting -> - (content * (properties * content_to_insert list) list) S.decoder = - fun conf -> - let* name = S.field "id" S.string in - properties conf name - - let configuration : - Configuration.Ast.setting -> - (content * (properties * content_to_insert list) list) list S.decoder = - fun conf -> S.field "content" (S.list (content conf)) -end - -module D = Make (Configuration.Json5.Decode) - let query_columns : 'a Model.Content.t -> string = fun content -> let fields = @@ -122,13 +47,35 @@ let query_columns : 'a Model.Content.t -> string = Buffer.contents buff -let query table = +type content = Model.Reference.t Model.Content.t + +let query (table : content) = Caqti_request.Infix.(Caqti_type.(int64) ->! Caqti_type.string) ~oneshot:true ("SELECT json_object(" ^ query_columns table ^ ") from " ^ Model.Content.id table ^ " where id=?") -let insert_and_get_result ?parent db content entry = +let query_values (table : content) (feature : string) = + Caqti_request.Infix.(Caqti_type.(int64) ->* Caqti_type.string) + ~oneshot:true + ("SELECT json_object('" ^ feature ^ "', target) from \"" + ^ Model.Content.id table ^ "." ^ feature ^ "\" where parent=?") + +type value = Model.Reference.t Model.Typ.value +type properties = (string * value) list + +(** [insert_and_get_result db content entry] will insert the value in the + database and return the informations for the content just inserted. + + [content] is the type definition for the element we want to insert [entry] + contains all the values to insert in the database. *) +let insert_and_get_result : + ?parent:int64 -> + Caqti_lwt.connection -> + content -> + properties -> + (string * int64 * string) Lwt.t = + fun ?parent db content entry -> let ( let* ) = Lwt.bind in let* id = Query.insert ?parent db content (fun v -> @@ -140,47 +87,267 @@ let insert_and_get_result ?parent db content entry = let* json = Caqti_lwt.or_fail json_result in Lwt.return (content_id, id, json) +(** Read the values to insert in the configuration *) +module Make (S : Decoders.Decode.S) = struct + let ( let* ) = S.( let* ) + let ( let+ ) = S.( let+ ) + + type content_to_insert = content * properties list + + let ( let@@ ) = Lwt.bind + + (** Load the values associated with the configuration. *) + class loader (db : Caqti_lwt.connection) (conf : Configuration.Ast.setting) = + object (self) + method insert_and_return_references : + content -> properties list Lwt.t -> int64 list Lwt.t = + fun content properties -> + let ( let* ) = Lwt.bind in + let* properties = properties in + Lwt_list.map_s + (fun line -> + let* _, id, _ = insert_and_get_result db content line in + Lwt.return id) + properties + + method value : content -> string -> (string * value) Lwt.t S.decoder = + fun content key -> + ignore content; + S.one_of + [ + ( "numeric", + S.map + (fun v -> + Lwt.return + (key, Model.Typ.(V (Integer, Some (Int64.of_int v))))) + S.int ); + ( "text", + S.map + (fun v -> Lwt.return (key, Model.Typ.(V (Text, Some v)))) + S.string ); + ( "reference", + match Model.Content.find_target content key with + | None -> S.fail "Not a feature" + | Some target_ref -> + let target = Model.Reference.get target_ref in + let* properties = self#properties target in + let sequence = + let@@ properties = properties in + + let@@ _, id, _ = + insert_and_get_result db target properties + in + let reference = + Model.Typ.{ t = target_ref; constraints = None } + in + Lwt.return + ( key, + Model.Typ.( + V (Model.Typ.MonoReference reference, Some id)) ) + in + S.succeed sequence ); + ( "references", + match Model.Content.find_target content key with + | None -> S.fail "Not a feature" + | Some target_ref -> + let target = Model.Reference.get target_ref in + let* properties = self#values target in + let sequence = + let@@ ids = + self#insert_and_return_references target properties + in + let reference = + Model.Typ.{ t = target_ref; constraints = None } + in + Lwt.return + ( key, + Model.Typ.( + Seq + ( Model.Typ.MultiReference reference, + List.to_seq ids )) ) + in + + S.succeed sequence ); + ( "other", + (* If the value is a dictionnary list, consider it as external references *) + S.succeed (Lwt.return (key, Model.Typ.None)) ); + ] + (** The values are encoded in a very simple way, depending of the nature + of the field in the json, we create a property in for text or numeric + *) + + method properties : content -> properties Lwt.t S.decoder = + fun content -> + S.map Lwt.all (S.key_value_pairs_seq (self#value content)) + + method values : content -> properties list Lwt.t S.decoder = + fun content -> S.map Lwt.all (S.list (self#properties content)) + + method load_content : content_to_insert list Lwt.t S.decoder = + let* properties = + S.key_value_pairs_seq (fun key -> + S.one_of + [ + ( "content", + fun v -> + match (Configuration.Ast.get_content conf) key with + | None -> Error (Decoders.Error.make "no content") + | Some subcontent -> + let values = self#values subcontent v in + Result.map + (fun v -> + let content_to_insert = + let@@ v = v in + Lwt.return (subcontent, v) + in + Some content_to_insert) + values ); + ("other", fun _ -> Ok None); + ]) + in + let properties = List.filter_map ~f:(fun v -> v) properties in + S.succeed (Lwt.all properties) + (** Read the content and for each key, check if there is an existing + subcontent with the same name, If this subcontent exists, parse all + the subcontents with all the values and return them. *) + + method root_content : + string -> + (content * (properties * content_to_insert list) list) Lwt.t S.decoder + = + fun name -> + (* In this syntax, the content is supposed to follow the definition + and will never be None *) + let content = Configuration.Ast.get_content conf name |> Option.get in + let* properties = + S.field_opt_or ~default:(Lwt.return []) "values" + (self#values content) + in + + (* Look for subcontents in the given values. The subcontent is + identfied by having a key name equal to the subcontent + identifier. *) + let* subcontents : content_to_insert list list Lwt.t = + S.map Lwt.all + (S.field_opt_or ~default:[] "values" (S.list self#load_content)) + in + let result = + let@@ properties = properties in + let@@ subcontents = subcontents in + + let to_insert = List.combine properties subcontents in + Lwt.return (content, to_insert) + in + S.succeed result + + method content : + (content * (properties * content_to_insert list) list) Lwt.t S.decoder + = + let* name = S.field "id" S.string in + let* properties = self#root_content name in + S.succeed properties + + method configuration : + (content * (properties * content_to_insert list) list) list Lwt.t + S.decoder = + let* content = S.field "content" (S.list self#content) in + let conf = Lwt.all content in + S.succeed conf + end +end + +module D = Make (Configuration.Json5.Decode) + +(** Query all the multireferences tables for the given content and the given id. + Collect all the values and return them in the same json format as the same + content. *) +let collect_references : + Caqti_lwt.connection -> content -> int64 -> 'a list Lwt.t = + fun db content id -> + let module Db = (val db) in + let ( let* ) = Lwt.bind in + let content_id = Model.Content.id content in + + (* Only keep the multivaluated fields *) + let fields = + Seq.filter + (fun field -> + let (T ty) = Model.Field.type_ field in + match ty with Model.Typ.MultiReference _ -> true | _ -> false) + (Model.Content.fields content) + |> List.of_seq + in + let results = + Lwt_list.fold_left_s + (fun acc field -> + let field_name = Model.Field.name field in + let* json_result = + Db.collect_list (query_values content field_name) id + in + let* json = Caqti_lwt.or_fail json_result in + let line = + List.fold_left ~init:acc json ~f:(fun acc json -> + (content_id, id, json) :: acc) + in + Lwt.return line) + [] fields + in + + results + let exec : string list -> t = fun _ -> let stdin = In_channel.input_all stdin in - let ( let* ) = Result.bind in - let* configuration = Configuration.Read_conf.read_string_conf stdin in - let* inserts = - Configuration.Json5.Decode.decode_string - (D.configuration configuration) - stdin - in + let ( let** ) = Result.bind in + let** configuration = Configuration.Read_conf.read_string_conf stdin in Lwt_main.run (let ( let* ) = Lwt.bind in let* db = Common.connect configuration in let module Db = (val db) in - let* insertions = - Lwt_list.fold_left_s - (fun acc (content, entries) -> + let inserts = + Configuration.Json5.Decode.decode_string + (new D.loader db configuration)#configuration stdin + in + match inserts with + | Error err -> Lwt.return_error err + | Ok inserts -> + let* inserts = inserts in + let* insertions = Lwt_list.fold_left_s - (fun acc (entry, subcontents) -> - let* content_id, id, json = - insert_and_get_result db content entry - in - - let acc = (content_id, id, json) :: acc in - - (* Insert the subcontent associated *) + (fun acc (content, entries) -> Lwt_list.fold_left_s - (fun acc (subcontent, entries) -> - let* acc = - Lwt_list.fold_left_s - (fun acc entry -> - let* subcontent_id, id, json = - insert_and_get_result ~parent:id db subcontent entry - in - Lwt.return ((subcontent_id, id, json) :: acc)) - acc entries + (fun acc (entry, subcontents) -> + (* Insert the main content *) + let* content_id, id, json = + insert_and_get_result db content entry in + let acc = (content_id, id, json) :: acc in - Lwt.return acc) - acc subcontents) - acc entries) - [] inserts - in - Lwt.return_ok (List.rev insertions)) + (* Also query the multivaluated references *) + let* ext = collect_references db content id in + let acc = List.append ext acc in + (* Insert the subcontent associated *) + Lwt_list.fold_left_s + (fun acc (subcontent, entries) -> + let* acc = + Lwt_list.fold_left_s + (fun acc entry -> + let* subcontent_id, id, json = + insert_and_get_result ~parent:id db subcontent + entry + in + let acc = (subcontent_id, id, json) :: acc in + + (* Also query the multivaluated references *) + let* ext = collect_references db subcontent id in + let acc = List.append ext acc in + Lwt.return acc) + acc entries + in + + Lwt.return acc) + acc subcontents) + acc entries) + [] inserts + in + Lwt.return_ok (List.rev insertions)) |
