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