Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(* [running] is the program's own count (Vdbe.nChange), [last] what changes() answers (sqlite3.nChange), [total] what total_changes() answers (sqlite3.nTotalChange), [last_rowid] what last_insert_rowid() answers (sqlite3.lastRowid). [txn] is whether a transaction is open and what opened it (sqlite3.autoCommit, sqlite3.isTransactionSavepoint), and [savepoints] the open savepoints, innermost first (sqlite3.pSavepoint), each named or, for a span the host runs, unnamed. [resolved] is the resolution the statement's violation was raised under, the P2 operand of its OP_Halt. [frame] is the running trigger program's (VdbeFrame), and [recursive_triggers] the flag of that name (SQLITE_RecTriggers). [fk_statement] is the statement's count of violations of immediate foreign keys (Vdbe.nFkConstraint), [fk_deferred] and [fk_deferred_imm] the transaction's of deferred ones and of immediate ones deferred by [defer_all] (nDeferredCons, nDeferredImmCons, SQLITE_DeferFKs), and [foreign_keys] the flag that enforces them (SQLITE_ForeignKeys). Each savepoint keeps the deferred counts it found, which a rollback to it gives back. *)type txn = Autocommit | Begun | By_savepoint
type frame = { scope : Query.binding list; orconf : Ast.insert_conflict; depth : int; running : string list;}
let top = { scope = []; orconf = Unspecified; depth = 0; running = [] }
type counter = { name : string; mutable seq : int64; stored : (int64 * int64) option;}
type savepoint = { name : string option; deferred : int; deferred_imm : int }
type t = { catalog : Catalog.t; recursion_cap : int; mutable running : int; mutable last : int; mutable total : int; mutable last_rowid : int64; mutable txn : txn; mutable savepoints : savepoint list; mutable resolved : Ast.insert_conflict; mutable frame : frame; mutable recursive_triggers : bool; mutable fk_statement : int; mutable fk_deferred : int; mutable fk_deferred_imm : int; mutable defer_all : bool; mutable foreign_keys : bool; table_function : t -> string -> Func.table_function option; mutable counters : counter list;}
let v ?(recursion_cap = Query.default_recursion_cap) ?(table_function = fun _ _ -> None) catalog = if recursion_cap < 1 then Fmt.invalid_arg "recursion_cap %d is not positive" recursion_cap; { catalog; recursion_cap; running = 0; last = 0; total = 0; last_rowid = 0L; txn = Autocommit; savepoints = []; resolved = Unspecified; frame = top; recursive_triggers = false; fk_statement = 0; fk_deferred = 0; fk_deferred_imm = 0; defer_all = false; foreign_keys = false; table_function; counters = []; }
let catalog t = t.catalog
let pp ppf t = Fmt.pf ppf "connection(%a)" Fmt.(list ~sep:(any ",") string) (Catalog.Spi.tables t.catalog)
let recursion_cap t = t.recursion_caplet changes t = Int64.of_int t.lastlet total_changes t = Int64.of_int t.totallet last_insert_rowid t = t.last_rowidlet set_last_insert_rowid t r = t.last_rowid <- r
(* A builtin is looked up at each call, so a name that is none of the three allocates nothing. *)let table_function t name = t.table_function t namelet counters t = t.counterslet set_counters t l = t.counters <- l
let call t name = match match name with | "changes" -> Some changes | "total_changes" -> Some total_changes | "last_insert_rowid" -> Some last_insert_rowid | _ -> None with | None -> None | Some count -> Some (function | [] -> Catalog.Value.Int (count t) | _ -> Catalog.Error.fail_prepare "wrong number of arguments to function %s()" name)
let start t = t.running <- 0; t.resolved <- Unspecified; t.fk_statement <- 0
let add t n = t.running <- t.running + n
let set t n = t.last <- n; t.total <- t.total + n
let publish t = set t t.running; t.running <- 0
let discard t = set t 0; t.running <- 0
(* {1 Trigger programs} *)
let current t = t.framelet recursive_triggers t = t.recursive_triggerslet set_recursive_triggers t on = t.recursive_triggers <- on
(* {1 Foreign keys} *)
(* vdbe.c, OP_FkCounter: a deferred key counts into the transaction's count, any other into the one of keys defer_foreign_keys defers while it is on, else into the statement's. *)let count_violations t ~deferred n = if deferred then t.fk_deferred <- t.fk_deferred + n else if t.defer_all then t.fk_deferred_imm <- t.fk_deferred_imm + n else t.fk_statement <- t.fk_statement + n
(* vdbe.c, OP_FkIfZero with P1 the key's isDeferred. *)let no_violations t ~deferred = t.fk_deferred_imm = 0 && if deferred then t.fk_deferred = 0 else t.fk_statement = 0
(* vdbeaux.c, sqlite3VdbeCheckFkDeferred. *)let deferred_violated t = t.fk_deferred + t.fk_deferred_imm > 0let defer_foreign_keys t = t.defer_all
type counts = { statement : int; deferred : int; deferred_imm : int }
let counts t = { statement = t.fk_statement; deferred = t.fk_deferred; deferred_imm = t.fk_deferred_imm; }
let forget_deferred t = t.fk_deferred <- 0; t.fk_deferred_imm <- 0
(* pragma.c, PragTyp_FLAG: turning SQLITE_DeferFKs off forgets both deferred counts. *)let set_defer_foreign_keys t on = t.defer_all <- on; if not on then forget_deferred t
(* main.c, sqlite3RollbackAll, and vdbeaux.c, sqlite3VdbeHalt once the commit is made. *)let end_foreign_keys t = forget_deferred t; t.defer_all <- false
let foreign_keys t = t.foreign_keys
(* pragma.c, PragTyp_FLAG: SQLITE_ForeignKeys is masked out of the change while a transaction is open. *)let set_foreign_keys t on = if t.txn = Autocommit then t.foreign_keys <- on
(* SQLITE_MAX_TRIGGER_DEPTH (sqliteLimit.h), the frames OP_Program allows on the stack. *)let max_depth = 1000
let program ?name t ~scope ~orconf f = let outer = t.frame in if outer.depth >= max_depth then Catalog.Error.fail_runtime "triggers nested too deep"; let names = match name with Some n -> n :: outer.running | None -> outer.running in t.frame <- { scope; orconf; depth = outer.depth + 1; running = names }; let running = t.running and last = t.last and last_rowid = t.last_rowid in t.running <- 0; let restore () = t.frame <- outer; t.running <- running; t.last <- last; t.last_rowid <- last_rowid in match f () with | r -> (* OP_Halt of a sub-program publishes what is left before the frame is restored *) t.total <- t.total + t.running; restore (); r | exception e -> let bt = Printexc.get_raw_backtrace () in restore (); Printexc.raise_with_backtrace e bt
(* {1 Transactions} *)
module Spi = Catalog.Spi
let lock : Ast.transaction_type -> Spi.lock = function | Deferred -> `Deferred | Immediate -> `Immediate | Exclusive -> `Exclusive
let autocommit t = t.txn = Autocommit
let begin_ t kind = if t.txn <> Autocommit then Catalog.Error.fail_runtime "cannot start a transaction within a transaction"; Spi.begin_transaction t.catalog (lock kind); t.txn <- Begun
(* A transaction's end forgets its deferred counts and turns defer_foreign_keys off (main.c, sqlite3RollbackAll; vdbeaux.c, sqlite3VdbeHalt once the commit is made). *)let ended t = t.txn <- Autocommit; t.savepoints <- []; end_foreign_keys t
(* A commit the store refused before anything ended leaves the transaction open, for a later COMMIT to try again (vdbe.c, OP_AutoCommit on SQLITE_BUSY); any other failure ended it ({!Catalog.Spi.commit}). *)let left_open = function | Catalog.Error (Busy _ | Constraint _) -> true | _ -> false
(* A commit is refused before anything ends while a deferred foreign key is violated, and the transaction stays open for the statement that repairs it (vdbeaux.c, sqlite3VdbeCheckFkDeferred; vdbe.c, OP_AutoCommit and OP_Savepoint). *)let end_by_commit t = if deferred_violated t then Catalog.Error.fail (Constraint Foreign_key); match Spi.commit t.catalog with | () -> ended t | exception e -> let bt = Printexc.get_raw_backtrace () in if not (left_open e) then ended t; Printexc.raise_with_backtrace e bt
let end_by_rollback t = match Spi.rollback t.catalog with | () -> ended t | exception e -> let bt = Printexc.get_raw_backtrace () in ended t; Printexc.raise_with_backtrace e bt
(* A savepoint with no name is a nested transaction of the host's in flight, as a statement is: the transaction cannot end under it (vdbe.c, OP_AutoCommit, "SQL statements in progress"). *)let in_flight t = List.exists (fun s -> Option.is_none s.name) t.savepoints
let commit t = if t.txn = Autocommit then Catalog.Error.fail_runtime "cannot commit - no transaction is active"; if in_flight t then Catalog.Error.fail_runtime "cannot commit transaction - SQL statements in progress"; end_by_commit t
let rollback t = if t.txn = Autocommit then Catalog.Error.fail_runtime "cannot rollback - no transaction is active"; if in_flight t then Catalog.Error.fail_runtime "cannot rollback transaction - SQL statements in progress"; end_by_rollback t
(* The savepoint [name] opened over the counts the connection holds now. *)let mark t name = { name; deferred = t.fk_deferred; deferred_imm = t.fk_deferred_imm }
(* A SAVEPOINT outside a transaction begins one, deferred, which releasing that savepoint commits (vdbe.c, OP_Savepoint). *)let savepoint t name = let began = t.txn = Autocommit in if began then begin Spi.begin_transaction t.catalog `Deferred; t.txn <- By_savepoint end; match Spi.savepoint t.catalog with | () -> t.savepoints <- mark t (Some name) :: t.savepoints | exception e -> let bt = Printexc.get_raw_backtrace () in if began then end_by_rollback t; Printexc.raise_with_backtrace e bt
(* The number of savepoints opened after [name], the savepoint itself and the ones opened before it. A savepoint with no name stands between [name] and anything run inside it. *)let split t name = let rec go inner = function | [] | { name = None; _ } :: _ -> Catalog.Error.fail_runtime "no such savepoint: %s" name | ({ name = Some s; _ } as sp) :: below when Catalog.Ident.equal s name -> (inner, sp, below) | _ :: rest -> go (inner + 1) rest in go 0 t.savepoints
let release_n t n = for _ = 1 to n do Spi.release t.catalog done
let release t name = let inner, _, below = split t name in if below = [] && t.txn = By_savepoint then end_by_commit t else begin release_n t (inner + 1); t.savepoints <- below end
let restore t (sp : savepoint) = t.fk_deferred <- sp.deferred; t.fk_deferred_imm <- sp.deferred_imm
let rollback_to t name = let inner, sp, below = split t name in release_n t inner; Spi.rollback_to t.catalog; restore t sp; t.savepoints <- sp :: below
let nested t f = if t.txn = Autocommit then invalid_arg "Sql.Private.Connection.nested: no transaction is open"; Spi.savepoint t.catalog; let sp = mark t None in t.savepoints <- sp :: t.savepoints; let close () = t.savepoints <- List.tl t.savepoints in match f () with | r -> Spi.release t.catalog; close (); r | exception e -> let bt = Printexc.get_raw_backtrace () in Spi.rollback_to t.catalog; Spi.release t.catalog; restore t sp; close (); Printexc.raise_with_backtrace e bt
type undo = [ `Row | `Statement | `Transaction ]
let undo_scope : Ast.insert_conflict -> undo = function | Fail -> `Row | Rollback -> `Transaction | Unspecified | Abort | Ignore | Replace -> `Statement
let resolved t = t.resolved
let fail t (res : Ast.insert_conflict) c = t.resolved <- (match res with | Fail -> Fail | Rollback -> Rollback | Unspecified | Abort | Ignore | Replace -> Abort); Catalog.Error.fail (Constraint c)
(* Whether the statement leaves a foreign key violated: its own count, and the connection's where the statement is its own transaction ([own]), whose end is the commit they are judged at too. *)let violated t ~own = t.fk_statement > 0 || (own && deferred_violated t)
(* The statement's own transaction is committed, or undone where the store refuses the commit (vdbeaux.c, sqlite3VdbeHalt); either way it ends. *)let commit_own t = match Spi.commit t.catalog with | () -> end_foreign_keys t | exception e -> let bt = Printexc.get_raw_backtrace () in if left_open e then Spi.rollback t.catalog; end_foreign_keys t; Printexc.raise_with_backtrace e bt
let rollback_own t = Spi.rollback t.catalog; end_foreign_keys t
(* A statement runs no transaction verb, so the savepoint it runs in has no name for the connection to keep; the deferred counts it found are held here, for an undo of the statement to give back. The foreign keys are judged once the statement has written everything, its triggers and foreign-key actions included, inside its undo: ABORT, whatever the statement's OR clause, and over the error of a statement that stopped under FAIL (vdbeaux.c, sqlite3VdbeHalt, the sqlite3VdbeCheckFkImmediate and sqlite3VdbeCheckFkDeferred calls). *)let atomic t f = let own = t.txn = Autocommit in let deferred = t.fk_deferred and deferred_imm = t.fk_deferred_imm in if own then Spi.begin_transaction t.catalog `Immediate else Spi.savepoint t.catalog; match match f () with | r -> if violated t ~own then fail t Abort Foreign_key; r | exception Catalog.Error _ when undo_scope t.resolved = `Row && violated t ~own -> fail t Abort Foreign_key with | r -> if own then commit_own t else Spi.release t.catalog; r | exception e -> let bt = Printexc.get_raw_backtrace () in (match (undo_scope t.resolved, own) with | `Row, true -> commit_own t | `Row, false -> Spi.release t.catalog | (`Statement | `Transaction), true -> rollback_own t | `Statement, false -> Spi.rollback_to t.catalog; Spi.release t.catalog; t.fk_deferred <- deferred; t.fk_deferred_imm <- deferred_imm | `Transaction, false -> end_by_rollback t); Printexc.raise_with_backtrace e bt
let close t = if t.txn <> Autocommit then end_by_rollback t
(* {1 Statements} *)
let reads_database ~sets_connection : Ast.stmt -> bool = function | Select s -> Resolve.table_names s <> [] | Pragma p -> not (sets_connection p) | Begin _ | Commit | Rollback | Savepoint _ | Release _ | Rollback_to _ -> false | Explain _ | Insert _ | Delete _ | Update _ | Create_table _ | Create_table_as _ | Create_index _ | Create_view _ | Create_trigger _ | Drop _ | Alter_table _ | Vacuum _ | Analyze -> true
(* A statement that read the database outside a transaction ended the read transaction it ran in (vdbeaux.c, sqlite3VdbeHalt). *)let end_read t = if t.txn = Autocommit then end_foreign_keys t