(** Generate the insert queries for the different database *) (** 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.field list -> ?filter:(Model.field -> bool) -> Model.content -> 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_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.content; provider : string -> Model.value; k : (unit, Caqti.Error.t) result Lwt.t; } type request = (int64 * int64, unit, [ `Zero ]) Caqti.Template.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 let module Identifier = Model.Identifier in let parent = Identifier.quote Identifier.parent and target = Identifier.quote Identifier.target in match content_type with | Model.Typ.MultiReference _target -> ( let result = provider (Model.Identifier.to_string name) in match result with | Model.Typ.None -> acc | Model.Typ.V _ -> raise Encoder.TypeMismatch | Model.Typ.Seq (field_type', values) -> ( match Model.Typ.eq content_type field_type' with | None -> raise Encoder.TypeMismatch | Some Equal -> let q = Croquette_common.Format.format_string (fun format -> Format.fprintf format "INSERT INTO %s (%s, %s) VALUES (?, ?)" (Identifier.quote (Identifier.dot (Model.Content.id content) name)) parent target) in let request : request = Caqti.Templater.(dynamic T.(t2 int64 int64 -->. unit) q) 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* () = Caqti_lwt.or_fail res in let* res = Db.deallocate request in let* () = Caqti_lwt.or_fail res in Lwt.return res in { acc with k })) | _ -> raise Encoder.TypeMismatch end module Fold = Encoder.Fold (MultiReferencesInsert) (** Insert a row. This syntax use RETURNING ID to get the value we just inserted *) let insert_returning : Caqti_lwt.connection -> Model.content -> (string -> Model.value) -> int64 Lwt.t = fun db content provider -> let module Db = (val db) in let init_fields = match Model.Content.parent content with | None -> [] | Some _ -> Model.Field. [ create (T Integer) [] ~required:true Model.Identifier.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.EncodeParameter.f ()) t ^ ")" and columns = match t with | Intf.T0 -> "DEFAULT" | _ -> "(" ^ (Encoder.InsertTableName.f ()) t ^ ")" in let module Identifier = Model.Identifier in let q = Croquette_common.Format.format_string (fun format -> Format.fprintf format "INSERT INTO %s %s VALUES %s RETURNING ID" (Identifier.quote (Model.Content.id content)) columns insert_template) in let types_param = (Encoder.CaqtiRequest.f ()) t in let request = Caqti.Templater.(direct T.(types_param -->! int64) q) in let ( let* ) = Lwt.bind in let values = (Encoder.DataToCaqtiValues.f provider) 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* 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 *) 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 acc = MultiReferencesInsert. { db; provider; k = Lwt.return_ok (); parent_id = content_id; content } in let MultiReferencesInsert.{ k; _ } = Fold.f acc multi_valuated_fields in let* res = k in let* () = Caqti_lwt.or_fail res in Lwt.return content_id (** Insert an entry for a specific content *) let insert : Caqti_lwt.connection -> Model.content -> ?parent:int64 -> (string -> Model.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 Encoder.TypeMismatch | Some v, Some _ -> ( (* Otherwise update the provider to give a value for the parent *) function | "parent" -> Model.Typ.(V (Integer, Some v)) | other -> provider other) in let module Db = (val db) in match Db.dialect with | Caqti.Template.Dialect.(Sqlite _ | Pgsql _) -> insert_returning db content provider | _ -> raise Not_found let insert_references : Caqti_lwt.connection -> Model.content -> Int64.t -> Model.Identifier.t -> Model.value -> Int64.t Intf.data -> unit Lwt.t = fun db content content_id field_name value data -> let provider : string -> Model.value = function | n when String.equal n (Model.Identifier.to_string field_name) -> value | _ -> Model.Typ.None in let acc = MultiReferencesInsert. { db; provider; k = Lwt.return_ok (); parent_id = content_id; content } in let ( let* ) = Lwt.bind in let MultiReferencesInsert.{ k; _ } = MultiReferencesInsert.f acc data in let* res = k in Caqti_lwt.or_fail res