summaryrefslogtreecommitdiff
path: root/lib/query/create.ml
blob: 8dcd10db73551b19ab9e0591dfbdd126a1537dec (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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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 _) ->
        (* References are stored as the id of the target row, in the content
           table or in the dedicated list table *)
        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.Identifier.t -> string =
 fun property dst_table ->
  "FOREIGN KEY("
  ^ Model.Identifier.quote property
  ^ ") REFERENCES "
  ^ Model.Identifier.quote dst_table
  ^ "("
  ^ Model.Identifier.quote Model.Identifier.id
  ^ ")"

(** Create the dedicated table of a static list.

    References to a list point to the [id] of this table, exactly like
    references to a content. The rows themselves come from the list source and
    are not created here. *)
let create_list_table : Caqti_lwt.connection -> Model.List.t -> unit Lwt.t =
 fun db list ->
  let module Db = (val db) in
  let buff = Buffer.create 64 in
  let format = Format.formatter_of_buffer buff in
  let () =
    Format.fprintf format "CREATE TABLE %s@;    @[@[<v>( %a@] )@]"
      (Model.Identifier.quote list.Model.List.id)
      Format.pp_print_string "\"id\" INTEGER PRIMARY KEY"
  in
  Format.pp_print_flush format ();
  let request =
    let open Caqti.Templater in
    direct T.(unit -->. unit) (Buffer.contents buff)
  in
  let* result = Db.exec request () in
  Caqti_lwt.or_fail result

(** 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
      (* The target is the id of a row in the target content table, or in the
         dedicated table of the target list *)
      let target_table =
        match reference.Model.Typ.t with
        | Model.Typ.Content ref ->
            Model.Content.id (Model.Reference.get ref)
        | Model.Typ.List list -> list.Model.List.id
      in
      let fields =
        [
          "\"id\" INTEGER PRIMARY KEY";
          "\"parent\" INTEGER NOT NULL";
          "\"target\" INTEGER NOT NULL";
          get_foreign_statement Model.Identifier.parent
            (Model.Content.id content);
          (* Table constraints must come after the column definitions *)
          get_foreign_statement Model.Identifier.target target_table;
        ]
      in
      let () =
        Format.fprintf format "CREATE TABLE %s@;    @[@[<v>( %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 (Model.Content.id 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 column = Model.Field.name field in
            match reference.Model.Typ.t with
            | Model.Typ.List list ->
                (* The list tables are created before the content tables, so
                   the constraint can be declared directly *)
                let foreign =
                  get_foreign_statement column list.Model.List.id :: foreign
                in
                (foreign, alter_queries)
            | Model.Typ.Content ref -> (
                let dst = Model.Reference.get ref in
                match List.mem ~set:created dst with
                | true ->
                    let foreign =
                      get_foreign_statement column (Model.Content.id 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@;    @[@[<v>( %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
  (* The list tables are created first, so that the content tables can declare
     their foreign keys to the lists directly *)
  let* () =
    Lwt_list.iter_s (create_list_table db) (Configuration.Ast.lists conf)
  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