summaryrefslogtreecommitdiff
path: root/lib/query/create.ml
blob: d34339b9b34a25b563a952c86f6f3ca27d157efe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
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\"@;    @[@[<v>( %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 =
        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.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\"@;    @[@[<v>( %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 =
    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 request_str =
    "ALTER TABLE ? ADD CONSTRAINT FOREIGN KEY(?) REFERENCES ?(?)"
  in
  let request =
    let open Caqti.Templater in
    direct T.(t4 string string string string -->. unit) 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 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