aboutsummaryrefslogtreecommitdiff
path: root/lib/sql/date.ml
blob: e8933c7920fd88e8ea1489c66a17016c23d07c6c (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
(** Parse a text value into a date *)

let first_day = CalendarLib.Date.make 1899 12 30

let f : Sqlite3.Data.t -> Sqlite3.Data.t -> Sqlite3.Data.t =
 fun str data ->
  match (str, data) with
  | Sqlite3.Data.TEXT format_, Sqlite3.Data.TEXT content -> (
      try
        let date = CalendarLib.Printer.Date.from_fstring format_ content in
        let period =
          CalendarLib.Date.sub date first_day
          |> CalendarLib.Date.Period.nb_days |> Int64.of_int
        in
        Sqlite3.Data.INT period
      with
      | Invalid_argument e ->
          prerr_endline e;
          Sqlite3.Data.NULL)
  | _ ->
      (* If the data is already a date, it should be preserved as is *)
      data

let register : Sqlite3.db -> unit = fun db -> Sqlite3.create_fun2 db "date" f