Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
module Table = Catalog.Spi.Schemamodule S = Tablemodule Render = Sql.Private.Render
let direction = function | None -> "" | Some `Asc -> " ASC" | Some `Desc -> " DESC"
let collate = function None -> "" | Some c -> " COLLATE " ^ c
let key (k : S.key) = Render.ident k.column ^ collate k.collation ^ direction k.order
let keys ks = String.concat ", " (List.map key ks)
let index_key = function | S.Column k -> key k | S.Expression e -> e.sql ^ collate e.collation ^ direction e.order
let names ns = String.concat ", " (List.map Render.ident ns)
(* The column the key is written on, where the schema says it is. *)let inline_key (s : S.t) = match s.primary_key with | Some { keys = [ k ]; on_column = true; _ } -> Some k | _ -> None
let on_primary_key (s : S.t) = Option.bind s.primary_key (fun (p : S.primary_key) -> p.on_conflict)
let conflict = function | None -> [] | Some c -> [ ("ON CONFLICT " ^ match (c : S.conflict) with | `Rollback -> "ROLLBACK" | `Abort -> "ABORT" | `Fail -> "FAIL" | `Ignore -> "IGNORE" | `Replace -> "REPLACE"); ]
let action what = function | `No_action -> [] | `Restrict -> [ what ^ " RESTRICT" ] | `Cascade -> [ what ^ " CASCADE" ] | `Set_null -> [ what ^ " SET NULL" ] | `Set_default -> [ what ^ " SET DEFAULT" ]
let default = function | `Value v -> Render.default_clause (Sql.Ast.Lit v) | `Expression sql -> "(" ^ sql ^ ")"
let generated (kind, sql) = Fmt.str "AS (%s) %s" sql (match kind with `Virtual -> "VIRTUAL" | `Stored -> "STORED")
let foreign_key (f : S.foreign_key) = String.concat " " ((Fmt.str "FOREIGN KEY (%s) REFERENCES %s" (names f.columns) (Render.ident f.parent) ^ match f.parent_columns with [] -> "" | cs -> Fmt.str " (%s)" (names cs)) :: action "ON DELETE" f.on_delete @ action "ON UPDATE" f.on_update @ if f.deferred then [ "DEFERRABLE INITIALLY DEFERRED" ] else [])
(* No IF NOT EXISTS: sqlite3 stores the statement from its CREATE keyword with that clause removed, so a statement without it is the text every engine stores and the one a database is compared with. *)let create_table (s : S.t) = let inline = inline_key s in let column (c : S.column) = let pk = match inline with | Some k when Catalog.Ident.equal k.column c.name -> Some k | _ -> None in let flag on w = if on then [ w ] else [] in let primary_key = match pk with | None -> [] | Some { order = None; _ } -> [ "PRIMARY KEY" ] | Some { order = Some `Asc; _ } -> [ "PRIMARY KEY ASC" ] | Some { order = Some `Desc; _ } -> [ "PRIMARY KEY DESC" ] in String.concat " " ((Render.ident c.name :: flag (c.decl_type <> "") c.decl_type) @ primary_key @ (if pk <> None then conflict (on_primary_key s) else []) @ flag (pk <> None && s.autoincrement) "AUTOINCREMENT" @ flag c.not_null "NOT NULL" @ conflict c.on_not_null @ flag c.unique "UNIQUE" @ conflict c.on_unique @ (match c.default with | None -> [] | Some d -> [ "DEFAULT " ^ default d ]) @ (match c.collation with None -> [] | Some n -> [ "COLLATE " ^ n ]) @ match c.generated with None -> [] | Some g -> [ generated g ]) in let table_key = match (inline, s.primary_key) with | None, Some p -> [ String.concat " " (Fmt.str "PRIMARY KEY (%s)" (keys p.keys) :: conflict p.on_conflict); ] | _ -> [] in let uniques = List.map (fun (u : S.unique) -> String.concat " " (("UNIQUE (" ^ keys u.keys ^ ")") :: conflict u.on_conflict)) s.uniques in let checks = List.map (fun c -> "CHECK (" ^ c ^ ")") s.checks in let options = (if s.without_rowid then [ "WITHOUT ROWID" ] else []) @ if s.strict then [ "STRICT" ] else [] in Fmt.str "CREATE TABLE %a (%s)%s" Render.pp_ident s.table (String.concat ", " (List.map column s.columns @ table_key @ uniques @ checks @ List.map foreign_key s.foreign_keys)) (match options with [] -> "" | os -> " " ^ String.concat ", " os)
let index_statement table (i : S.index) = Fmt.str "CREATE %sINDEX %a ON %a (%s)%s" (if i.unique then "UNIQUE " else "") Render.pp_ident i.name Render.pp_ident table (String.concat ", " (List.map index_key i.keys)) (match i.where with None -> "" | Some w -> " WHERE " ^ w)
let sql_of_table (s : S.t) = create_table s :: List.map (index_statement s.table) s.indexes
type def = { name : string; sql : string }type t = { defs : def list; identity : int }
(* The header's version is a signed 32-bit integer and [0] is a new database, so the digest is cut to 31 bits and a zero moved to one. A derivation follows the statements as a line no statement can be. *)let identity_of ?derivation defs = let lines = List.map (fun d -> d.sql) defs in let lines = match derivation with | None -> lines | Some d -> lines @ [ "-- derivation " ^ d ] in let d = Digest.string (String.concat "\n" lines) in let n = Int32.to_int (String.get_int32_be d 0) land 0x7fff_ffff in if n = 0 then 1 else n
let defs_of (s : S.t) = { name = s.table; sql = create_table s } :: List.map (fun (i : S.index) -> { name = i.name; sql = index_statement s.table i }) s.indexes
let v ?derivation tables = if tables = [] then invalid_arg "Sqlite.Schema.v: no table"; let defs = List.concat_map defs_of tables in let rec dup = function | [] -> () | d :: rest -> if List.exists (fun o -> Catalog.Ident.equal o.name d.name) rest then Fmt.invalid_arg "Sqlite.Schema.v: %s is declared twice" d.name; dup rest in dup defs; { defs; identity = identity_of ?derivation defs }
let statements t = List.map (fun d -> d.sql) t.defs
(* A trigger goes before the table it is on and a view before the tables it reads; an index goes with its table, and every table goes. *)let drops objects = let of_kind k = List.filter_map (fun (kind, name) -> if String.equal kind k then Fmt.kstr Option.some "DROP %s %a" (String.uppercase_ascii k) Render.pp_ident name else None) objects in of_kind "trigger" @ of_kind "view" @ of_kind "table"
let identity t = t.identity
type mismatch = | Empty | Missing of { name : string; declared : string } | Undeclared of { name : string; found : string } | Differs of { name : string; found : string; declared : string } | Version of { found : int; declared : int }
(* The columns a CREATE TABLE statement declares, by name, as the engine reads them; an index, or a statement this engine does not parse, declares none. *)let columns sql = List.map (fun (c : Model.column) -> c.name) (Decl.parse_create_table sql)
let kind sql = if String.starts_with ~prefix:"CREATE TABLE" sql then "table" else "index"
let pp_names = Fmt.(list ~sep:comma string)
let without names others = List.filter (fun n -> not (List.exists (Catalog.Ident.equal n) others)) names
(* What a reader acts on is the column that differs, so a table whose columns differ is said by them; a difference only in types or constraints quotes both statements, the whole of what is known. *)let pp_differs ppf ~name ~found ~declared = let found_cols = columns found and declared_cols = columns declared in match (without declared_cols found_cols, without found_cols declared_cols) with | [], [] -> Fmt.pf ppf "%s %s is declared as %S and the database holds %S" (kind declared) name declared found | missing, [] -> Fmt.pf ppf "table %s has no column %a" name pp_names missing | [], extra -> Fmt.pf ppf "table %s has column %a, which the schema does not declare" name pp_names extra | missing, extra -> Fmt.pf ppf "table %s has no column %a, and has column %a, which the schema does \ not declare" name pp_names missing pp_names extra
let pp_mismatch ppf = function | Empty -> Fmt.string ppf "the database holds no schema" | Missing { name; declared } -> Fmt.pf ppf "the database has no %s %s" (kind declared) name | Undeclared { name; found } -> Fmt.pf ppf "the database has %s %s, which the schema does not declare" (kind found) name | Differs { name; found; declared } -> pp_differs ppf ~name ~found ~declared | Version { found; declared } -> Fmt.pf ppf "the database is at schema version %d, and the schema declares %d" found declared
let diff t ~user_version ~found = let find name = List.find_opt (fun (n, _) -> Catalog.Ident.equal n name) in let declared (n, _) = List.exists (fun d -> Catalog.Ident.equal d.name n) t.defs in if found = [] && user_version = 0 then Error Empty else let differs = List.find_map (fun d -> match find d.name found with | None -> Some (Missing { name = d.name; declared = d.sql }) | Some (_, sql) when String.equal sql d.sql -> None | Some (name, sql) -> Some (Differs { name; found = sql; declared = d.sql })) t.defs in match differs with | Some m -> Error m | None -> ( match List.find_opt (fun f -> not (declared f)) found with | Some (name, sql) -> Error (Undeclared { name; found = sql }) | None -> if user_version = t.identity then Ok () else Error (Version { found = user_version; declared = t.identity }) )