package sihl

  1. Overview
  2. Docs
The Sihl web framework

Install

Dune Dependency

Authors

Maintainers

Sources

2.0.0.tar.gz
md5=8cde8cf002a145dc3223568924a34ba3
sha512=d61b776017feeb5e0a24624fa4c5db6f30d7c7badd8c696283cf51baf0c36d4d3335fee0fdf835e6d7289ce51d36439463014ce3b25a2eb15d05f331c094aa86

doc/src/sihl/database.ml.html

Source file database.ml

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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
include Contract_database

let log_src = Logs.Src.create "sihl.service.database"

module Logs = (val Logs.src_log log_src : Logs.LOG)

let main_pool_ref
    : (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t option ref
  =
  ref None
;;

let pools
    : (string, (Caqti_lwt.connection, Caqti_error.t) Caqti_lwt.Pool.t) Hashtbl.t
  =
  Hashtbl.create 100
;;

type 'a prepared_search_request =
  { asc_request :
      (int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t
  ; desc_request :
      (int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t
  ; filter_asc_request :
      (string * int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t
  ; filter_desc_request :
      (string * int * int, int * 'a, [ `Many | `One | `Zero ]) Caqti_request.t
  ; format_filter : string -> string
  }

let prepare_requests _ _ _ = failwith "prepare_requests deprecated"
let default_format_filter keyword = "%" ^ keyword ^ "%"

let prepare_search_request
    ~search_query
    ~filter_fragment
    ?(sort_by_field = "id")
    ?(format_filter = default_format_filter)
    output_type
    : 'a prepared_search_request
  =
  let output_type = Caqti_type.(tup2 int output_type) in
  let asc_request =
    let input_type = Caqti_type.(tup2 int int) in
    let query =
      Printf.sprintf
        "%s ORDER BY %s ASC %s"
        search_query
        sort_by_field
        "LIMIT $1 OFFSET $2"
    in
    Caqti_request.collect input_type output_type query
  in
  let desc_request =
    let input_type = Caqti_type.(tup2 int int) in
    let query =
      Printf.sprintf
        "%s ORDER BY %s DESC %s"
        search_query
        sort_by_field
        "LIMIT $1 OFFSET $2"
    in
    Caqti_request.collect input_type output_type query
  in
  let filter_asc_request =
    let input_type = Caqti_type.(tup3 string int int) in
    let query =
      Printf.sprintf
        "%s %s ORDER BY %s ASC %s"
        search_query
        filter_fragment
        sort_by_field
        "LIMIT $2 OFFSET $3"
    in
    Caqti_request.collect input_type output_type query
  in
  let filter_desc_request =
    let input_type = Caqti_type.(tup3 string int int) in
    let query =
      Printf.sprintf
        "%s %s ORDER BY %s DESC %s"
        search_query
        filter_fragment
        sort_by_field
        "LIMIT $2 OFFSET $3"
    in
    Caqti_request.collect input_type output_type query
  in
  { asc_request
  ; desc_request
  ; filter_asc_request
  ; filter_desc_request
  ; format_filter
  }
;;

let run_request _ _ _ _ _ = failwith "prepare_requests deprecated"

type config =
  { url : string
  ; pool_size : int option
  ; skip_default_pool_creation : bool option
  ; choose_pool : string option
  }

let config url pool_size skip_default_pool_creation choose_pool =
  { url; pool_size; skip_default_pool_creation; choose_pool }
;;

let schema =
  let open Conformist in
  make
    [ string
        ~meta:
          "The database connection url. This is the only string that Sihl \
           needs to connect to a database."
        "DATABASE_URL"
    ; optional
        ~meta:
          "The amount of connections in the database connection pool that Sihl \
           manages. If the number is too high, the server might struggle. If \
           the number is too low, your Sihl app performs badly. This can be \
           configured using DATABASE_POOL_SIZE and the default is 5."
        (int ~default:5 "DATABASE_POOL_SIZE")
    ; optional
        ~meta:
          "By default, Sihl assumes one database connection pool to connect to \
           one default application database. This value can be set to [true] \
           to skip the creation of the default connection pool, which is \
           configured using env variables. This is useful if an application \
           uses multiple databases. By default, the value is [false]."
        (bool ~default:false "DATABASE_SKIP_DEFAULT_POOL_CREATION")
    ; optional
        ~meta:
          "The database connection pool name that should be used by default. \
           The main pool is used if no value is set. This value can be \
           overriden by using the pool name in the service context."
        (string "DATABASE_CHOOSE_POOL")
    ]
    config
;;

let print_pool_usage pool =
  let n_connections = Caqti_lwt.Pool.size pool in
  let max_connections =
    Option.value (Core_configuration.read schema).pool_size ~default:10
  in
  Logs.debug (fun m -> m "Pool usage: %i/%i" n_connections max_connections)
;;

let fetch_pool ?(ctx = []) () =
  let chosen_pool_name_ctx = CCList.assoc_opt ~eq:String.equal "pool" ctx in
  let chosen_pool_name_env = (Core_configuration.read schema).choose_pool in
  let chosen_pool_name =
    match chosen_pool_name_ctx, chosen_pool_name_env with
    | Some chosen_pool_name, _ -> Some chosen_pool_name
    | None, Some chosen_pool_name -> Some chosen_pool_name
    | None, None -> None
  in
  let chosen_pool = Option.bind chosen_pool_name (Hashtbl.find_opt pools) in
  match chosen_pool, !main_pool_ref with
  | Some pool, _ -> pool
  | None, Some pool ->
    Logs.debug (fun m -> m "Skipping pool creation, re-using existing pool");
    pool
  | None, None ->
    if Option.value
         (Core_configuration.read schema).skip_default_pool_creation
         ~default:false
    then
      Logs.warn (fun m ->
          m
            "DATABASE_SKIP_DEFAULT_POOL_CREATION was set to true, but no pool \
             was defined for querying.");
    let pool_size =
      Option.value (Core_configuration.read schema).pool_size ~default:10
    in
    Logs.info (fun m -> m "Create pool with size %i" pool_size);
    (Core_configuration.read schema).url
    |> Uri.of_string
    |> Caqti_lwt.connect_pool ~max_size:pool_size
    |> (function
    | Ok pool ->
      main_pool_ref := Some pool;
      pool
    | Error err ->
      let msg = "Failed to connect to DB pool" in
      Logs.err (fun m -> m "%s %s" msg (Caqti_error.show err));
      raise (Contract_database.Exception ("Failed to create pool: " ^ msg)))
;;

let add_pool ?(pool_size = 10) name database_url =
  database_url
  |> Uri.of_string
  |> Caqti_lwt.connect_pool ~max_size:pool_size
  |> function
  | Ok pool ->
    if Option.is_some (Hashtbl.find_opt pools name)
    then (
      let msg =
        Format.sprintf "Connection pool with name '%s' exists already" name
      in
      Logs.err (fun m -> m "%s" msg);
      raise (Contract_database.Exception ("Failed to create pool: " ^ msg)))
    else Hashtbl.add pools name pool
  | Error err ->
    let msg = "Failed to connect to DB pool" in
    Logs.err (fun m -> m "%s %s" msg (Caqti_error.show err));
    raise (Contract_database.Exception ("Failed to create pool: " ^ msg))
;;

let raise_error err =
  match err with
  | Error err -> raise @@ Contract_database.Exception (Caqti_error.show err)
  | Ok result -> result
;;

let transaction ?ctx f =
  let pool = fetch_pool ?ctx () in
  print_pool_usage pool;
  let%lwt result =
    Caqti_lwt.Pool.use
      (fun connection ->
        Logs.debug (fun m -> m "Fetched connection from pool");
        let (module Connection : Caqti_lwt.CONNECTION) = connection in
        let%lwt start_result = Connection.start () in
        match start_result with
        | Error msg ->
          Logs.debug (fun m ->
              m "Failed to start transaction: %s" (Caqti_error.show msg));
          Lwt.return @@ Error msg
        | Ok () ->
          Logs.debug (fun m -> m "Started transaction");
          Lwt.catch
            (fun () ->
              let%lwt result = f connection in
              let%lwt commit_result = Connection.commit () in
              match commit_result with
              | Ok () ->
                Logs.debug (fun m -> m "Successfully committed transaction");
                Lwt.return @@ Ok result
              | Error error ->
                Logs.err (fun m ->
                    m
                      "Failed to commit transaction: %s"
                      (Caqti_error.show error));
                Lwt.fail
                @@ Contract_database.Exception "Failed to commit transaction")
            (fun e ->
              let%lwt rollback_result = Connection.rollback () in
              match rollback_result with
              | Ok () ->
                Logs.debug (fun m -> m "Successfully rolled back transaction");
                Lwt.fail e
              | Error error ->
                Logs.err (fun m ->
                    m
                      "Failed to rollback transaction: %s"
                      (Caqti_error.show error));
                Lwt.fail
                @@ Contract_database.Exception "Failed to rollback transaction"))
      pool
  in
  match result with
  | Ok result -> Lwt.return result
  | Error error ->
    let msg = Caqti_error.show error in
    Logs.err (fun m -> m "%s" msg);
    Lwt.fail (Contract_database.Exception msg)
;;

let transaction' ?ctx f = transaction ?ctx f |> Lwt.map raise_error

let run_search_request
    ?ctx
    (r : 'a prepared_search_request)
    (sort : [ `Asc | `Desc ])
    (filter : string option)
    ~(limit : int)
    ~(offset : int)
  =
  transaction' ?ctx (fun connection ->
      let module Connection = (val connection : Caqti_lwt.CONNECTION) in
      let%lwt result =
        match sort, filter with
        | `Asc, None -> Connection.collect_list r.asc_request (limit, offset)
        | `Desc, None -> Connection.collect_list r.desc_request (limit, offset)
        | `Asc, Some filter ->
          Connection.collect_list
            r.filter_asc_request
            (r.format_filter filter, limit, offset)
        | `Desc, Some filter ->
          Connection.collect_list
            r.filter_desc_request
            (r.format_filter filter, limit, offset)
      in
      let things = Result.map (List.map snd) result in
      let total =
        Result.map
          (fun e ->
            e |> List.map fst |> CCList.head_opt |> Option.value ~default:0)
          result
      in
      CCResult.both things total |> Lwt.return)
;;

let query ?ctx f =
  let pool = fetch_pool ?ctx () in
  print_pool_usage pool;
  let%lwt result =
    Caqti_lwt.Pool.use
      (fun connection ->
        let module Connection = (val connection : Caqti_lwt.CONNECTION) in
        f connection |> Lwt.map Result.ok)
      pool
  in
  match result with
  | Ok result -> Lwt.return result
  | Error error ->
    let msg = Caqti_error.show error in
    Logs.err (fun m -> m "%s" msg);
    Lwt.fail (Contract_database.Exception msg)
;;

let query' ?ctx f = query ?ctx f |> Lwt.map raise_error

let find_opt ?ctx request input =
  query' ?ctx (fun connection ->
      let module Connection = (val connection : Caqti_lwt.CONNECTION) in
      Connection.find_opt request input)
;;

let find ?ctx request input =
  query' ?ctx (fun connection ->
      let module Connection = (val connection : Caqti_lwt.CONNECTION) in
      Connection.find request input)
;;

let collect ?ctx request input =
  query' ?ctx (fun connection ->
      let module Connection = (val connection : Caqti_lwt.CONNECTION) in
      Connection.collect_list request input)
;;

let exec ?ctx request input =
  query' ?ctx (fun connection ->
      let module Connection = (val connection : Caqti_lwt.CONNECTION) in
      Connection.exec request input)
;;

let used_database () =
  let host =
    (Core_configuration.read schema).url |> Uri.of_string |> Uri.host
  in
  match host with
  | Some "mariadb" -> Some Contract_database.MariaDb
  | Some "mysql" -> Some Contract_database.MariaDb
  | Some "postgresql" | Some "postgres" | Some "pg" ->
    Some Contract_database.PostgreSql
  | Some not_supported ->
    Logs.warn (fun m -> m "Unsupported database %s found" not_supported);
    None
  | None -> None
;;

(* Service lifecycle *)

let start () =
  let skip_default_pool_creation =
    Option.value
      (Core_configuration.read schema).skip_default_pool_creation
      ~default:false
  in
  if skip_default_pool_creation
  then Lwt.return ()
  else (
    (* Make sure the default database is online when starting service. *)
    let _ = fetch_pool () in
    Lwt.return ())
;;

let stop () = Lwt.return ()

let lifecycle =
  Core_container.create_lifecycle Contract_database.name ~start ~stop
;;

let register () =
  let configuration = Core_configuration.make ~schema () in
  Core_container.Service.create ~configuration lifecycle
;;
OCaml

Innovation. Community. Security.