summaryrefslogtreecommitdiff
path: root/lib/query/insert.ml
blob: 01b2dae66af7be8d05088680219c4f6590b1bf4a (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
(** 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.field list ->
    Intf.t =
 fun ?(init_fields = []) ?filter fields ->
  let fields =
    match filter with None -> fields | Some f -> List.filter f fields
  in

  let fields = init_fields @ fields 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;
    table : Model.Identifier.t;
        (** The table holding the row: a content table, or a list *)
    provider : string -> Value.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 b. 'a t -> (any, b) Intf.data -> 'a t =
   fun ({ db; parent_id; provider; k; table } 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
        | Value.Data.Any d -> (
            match d with
            | Value.Data.None -> acc
            | Value.Data.V (field_type', values) -> (
                match Model.Typ.eq_ocaml 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 table 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 in the given table, then insert the multivalued fields in their
    dedicated tables. This syntax uses RETURNING ID to get the value we just
    inserted *)
let insert_row :
    Caqti_lwt.connection ->
    table:Model.Identifier.t ->
    ?init_fields:Model.field list ->
    Model.field list ->
    (string -> Value.value) ->
    int64 Lwt.t =
 fun db ~table ?(init_fields = []) fields provider ->
  let module Db = (val db) in
  (* Remove the mulivaluated fields from the request because they are
     not inserted in the table directly *)
  let (T t) =
    collect_fields ~init_fields
      ~filter:(fun field ->
        let (T ty) = Model.Field.type_ field in
        match ty with Model.Typ.MultiReference _ -> false | _ -> true)
      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 table) 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* row_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 fields ~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 = row_id; table }
  in
  let MultiReferencesInsert.{ k; _ } = Fold.f acc multi_valuated_fields in
  let* res = k in
  let* () = Caqti_lwt.or_fail res in
  Lwt.return row_id

let insert_returning :
    Caqti_lwt.connection ->
    Model.content ->
    (string -> Value.value) ->
    Model.content Value.t Lwt.t =
 fun db content provider ->
  let init_fields =
    match Model.Content.parent content with
    | None -> []
    | Some _ ->
        Model.Field.
          [ create (T Integer) [] ~required:true Model.Identifier.parent ]
  in
  let ( let* ) = Lwt.bind in
  let* id =
    insert_row db ~table:(Model.Content.id content) ~init_fields
      (List.of_seq (Model.Content.fields content))
      provider
  in
  Lwt.return (Value.v content id)

(** Insert an entry for a specific content *)
let insert :
    Caqti_lwt.connection ->
    Model.content ->
    ?parent:Model.content Value.t ->
    (string -> Value.value) ->
    Model.content Value.t 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 *)
        let parent_id =
          match Value.get v Value.id_ref with
          | Some parent_id -> parent_id
          | None -> raise Encoder.TypeMismatch
        in
        function
        | "parent" -> Value.single (Model.Typ.Integer, Some parent_id)
        | 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

(** Insert a row in the dedicated table of a list, and return it.

    Like [insert], the [provider] is called with the name of each field of the
    list to get its value. Multivalued fields are inserted in their own
    dedicated table, with the parent pointing to the list row. *)
let insert_list :
    Caqti_lwt.connection ->
    Model.list ->
    (string -> Value.value) ->
    Model.list Value.t Lwt.t =
 fun db list provider ->
  let module Db = (val db) in
  match Db.dialect with
  | Caqti.Template.Dialect.(Sqlite _ | Pgsql _) ->
      let ( let* ) = Lwt.bind in
      let* id =
        insert_row db ~table:list.Model.DataList.id list.Model.DataList.fields
          provider
      in
      Lwt.return (Value.v list id)
  | _ -> raise Not_found

let insert_references :
    Caqti_lwt.connection ->
    Model.content ->
    Int64.t ->
    Model.Identifier.t ->
    Value.value ->
    (Int64.t, _) Intf.data ->
    unit Lwt.t =
 fun db content content_id field_name value data ->
  let provider : string -> Value.value = function
    | n when String.equal n (Model.Identifier.to_string field_name) -> value
    | _ -> Value.none
  in
  let acc =
    MultiReferencesInsert.
      {
        db;
        provider;
        k = Lwt.return_ok ();
        parent_id = content_id;
        table = Model.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