Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(** Database sessions.
[Session] opens and closes databases, loads their schema, makes commits durable, and manages transactions and savepoints. It works on the fields of {!Handle.t} directly, and does not depend on the catalog, the query executor, the write path or DDL. *)
open Handle
(** {1:open Opening and closing} *)
include Session_intf.STATE
val overlay : t -> t(** [overlay t] is a database in memory that reads what the open transaction of [t] reads and keeps its own writes. As {!Sqlite.overlay}. *)
val open_ : sw:Eio.Switch.t -> ?create:bool -> ?read_only:bool -> ?busy_timeout:float -> ?synchronous:synchronous -> ?journal_mode:journal_mode -> ?clock:_ Eio.Time.clock -> ?zone:(int64 -> int) -> Eio.Fs.dir_ty Eio.Path.t -> t(** [open_ ~sw ~create ~read_only ~busy_timeout ~synchronous ~journal_mode ~clock ~zone path] is the database at [path], created if missing and [create] is [true] (the default). It creates no directory; a missing one raises [Eio.Fs.Not_found]. It refuses a file with a [-wal] or [-journal] it cannot read, whatever [create] says. A file the operating system refuses to open for writing, short of naming a directory, opens as a [read_only] one.
A [read_only] handle only reads: its open, reads and {!close} write nothing to the database, log or journal, and every write refuses it ({!check_writable}). While it reads ({!read_op}), checkpoints of the file defer, and it holds SHARED on the file, waiting up to [busy_timeout] seconds (defaults to [0.]) for a writer of another process and raising [Catalog.Error (Busy _)] after that. A WAL read uses the index's shared read mark. Where the index cannot be written, it instead holds WAL_READ_LOCK(0) where available and checks for a checkpoint or log restart across the read.
A writable handle reads as a read-only one does, under SHARED and in WAL mode a read mark, and takes the write session at its first write: EXCLUSIVE in a rollback journal, the WAL-index's WRITE lock in WAL mode. It gives each back at the transaction's end, the log left in place; its cache stands across the interval only while the file and its log are as it left them. A failed session retains its claim and refuses further access until close.
[journal_mode] is the mode of the database; without it, page 1 of an existing file decides and a new file uses [`Wal]. [clock] gives [CURRENT_TIMESTAMP]; without it, wall-clock values are NULL. [zone] is the local offset in seconds east of UTC (defaults to UTC). *)
val moved : t -> bool(** [moved t] is [true] iff the path [t] was opened at no longer names the file [t] reads: it names none, or another file (os_unix.c, fileHasMoved). An in-memory handle, or a closed one, never moved. *)
val close : t -> unit(** [close t] rolls back an open transaction or savepoint, writes what is left, copies the log into the file and removes the log. It creates no switch resource, so [Eio.Switch.on_release] may call it, and it completes in a cancelled fiber ([Eio.Cancel.protect]). It releases the descriptor of the open, deferring its close while a lock of this process stands on the file. Where another handle holds the file past [busy_timeout], the log stays. A read-only handle drops its snapshot and writes no database or recovery log. A second close does nothing. *)
val with_open : sw:Eio.Switch.t -> ?create:bool -> ?read_only:bool -> ?busy_timeout:float -> ?synchronous:synchronous -> ?journal_mode:journal_mode -> ?clock:_ Eio.Time.clock -> ?zone:(int64 -> int) -> Eio.Fs.dir_ty Eio.Path.t -> (t -> 'a) -> 'a(** [with_open ~sw ~create ~read_only ~busy_timeout ~synchronous ~journal_mode ~clock ~zone path f] opens the database at [path], runs [f db] and {!close}s [db] before returning, even if [f] raises. *)
(** {1:durable Durability} *)
val sync : t -> unit(** [sync t] makes the committed writes durable. It does nothing inside a transaction or savepoint, whose work may still be rolled back. *)
val checkpoint_log : ?mode:[ `Passive | `Truncate ] -> t -> unit(** [checkpoint_log ~mode t] is {!Sqlite.checkpoint}. *)
val wal_checkpoint : t -> [ `Passive | `Full | `Restart | `Truncate | `Noop ] -> bool * int * int(** [wal_checkpoint t mode] is [PRAGMA wal_checkpoint(mode)] run in a statement of [t]: [(busy, log, copied)], whether the checkpoint was kept from finishing, the last frame of the log and the frame up to which the database file holds it, as sqlite3's [sqlite3_wal_checkpoint_v2] reports them; [(false, -1, -1)] with no log. [`Noop] copies nothing, [`Passive], [`Full] and [`Restart] copy the frames no read mark keeps, the last two answering [busy] where one kept a frame, and [`Truncate] also starts the log over, cut to no bytes ({!Sqlite.last_copy_back}).
@raise Catalog.Error inside an explicit transaction or savepoint. @raise Invalid_argument on a read-only handle, unless [mode] is [`Noop]. *)
val autocommit : t -> (unit -> 'a) -> 'a(** [autocommit t f] runs the direct write [f] as a transaction of its own, begun and committed through the connection of [t], so its writes are durable or undone. It takes the write session first, so [f] writes in it. Inside a transaction it is just [f ()], since that transaction commits at its own end. *)
val set_journal_mode : t -> journal_mode -> unit(** [set_journal_mode t mode] sets the journal mode of [t] to [mode] and records it on page 1. Leaving [`Wal] first copies the log into the file and removes it. It does nothing if the mode is already [mode].
@raise Catalog.Error inside an explicit transaction or savepoint, with the message of sqlite3.*)
(** {1:refresh Commits of other handles} *)
val in_transaction : t -> bool(** [in_transaction t] is [true] iff the connection of [t] has a transaction open, by [BEGIN] or [SAVEPOINT] ({!Sql.Private.Connection.autocommit}). *)
val backup : t -> Eio.Fs.dir_ty Eio.Path.t -> unit(** [backup t dst] writes the database [t] holds to a new file at [dst]. See {!Sqlite.backup}. *)
val check_vacuum : t -> unit(** [check_vacuum t] raises {!Catalog.exception-Error} if [t] is inside a transaction, where no [VACUUM] runs. *)
val vacuum_into : t -> Eio.Fs.dir_ty Eio.Path.t -> unit(** [vacuum_into t dst] writes a compact copy of the database [t] holds to a new file at [dst], through the public read door {!read_op}. See {!Sqlite.vacuum_into}. *)
val vacuum : t -> unit(** [vacuum t] writes the compact image of the database over its pages and cuts its page count to the image's, as [VACUUM] does, in the write transaction the caller commits; the commit cuts the file. Raises {!Catalog.exception-Error} inside a transaction or on a read-only handle, and as {!Vacuum.copy} raises. *)
val vacuum_into_read : t -> Eio.Fs.dir_ty Eio.Path.t -> unit(** [vacuum_into_read t dst] is {!vacuum_into} for a caller already inside a read of [t], a statement of a script. *)
val read_op : t -> (unit -> 'a) -> 'a(** [read_op t f] runs the public read [f] after {!maybe_refresh}, so it never reads a page another handle replaced. A read-only handle counts as a reader while [f] runs, so checkpoints defer ({!Durability.Readers}); the count is released however [f] ends, unless [f] left a transaction or savepoint open. A read-only handle in [`Journal] mode checks the version of the file before and after [f], and runs [f] again if it changed; {!read_op_once} is for an [f] that cannot run twice. *)
val pin_read : t -> unit(** [pin_read t] says that the open transaction or savepoint of [t] reads: it keeps the snapshot of the session it reads under until it ends, as a deferred transaction keeps the snapshot of its first read. It does nothing outside one. {!read_op} and {!read_op_once} call it. *)
val script_op : ?write:bool -> t -> (unit -> 'a) -> 'a(** [script_op ~write t f] is {!read_op_once} for a script, whose statements each call {!pin_read} where they read: a transaction verb reads nothing. With [write] (defaults to [false]), it takes the write session before [f] runs, for a script whose first statement writes. *)
val read_op_once : t -> (unit -> 'a) -> 'a(** [read_op_once t f] is like {!read_op} but runs [f] once, as needed for a script that sends rows to a callback or runs transaction commands. It settles the version of the file with an empty read first. *)
(** {1:schema Schema} *)
val relay_at_page_size : t -> int -> unit(** [relay_at_page_size t page_size] truncates an unwritten database, uses a pager of [page_size], and creates page 1 again. Call it only if {!is_unwritten}. *)
val begin_transaction : t -> Catalog.Spi.lock -> unit(** [begin_transaction t lock] begins the transaction, as sqlite3's [BEGIN] does (lang_transaction.html), on a view that holds other handles' commits. [`Deferred] takes nothing until the transaction reads or writes: its first read takes the snapshot it keeps, and its first write the write session, refused as [Catalog.Error (Busy _)] where another connection committed past that snapshot. [`Immediate] takes the write session at once, waiting as [busy_timeout] says. [`Exclusive] does too, and in a rollback journal keeps every reader of this process out until the transaction ends. *)
val commit : t -> unit(** [commit t] ends the transaction and makes it durable, closing its savepoints. It raises [Catalog.Error (Busy _)] where the lock the commit needs is refused, leaving the transaction open; if the commit cannot be made durable, it ends the transaction undone and raises. *)
val rollback : t -> unit(** [rollback t] ends the transaction, giving back the state it began on. *)
val savepoint : t -> unit(** [savepoint t] opens a savepoint over the state [t] has: a statement journal of the pager and the schema beside it. *)
val release : t -> unit(** [release t] closes the innermost savepoint, keeping its writes. *)
val rollback_to : t -> unit(** [rollback_to t] gives back the state the innermost savepoint was opened on, and leaves it open. *)
(** {1:defs Stored definitions}
The definition door of {!Catalog.Spi} over the file: every row of [sqlite_master] is one, and a view or a trigger is nothing but its row. *)
val definition_kind : string -> Catalog.Spi.Definition.kind option(** [definition_kind type_] is the kind of definition a [sqlite_master] row of type [type_] holds, or [None] for a type that is none. *)
val definitions : t -> (int64 * Catalog.Spi.Definition.t) list(** [definitions t] is every row of [t]'s [sqlite_master] that names a table, an index, a view or a trigger, with its rowid, in rowid order. *)
val define : t -> Catalog.Spi.Definition.t -> unit(** [define t d] adds the [sqlite_master] row of [d], at the next rowid, and rewrites page 1 for it. *)
val undefine : t -> Catalog.Spi.Definition.kind -> string -> unit(** [undefine t kind name] removes the row of the [kind] named [name].
Invalid_argument where [t] holds none. *)
val redefine : t -> Catalog.Spi.Definition.t -> unit(** [redefine t d] replaces the text of the view or trigger row [d] names, at its rowid, and rewrites page 1 for it.
Invalid_argument where [d] is no view or trigger [t] holds. *)
val with_transaction_result : t -> (unit -> 'a) -> ('a, Catalog.Error.t) result(** [with_transaction_result t f] is like {!with_transaction} but is [Error e] when the transaction's own begin or commit is refused with [e]. An exception of [f] propagates unchanged. *)
val with_transaction : t -> (unit -> 'a) -> 'a(** [with_transaction t f] runs [f ()] in a write transaction, committed if [f] returns and rolled back if it raises or the commit cannot be made durable. It takes the write session before [f] runs, as [BEGIN IMMEDIATE] does, so a writer that holds it makes [f] wait or refuses it before [f] reads. A nested call is a savepoint with no name. *)
val writing : t -> unit(** [writing t] takes the write session a write needs before it reads a page it will change: on the snapshot the open transaction read, or afresh, waiting as [busy_timeout] says. A read-only handle takes nothing. *)
val write_op : t -> (unit -> 'a) -> 'a(** [write_op t f] runs the direct write [f] in the write session. *)