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.Identifier.quote (Model.Field.name field); t ]) ty type foreign = { src_table : Model.Identifier.t; src_column : Model.Identifier.t; dst_table : Model.Identifier.t; dst_column : Model.Identifier.t; } (** 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 : Model.Identifier.t -> Model.content -> string = fun property content -> "FOREIGN KEY(" ^ Model.Identifier.quote property ^ ") REFERENCES " ^ Model.Identifier.quote (Model.Content.id content) ^ "(" ^ Model.Identifier.quote Model.Identifier.id ^ ")" (** Create the dedicated table required for multivaluated fields *) let create_external_reference_table : Caqti_lwt.connection -> Model.content -> foreign list -> Model.field -> 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 Model.Identifier.parent content; get_foreign_statement Model.Identifier.target target; ] in let () = Format.fprintf format "CREATE TABLE %s@; @[@[( %a@] )@]" (Model.Identifier.quote (Model.Identifier.dot (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 = let open Caqti.Templater in direct T.(unit -->. unit) 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.content list -> Model.content -> (foreign list * Model.content list) Lwt.t = fun db (alter_queries, created) content -> let module Identifier = Model.Identifier in (* 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 = Model.Identifier.parent; dst_table = Model.Content.id p; dst_column = Model.Identifier.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 Identifier.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 = Model.Identifier.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@] )@]" (Identifier.quote (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 = let open Caqti.Templater in direct T.(unit -->. unit) 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 module Db = (val db) in let module Identifier = Model.Identifier in (* Identifiers cannot be passed as query parameters, so the statement is built with validated and quoted identifiers for each constraint. *) Lwt_list.iter_s (fun foreign -> let request_str = "ALTER TABLE " ^ Identifier.quote foreign.src_table ^ " ADD CONSTRAINT FOREIGN KEY(" ^ Identifier.quote foreign.src_column ^ ") REFERENCES " ^ Identifier.quote foreign.dst_table ^ "(" ^ Identifier.quote foreign.dst_column ^ ")" in let request = let open Caqti.Templater in direct T.(unit -->. unit) request_str in let* result = Db.exec request () in Caqti_lwt.or_fail result) foreigns 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 Db.dialect with | Caqti.Template.Dialect.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 | _ -> add_foreign_statement db foreign