aboutsummaryrefslogtreecommitdiff
path: root/lib/sql/t.ml
blob: 2297125a87c680ab9aa5e340edf3f70ea475a09b (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
exception SqlError of Sqlite3.Rc.t

type 'a t = Sqlite3.db
type 'a result = ('a, exn) Result.t

let to_result : Sqlite3.Rc.t -> unit result = function
  | Sqlite3.Rc.OK | Sqlite3.Rc.DONE -> Ok ()
  | res -> Error (SqlError res)

let begin_transaction : Sqlite3.db -> unit result =
 fun db ->
  let query = "BEGIN" in
  Sqlite3.exec db query |> to_result

let commit : Sqlite3.db -> unit result =
 fun db ->
  let query = "COMMIT" in
  Sqlite3.exec db query |> to_result

let rollback : Sqlite3.db -> unit result =
 fun db ->
  let query = "ROLLBACK" in
  Sqlite3.exec db query |> to_result

let savepoint : Sqlite3.db -> string -> unit result =
 fun db name ->
  let query = "SAVEPOINT " ^ name in
  Sqlite3.exec db query |> to_result

let release : Sqlite3.db -> string -> unit result =
 fun db name ->
  let query = "RELEASE SAVEPOINT " ^ name in
  Sqlite3.exec db query |> to_result

let finalize : Sqlite3.stmt -> unit result =
 fun statement -> to_result (Sqlite3.finalize statement)

let reset : Sqlite3.stmt -> unit result =
 fun statement -> to_result (Sqlite3.reset statement)

let of_datatype = function
  | ImportDataTypes.Value.Float f -> Sqlite3.Data.FLOAT f
  | ImportDataTypes.Value.Integer i -> Sqlite3.Data.INT (Int64.of_int i)
  | ImportDataTypes.Value.Null -> Sqlite3.Data.NULL
  | ImportDataTypes.Value.Error _ -> Sqlite3.Data.NULL
  | ImportDataTypes.Value.Content s -> Sqlite3.Data.TEXT s

let to_datatype : Sqlite3.Data.t -> ImportDataTypes.Value.t = function
  | Sqlite3.Data.NONE | Sqlite3.Data.NULL -> ImportDataTypes.Value.Null
  | Sqlite3.Data.INT i -> ImportDataTypes.Value.Integer (Int64.to_int i)
  | Sqlite3.Data.FLOAT f -> ImportDataTypes.Value.Float f
  | Sqlite3.Data.TEXT t | Sqlite3.Data.BLOB t -> ImportDataTypes.Value.Content t