Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(** SQLite databases in pure OCaml.
[Sqlite] is a B-tree store with the SQLite file format. Its main interface runs typed queries and writes over {!Catalog} row codecs, so a type mismatch, a column of a table the query does not scan or a nullability error does not compile. {!run} returns the rows a table codec decodes, and {!insert}, {!update} and {!delete} write records. {!module-Raw} runs SQL text, {!module-Table} reads and writes rows as lists of values, and {!module-Kv} is a string key-value store.
{2:dialect Dialect}
The dialect is the one of sqlite3 3.54.0, checked statement by statement, with these differences. A double-quoted string is always an identifier, never a string literal, as with [-DSQLITE_DQS=0]. A plan lists its sources in [FROM] order by table name, where sqlite3 may reorder them and use aliases. A query scans the table where sqlite3 reads a covering index, and an index on a [WITHOUT ROWID] table serves no seek, so this engine scans some sources that sqlite3 seeks; the rows and their order are the same. An open under a missing directory is refused.
{2:durability Durability}
A commit appends its changed pages to a write-ahead log and fsyncs it ([PRAGMA synchronous] [`Off] appends them and skips the fsync). A checkpoint copies the log into the database file, at {!close} or once the log passes a thousand pages. A commit is atomic, and opening a database replays its log, so a committed write survives a crash before the copy.
{2:concurrency Concurrency}
A process has one writer and any number of read-only handles ([open_ ~read_only:true]), each used by one domain. A handle is not safe to share between domains, and it refuses a second fiber while one is inside it. Readers take a handle each for the time of a read, from an [Eio.Pool]; the writer is one fiber fed by an [Eio.Stream], which can also batch writes ({!Writer}).
Between processes, and between writable handles of one process, the locks are SQLite's. In WAL mode a reader and a writer run at once (wal.html, section 2.2): every handle keeps the [-shm] WAL-index in sqlite3's format (walformat.html, section 2), and keeps the [-wal] log open with it from its first transaction to its close, as a sqlite3 connection does (sqlite3WalOpen). A checkpoint that starts the log over or cuts it keeps the file; one that removes the log removes the index with it, and the handle's next transaction opens the log at the name again. A read holds SHARED and a read mark, for one autocommit statement or for a transaction that has read, and reads the commit its mark names while a writer appends later ones; a checkpoint copies no frame past a mark still held. A write transaction holds SHARED and the index's WRITE lock: for one autocommit statement that writes, from [BEGIN IMMEDIATE] or [BEGIN EXCLUSIVE] or {!with_transaction} to its end, and from the first write of a [BEGIN] or an outermost [SAVEPOINT], which are DEFERRED and take nothing until they read or write (lang_transaction.html). A transaction that has read writes on its snapshot and takes the write lock without waiting, as sqlite3 does: where another connection holds it, or has committed past the snapshot (SQLITE_BUSY_SNAPSHOT), the write raises [Error (Busy _)]. In rollback-journal mode a read holds SHARED and a write transaction EXCLUSIVE (section 3 of lockingv3.html), so a reader waits for a commit to end and a commit for the readers. No lock is held between transactions, so an idle handle keeps no other process out (section 7). A handle waiting for EXCLUSIVE holds PENDING, so new readers wait for it. Every wait lasts up to the handle's [busy_timeout] and then raises [Error (Busy _)]. Read-only handles of the writer's own process read beside its transactions, on the snapshot their read marks and the checkpoint count keep ({!Durability.Readers}). A handle's cache stands across its unlocked intervals only while the file and its log are as it left them. *)
type t(** The type for database handles. *)
val pp : t Fmt.t(** [pp ppf t] formats [t] as [sqlite(t1,t2,...)], with its table names. *)
val path : t -> Eio.Fs.dir_ty Eio.Path.t option(** [path t] is the original path capability passed to {!open_}, retained after {!close}. An {!in_memory} database or an {!overlay} has no backing path and answers [None]. *)
(** {1:values Values} *)
(** The type for SQL values. See {!Sql.Ast.type-value}. *)type value = Sql.Ast.value = | Null | Int of int64 | Float of float | Blob of string | Text of string
(** Value printing and text conversions. *)module Value : sig val pp : value Fmt.t (** [pp ppf v] formats [v] as a SQL literal, for messages: [NULL], an integer, a real with [%g], a quoted string, or a blob as [x'..'] hex. *)
val to_text : value -> string (** [to_text v] is [CAST(v AS TEXT)] in SQLite: [""] for NULL, a float with a [.] so it reads back as a real, and every byte of a text or blob. *)
val to_c_text : value -> string (** [to_c_text v] is [to_text v] up to its first NUL byte, as [sqlite3_column_text] returns it. The shell prints text cells this way. *)
val to_shell : value -> string (** [to_shell v] is the cell the sqlite3 shell prints for [v] in its default list mode: a blob's bytes, and {!to_c_text} of anything else, with each control byte in caret notation, [^] followed by the byte plus [0x40], so a NUL reads ["^@"] and an ESC ["^\["]. Tab, newline, a carriage return just before a newline, DEL and every byte above it are kept. This is the shell's [qrfEscape], applied to a text cell as much as to a blob. *)
val to_float : value -> float option (** [to_float v] is [v] as a number, read the way numeric affinity reads it: an {!constructor-Int} or a {!constructor-Float} is its value, a {!constructor-Text} is the number it spells in full, surrounding whitespace allowed (["12"], [" 3.5 "], ["1e3"]), and [None] is a {!constructor-Null}, a {!constructor-Blob} or any other text (["12abc"], [""]). *)
val text : value -> string option (** [text v] is [Some s] when [v] is [Text s] and [None] otherwise. Unlike {!to_text} it converts nothing, so a NULL or a number is told apart from a string. *)end
module Ident = Catalog.Ident(** Schema names: tables, columns, indexes, views, triggers and aliases. {!Ident.equal} compares them without regard to ASCII case, and every entry point uses it, so [USERS] names a table [users]. *)
(** {1:errors Errors}
Every refusal of a statement or of the database raises {!exception-Error}, whose {!Error.t} names the sqlite3 result code: a statement refused before it runs, which the sqlite3 shell reports as "Parse error", is {!Error.constructor-Prepare}; a constraint violation is {!Error.constructor-Constraint}; a lock another handle held past [busy_timeout] is {!Error.constructor-Busy}. A file-system failure raises [Eio.Io], as Eio's own calls do. [Invalid_argument] is raised only for a broken precondition of the caller, such as a closed handle or a read from inside the [f] of an iteration, and a [Failure] is a bug of this library. *)
module Error = Catalog.Error(** Statement errors. *)
exception Error of Error.t(** [Error e] is {!Catalog.exception-Error}: a handler of either catches both.*)
type Eio.Exn.err += | Is_a_directory (** The error {!val-open_} raises through [Eio.Io], in either mode, when its path names a directory, as sqlite3 answers [SQLITE_CANTOPEN]. A read-only descriptor on a directory opens on POSIX and fails only at its first read, so the open asks what it opened. *)
(** {1:lifecycle Opening and closing} *)
val in_memory : ?clock:_ Eio.Time.clock -> ?zone:(int64 -> int) -> unit -> t(** [in_memory ~clock ~zone ()] is a new, empty database in memory, which does no file I/O and disappears with the handle. [clock] and [zone] are as in {!val-open_}. *)
type synchronous = [ `Off | `Normal | `Full | `Extra ](** The type for durability modes, as [PRAGMA synchronous]. [`Normal], [`Full] and [`Extra] fsync on every commit, as sqlite3 does by default, and the directory of a rollback journal once it is unlinked, which sqlite3 does only under [`Extra]; [`Off] writes the commit's pages when it ends, as the others do, and syncs nothing, so another process reads the commit at once and a crash of the process keeps it, but a power loss may not. *)
type journal_mode = [ `Wal | `Journal ](** The type for journal modes, as [PRAGMA journal_mode]. [`Wal], the mode of a new database, appends changed pages to a [-wal] file and folds the log into the database at a checkpoint. [`Journal] writes old pages to a [-journal] file, writes new pages to the database and deletes the journal. In both modes a handle sees the commits other handles made between its transactions.*)
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: a statement on it sees the commit that transaction began on, then what the overlay wrote, and nothing it writes reaches [t], its file or its log. It is for folding a few rows into a large database a reader may not write.
A page is read from [t] when a statement first needs it, and each page the overlay writes is held in memory: it holds the pages it wrote and a page cache, not the database. It reads [t] for as long as it is used, so the transaction of [t] stays open until the overlay is closed, and with it the read mark that keeps a checkpoint from copying past that commit.
Raises [Invalid_argument] where no transaction is open on [t], and at a read of a page once that transaction has ended. *)
val backup : t -> Eio.Fs.dir_ty Eio.Path.t -> unit(** [backup t dst] writes the database [t] holds, as its last commit left it, to a new file at [dst]: the consistent copy that sqlite3's [VACUUM INTO] and its backup API write, with no log beside it to replay. A program copying a live database, to keep it or to move it elsewhere, copies this file rather than the database and its [-wal], which a copy made between two commits leaves disagreeing.
The pages are copied as they are, under one read of [t], which a writer of another process commits beside in WAL mode and waits for in rollback mode, as for any read. Commits after the read began are not in the copy. Free pages are copied too: unlike [VACUUM INTO], the copy is not rebuilt. Its header keeps [t]'s journal mode, page size and {!val-user_version}. The copy is fsynced, then the directory holding it. A copy that fails part way is removed. [t] may be {!in_memory} or a snapshot.
@raise Invalid_argument if [t] is inside a transaction or savepoint, whose pages are not yet a commit. @raise Eio.Io if a file exists at [dst], even an empty one, or [dst] cannot be written.*)
val vacuum_into : t -> Eio.Fs.dir_ty Eio.Path.t -> unit(** [vacuum_into t dst] writes the database [t] holds, as its last commit left it, to a new file at [dst], rebuilt compactly: sqlite3's [VACUUM INTO] (lang_vacuum.html), which {!module-Raw.val-exec} also runs. Each table's rows are appended to full pages and each index's keys packed bottom-up, so the copy holds no free page and none that no b-tree reaches; [t] is left as it was. The header keeps [t]'s page size, reserved bytes, {!val-user_version} and application id, and states rollback-journal mode. The copy is made under one read of [t], a row at a time, so its memory does not grow with the database; it is fsynced, then the directory holding it, and a copy that fails part way is removed.
@raise Error [Runtime "output file already exists"] if a file exists at [dst], even an empty one; ["cannot VACUUM from within a transaction"] inside a transaction or savepoint; [Unsupported _] if [t] is in auto-vacuum mode or has an index whose order this engine cannot compute; and [Corrupt _] if [t] is damaged. *)
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].
If [create] is [true] (the default), a missing database is created. A file that exists but cannot be read fails the open, and a missing directory above [path] raises [Eio.Fs.Not_found].
If [read_only] is [true] (defaults to [false]), the handle only reads: its open, reads and {!close} write nothing to the database or its logs, it never recovers the database or its log, and every write raises [Error (Readonly _)]. A WAL read creates the [-shm] WAL-index where it is missing and writes its read mark there, as a sqlite3 reader does; where the index cannot be written, the read holds the index's WAL_READ_LOCK(0) shared, which keeps every checkpoint out of the file until it ends (wal.c, walBeginShmUnreliable). A reader domain holds such a handle while another domain writes. It reads under SHARED, taken for its open and for each read, and kept while a transaction a read opened stays open, as sqlite3 takes it for a read transaction (lockingv3.html, section 3). In WAL mode it reads beside a writer of any process; in rollback mode a writable open of another process is refused while it stands, and while a handle of another process holds the file for a write transaction, the open or the read waits for it.
[busy_timeout] is how long, in seconds, an open, a read or a write transaction waits for another handle to let the file go before raising [Error (Busy _)] (defaults to [0.], as [sqlite3_busy_timeout]'s default): a write waits for every other lock, a read-only access for a writer's.
[synchronous] is the initial durability mode (defaults to [`Full]). [journal_mode] is the mode of the database; without it, page 1 of an existing file decides and a new file uses [`Wal]. [clock] is what [CURRENT_TIMESTAMP], [CURRENT_DATE], [CURRENT_TIME] and ['now'] read; without it they are NULL. It is also what [busy_timeout]'s waits sleep on, as sqlite3's busy handler sleeps through the VFS that answers its time; without it they sleep on the operating system's clock. [zone] is the local offset in seconds east of UTC (defaults to UTC).
A writable open of a WAL database reads it under the WAL-index's WRITE lock, beside any reader, and raises [Error (Busy _)] once [busy_timeout] has passed while another handle is in a write transaction on it. Any other writable open recovers the file under EXCLUSIVE and lets it go, so it raises [Error (Busy _)] while another handle is in a transaction on the file or another process reads it. It does not truncate an existing file. It opens files that another SQLite wrote, rolling back a hot journal or replaying a log, and refuses a recovery file in an unknown format.
A writable open of a file this process may not write, or that the operating system otherwise refuses to open for writing short of naming a directory, opens it as [~read_only:true] does, as [sqlite3_open_v2] opens a file "write protected by the operating system" (os_unix.c, unixOpen). It never creates over such a file, whatever [create] says.
@raise Eio.Io if [path] cannot be opened, with {!Is_a_directory} if it names a directory, or a [-wal] or [-journal] sibling it has to recover cannot be read. @raise Error [Not_a_database _] if the file does not begin with the SQLite header. @raise Error [Unsupported _] if the file is a SQLite database this build cannot read.*)
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, as os_unix.c fileHasMoved tests it. A handle kept across another process's rebuild of the file sees the replacement here and opens the path again. An in-memory handle, or a closed one, never moved. *)
type log = { bytes : int; frames : int }(** The type for the size of a write-ahead log: its bytes and the frames they hold. *)
val log : _ Eio.Path.t -> log option(** [log path] is the write-ahead log of the database at [path], its frames counted from the page size its header names (fileformat2.html, "WAL File Format"), none where the header names none; [None] where the database has no log. *)
val pp_log : log Fmt.t(** [pp_log] formats a log as [log B bytes, F frames]. *)
val sync : t -> unit(** [sync t] makes the committed writes durable, appending them to the log and fsyncing it. It does nothing if there is nothing to write, or inside a transaction or savepoint. *)
val checkpoint : ?mode:[ `Passive | `Truncate ] -> t -> unit(** [checkpoint ~mode t] copies the committed frames of the log into the database file, up to the oldest read mark a reader holds, as [sqlite3_wal_checkpoint_v2] does in [mode] (defaults to [`Passive]), and waits for no reader. With [`Passive], once every frame is in the file the next commit starts the log over from its first frame. With [`Truncate], where every frame is then in the file and no reader marks any, the log is started over and cut to no bytes at once, and what the copy did is {!last_copy_back}; where a mark keeps the log, it stays for a later checkpoint. A process that keeps a handle open past its writes calls it after them, so the log holds no more than what one burst of writes appended beside readers that ended, and with [`Truncate] no byte once they did. It does nothing inside a transaction or savepoint, in a database with no log, or while another handle of this process reads the file.
@raise Error [Readonly _] on a read-only handle. *)
val holder : _ Eio.Path.t -> ([ `Free | `Process of int | `Unnamed ], string) result(** [holder path] is who uses the database at [path] in WAL mode, as the dead-man switch of its WAL-index says, which every process using the index read-locks for as long as it does (os_unix.c, unixLockSharedMemory): [`Process pid], this process where one of its handles holds it; [`Unnamed] where another process does and the kernel names none; [`Free] where none does, or the database has no WAL-index. One fcntl [F_GETLK] on the [-shm] file, whatever the number of processes. [Error] names what could not be read. *)
val writers : _ Eio.Path.t -> int(** [writers path] is the number of handles of this process inside a write transaction on the file at [path]: [0] between transactions, and never more than [1]. *)
type copy_back = { log_frames : int; (** The log's last frame when the copy began. *) copied : int; (** The frame up to which the database file holds the log. *) restarted : bool; (** [true] iff every frame went into the file and the log started over, cut to no bytes. *) held_by : int option list; (** Where the log did not start over, the process holding each read mark that kept it, [None] for one the kernel does not name. *)}(** The type for what a copy of the log into the database file did. A commit that leaves the log at [PRAGMA wal_autocheckpoint] frames or more (1000 by default, as in sqlite3) copies it as sqlite3's TRUNCATE checkpoint does: every frame into the file, then the log started over and cut to no bytes, waiting up to [busy_timeout] for the readers whose marks stop either; a [`Truncate] {!checkpoint} makes the same copy and waits for none. *)
val compact : t -> bool(** [compact t] rebuilds the database in place, as [VACUUM] does, when its free pages outnumber the pages its b-trees hold, and is [true] iff it did. A rebuild writes each page the b-trees hold once and gives the free ones back, so the file stays below twice what its b-trees hold, beyond one transaction's growth, and a freed page costs at most one page written. In WAL mode the rebuilt pages go to the log and a [`Truncate] {!checkpoint} with no reader marking it cuts the file. Its memory is the compacted size of the database.
@raise Error [Runtime "cannot VACUUM from within a transaction"] inside a transaction or savepoint. *)
val last_copy_back : t -> copy_back option(** [last_copy_back t] is what the last copy of the log a commit of [t] or a [`Truncate] {!checkpoint} started did, or [None] before one. *)
val close : t -> unit(** [close t] rolls back an open transaction or savepoint, writes what is left, copies the log into the database file and removes the log. Uncommitted work is lost, as with sqlite3. Where another handle is in a transaction on the file past [busy_timeout], the log stays for a later close; where a reader holds a mark into the log, the copy stops at it, and where another process holds the file, the log and its index stay, as sqlite3's last connection alone removes them. A handle whose database moved since its open ([Error (Readonly_dbmoved _)]) copies nothing and removes nothing: its log stays beside its path, and the file the path names, if any, is left as it is, as sqlite3_close leaves them (pager.c, sqlite3PagerClose). A read-only handle releases its snapshot and writes no database or recovery log. A second close does nothing.
It creates no switch resource, so [Eio.Switch.on_release] may call it, though {!with_open} is better; a handle whose switch ends without a close gives back what it holds, as a crash would. It completes in a cancelled fiber and releases the descriptor, deferring its close while a lock of this process stands on the file. *)
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 or the fiber is cancelled. It closes while [sw] is still live, which is better than closing on switch release. *)
val prefetch : t -> max_bytes:int -> unit(** [prefetch t ~max_bytes] loads up to [max_bytes] of the start of the database file into the page cache of [t] with one storage read, within the cache budget. Pages a write or the WAL already gave [t] keep their newer bytes. A broad query on a freshly opened handle reads fewer times after it. *)
val with_transaction : t -> (unit -> 'a) -> 'a(** [with_transaction t f] runs [f ()] in a write transaction, which takes the write lock before [f] runs, as [BEGIN IMMEDIATE] does: another writer makes it wait up to [busy_timeout] and then raise [Error (Busy _)], before [f] reads. If [f] raises, the changes are rolled back and the exception raised again; otherwise they are committed, durable as the {!synchronous} mode of [t] says, unless a deferred foreign key is still violated: then they are rolled back and [Error (Constraint Foreign_key)] is raised. A nested call is a savepoint, and durability follows the outermost commit. On a read-only handle it is a read transaction. *)
val with_transaction_result : t -> (unit -> 'a) -> ('a, 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], so a caller can retry a contended transaction without mistaking an [Error] that [f] raised for one. An exception of [f], an [Error] included, propagates. *)
val user_version : t -> int(** [user_version t] is [PRAGMA user_version], the signed 32-bit schema version of the application in the database header, [0] for a new database. The engine does not use it. *)
val set_user_version : t -> int -> unit(** [set_user_version t v] sets [PRAGMA user_version] to [v] and makes it durable, as any autocommit change. *)
(** {1:log Log formats} *)
module Durability = Durability(** Write-ahead log and rollback journal formats, and their recovery, usable without a database. *)
(** {1:writer Writer fibers}
When several fibers write to one database, one fiber owns the writable handle and the others submit their writes to it. The owner runs all queued writes as one transaction, so a batch costs one append and one fsync. *)
(** Writer fibers. *)module Writer : sig type db := t
type t (** The type for writer fibers. *)
val v : sw:Eio.Switch.t -> db -> t (** [v ~sw db] is a daemon fiber in [sw] that owns [db], so it does not keep [sw] open. Every later write to [db] must go through {!submit}. *)
val submit : t -> (db -> 'a) -> 'a (** [submit t f] runs [f] in the owner fiber, inside the transaction of its current batch, and is its result once that transaction commits. An exception of [f] is raised here only; the rest of the batch continues. A refusal [e] of the batch transaction raises [Error e], as {!with_transaction} does. *)
val submit_result : t -> (db -> 'a) -> ('a, Error.t) result (** [submit_result t f] is like {!submit} but is [Error e] when the batch transaction itself is refused with [e]. An exception of [f], an [Error] included, propagates. *)
val submit_at_boundary : t -> (db -> 'a) -> 'a (** [submit_at_boundary t f] is like {!submit} but runs [f] outside any transaction, after everything submitted before it is committed. Use it for operations that make no sense inside a transaction, such as {!val-sync}. A write here commits on its own. *)
val db : t -> db (** [db t] is the handle [t] owns, for a close, its path, or a pragma before the owner starts. The handle refuses a read or write from another fiber by name. *)end
(** {1:integrity Integrity} *)
module Integrity = Integrity(** Integrity check results and page accounting. *)
val integrity_check : t -> Integrity.t(** [integrity_check t] is [PRAGMA integrity_check]: it checks that every page is reached exactly once, and compares every index with its table. It only reads, reports damage instead of raising, and reads the whole database. *)
val quick_check : t -> Integrity.t(** [quick_check t] is like {!integrity_check} but does not look up every row in every index. It compares the entry count of each index with the row count of its table, so it finds an index with missing entries but not one with wrong entries. *)
(** {1:typed Typed queries and writes}
The main interface: a table is a {!Catalog.Table.t} row codec and a query a {!Catalog.Query.stmt}, so a column of a table the query does not scan, a comparison of a number with a string or an aggregate in a [WHERE] does not compile, and a row decodes to the caller's record.
{[ type layer = { name : string; exit_status : int64 }
let name = Catalog.Col.v "package_name" Catalog.text (fun l -> l.name)
let exit_status = Catalog.Col.v "exit_status" Catalog.int (fun l -> l.exit_status)
let layers = Catalog.Table.map "layers" (fun name exit_status -> { name; exit_status }) |> Catalog.Table.col name |> Catalog.Table.col exit_status |> Catalog.Table.seal
let find db ~pkg = Sqlite.run db Catalog.Query.( from layers @@ fun l -> where Expr.(get l name = text pkg) @@ all l |> limit 1) ]}
{!run} executes the [SELECT] that {!Sql.text_of_query} renders, with {!Raw.query}'s planner, so it uses the indexes that text would. {!insert}, {!update} and {!delete} enforce constraints and fire triggers as the equivalent SQL statement does. *)
val run : t -> 'o Catalog.Query.stmt -> 'o list(** [run db q] is all the rows of [q]. {!val-iter} gives them one at a time.
@raise Error [Prepare _] as {!Sql.text_of_query} does, or if [q] names a table or a column [db] does not have, and [Decode _] if a stored value is not of its column's type. *)
val iter : t -> 'o Catalog.Query.stmt -> f:('o -> unit) -> unit(** [iter db q ~f] calls [f] on each row of [q] as the scan produces it, in the order of {!val-run}, so only one row is held at a time; a query that needs later rows to produce one reads them first. [f] runs inside the read and must not read or write [db], which raises [Invalid_argument]. An exception of [f] stops the scan and is raised again. On a read-only handle in [`Journal] mode, [f] may see the rows again from the first one, if the file changed during the read. *)
val explain : t -> 'o Catalog.Query.stmt -> string(** [explain db q] describes how {!run} reads [q], one line per source in [FROM] order: [SCAN t] for a full read, and [SEARCH t USING ...] for an index seek. Any index whose key starts with columns that equalities or IN lists bind can serve, an IN list being sought once per value; the one that binds the most columns wins. A source read into a hash prints as a scan and a lookup. A subquery prints as sqlite3 names it ([LIST SUBQUERY 1]), its own plan indented two spaces under it. *)
val insert : t -> 'r Catalog.table -> 'r -> unit(** [insert db tbl r] inserts [r] into [tbl]: each column of the codec takes its value in [r], and any other column of the table its [DEFAULT]. It enforces every constraint of the schema.
@raise Error [Prepare _] if [tbl] or one of its columns is not in [db], and [Constraint _] if the row violates a constraint. *)
val insert_or_replace : t -> 'r Catalog.table -> 'r -> unit(** [insert_or_replace db tbl r] is like {!insert}, but first deletes a row that conflicts on a unique index or the [INTEGER PRIMARY KEY], and replaces a NULL in a [NOT NULL] column by its [DEFAULT]. Other constraints raise as for {!insert}. *)
val update : t -> 'r Catalog.table -> where:('r Catalog.Query.src -> bool Catalog.Query.expr) -> ('r -> 'r) -> unit(** [update db tbl ~where f] rewrites each row [r] of [tbl] that [where] selects as [f r], as one statement: every selected row is read, then written back by its rowid ([PRIMARY KEY] in a [WITHOUT ROWID] table). If [f] raises, no row is written. Columns outside the codec keep their values, and every constraint of the schema is enforced on the new rows.
@raise Error [Prepare _] if [tbl] or one of its columns is not in [db], and [Constraint _] if a new row violates a constraint. *)
val delete : t -> 'r Catalog.table -> where:('r Catalog.Query.src -> bool Catalog.Query.expr) -> unit(** [delete db tbl ~where] deletes the rows of [tbl] that [where] selects. To delete every row, pass [~where:(fun _ -> Expr.bool true)].
@raise Error [Prepare _] if [tbl] or one of its columns is not in [db], and [Constraint _] if a [RESTRICT] foreign key refuses a deletion. *)
(** {1:declared Declared schemas}
A table is declared once as a {!Schema.Table.t}: its columns, its primary key and its indexes. {!create_table} creates one in a database, and {!Schema} declares every table of a database at once: the statements are rendered from the declaration, written to a new database with the declaration's identity in [PRAGMA user_version], and compared with what an existing database holds when it is opened. A database written by another declaration is a {!Schema.mismatch}, never read as if it were this one. No step converts it.
{[ let jobs = Sqlite.Schema.Table.( v ~primary_key:[ key "id" ] "jobs" [ column ~decl_type:"INTEGER" "id"; column ~decl_type:"TEXT" "name" ])
let open_ db = match Sqlite.Schema.init db (Sqlite.Schema.v [ jobs ]) with | Ok () -> db | Error m -> Fmt.failwith "%a" Sqlite.Schema.pp_mismatch m ]}
A table with a {!Catalog.Table.t} codec is declared by {!Catalog.Table.schema}, so its declaration cannot disagree with its codec.*)
(** Declared schemas. *)module Schema : sig type db := t
include module type of struct include Schema end
val check : db -> t -> (unit, mismatch) result (** [check db t] compares what [db] holds with [t] ({!diff}), and writes nothing. A new database is {!constructor-Empty}. *)
val init : db -> t -> (unit, mismatch) result (** [init db t] is [check db t], except that a new database first receives every statement of [t] and the {!identity} of [t], in one transaction.
@raise Error [Readonly _] if [db] is read-only and new. *)
val reset : db -> t -> unit (** [reset db t] replaces what [db] holds with [t], in place and in one transaction: it drops every object but the engine's own ({!drops}), the rows of each table with it, then writes every statement of [t] and its {!identity}, so that [check db t] is [Ok ()]. A reader that holds the file open keeps it.
@raise Error [Readonly _] if [db] is read-only. *)end
val create_table : ?if_not_exists:bool -> t -> Schema.Table.t -> unit(** [create_table ~if_not_exists db s] creates the table [s] and its indexes, by the statements {!Schema.sql_of_table} renders, in one transaction. If [if_not_exists] is [true] (defaults to [false]), a table or view named [s.table] is not an error and nothing is created.
@raise Error [Prepare _] if a table, view or index already holds one of the names [s] declares. *)
val drop_table : ?if_exists:bool -> t -> string -> unit(** [drop_table ~if_exists db name] drops the table [name] and its indexes. If [if_exists] is [true] (defaults to [false]), a missing table is not an error. *)
(** {1:raw SQL text}
SQL statements as strings, for what the typed interface cannot express. *)
(** SQL text. *)module Raw : sig val query : t -> string -> params:value list -> value list list (** [query t sql ~params] is the rows of the single [SELECT] [sql], each a list of values in select-list order, with [params] for its [?] placeholders from left to right. {!val-iter} gives the rows one at a time.
A read-only [PRAGMA] that returns rows is also a query: [table_info], [table_xinfo], [index_list], [index_info], [index_xinfo], [foreign_key_list], and {!val-user_version} or [foreign_keys] without a value. The [pragma_*] table-valued functions return the same rows. A [PRAGMA] that sets a value goes to {!val-exec}.
@raise Error [Prepare _] if the SQL is not a single [SELECT] or read-only [PRAGMA], references an unknown name, or uses an unsupported function. *)
val iter : t -> string -> params:value list -> f:(value list -> unit) -> unit (** [iter t sql ~params ~f] calls [f] on each row of [query t sql ~params] as the scan produces it. [sql] is one statement, as for {!val-query}; {!val-run} takes several. [f] runs inside the read and must not read or write [t], which raises [Invalid_argument]. An exception of [f] stops the scan. On a read-only handle in [`Journal] mode, [f] may see the rows again from the first one.
@raise Error [Prepare _] if the SQL is not a single [SELECT] or read-only [PRAGMA], references an unknown name, or uses an unsupported function. @raise Invalid_argument if [f] reads or writes [t]. *)
type row (** The type for the result row a walk stands on, readable only inside the call of [f] that receives it, as a statement's columns are readable until its next [sqlite3_step]. *)
val iter_rows : t -> string -> params:value list -> f:(row -> unit) -> unit (** [iter_rows t sql ~params ~f] is {!val-iter} with each row read in place through {!Row} rather than handed over as a list of values: a column is converted only when, and as, it is read.
@raise Error [Prepare _] as {!val-iter} does. @raise Invalid_argument as {!val-iter} does. *)
(** Typed reads of a result row, as [sqlite3_column_*] reads a statement's columns (https://www.sqlite.org/c3ref/column_blob.html). Each raises [Invalid_argument] if the row is read outside the call of [f] that received it, or the column is not one of the row's. *) module Row : sig type kind = [ `Null | `Integer | `Real | `Text | `Blob ] (** The type for storage classes, as [sqlite3_column_type]. *)
val length : row -> int (** [length r] is the number of result columns of [r]. *)
val kind : row -> int -> kind (** [kind r i] is the storage class of column [i] of [r]. *)
val int64 : row -> int -> int64 (** [int64 r i] is column [i] as [sqlite3_column_int64]: NULL is [0], a real is truncated towards zero and held to the [int64] range, text or a blob is its leading integer, [0] if there is none. *)
val int : row -> int -> int (** [int r i] is {!int64} as a native integer.
@raise Invalid_argument also if it is outside the native range. *)
val float : row -> int -> float (** [float r i] is column [i] as [sqlite3_column_double]: NULL is [0.], text or a blob is its leading number, [0.] if there is none. *)
val text : row -> int -> string (** [text r i] is column [i] as [sqlite3_column_text]: a number is its text, as [CAST(x AS TEXT)] spells it, and NULL is [""]. *)
val bytes : row -> int -> int (** [bytes r i] is the length of {!text}[ r i], as [sqlite3_column_bytes]. *)
val blit : row -> int -> off:int -> bytes -> pos:int -> len:int -> unit (** [blit r i ~off dst ~pos ~len] copies the [len] bytes of {!text}[ r i] from [off] into [dst] at [pos].
@raise Invalid_argument also if the range is outside the cell or [dst]. *)
val value : row -> int -> value (** [value r i] is column [i] as {!val-iter} gives it. *)
val to_list : row -> value list (** [to_list r] is the row {!val-iter} gives. *) end
val exec : t -> string -> params:value list -> unit (** [exec t sql ~params] runs the statements of [sql], separated by [;], none of them a query: [INSERT [OR REPLACE]], [DELETE], [UPDATE ... SET ... [WHERE ...]], [CREATE TABLE [IF NOT EXISTS]], [CREATE INDEX [IF NOT EXISTS]], [CREATE TRIGGER], [PRAGMA], [BEGIN], [COMMIT] and [ROLLBACK]. [params] fill the [?] placeholders of each statement from left to right.
{3 Triggers}
A [BEFORE] or [AFTER] row trigger fires once per row, with [OLD] and [NEW] bound to it. Each statement of its body runs as a step of the statement that fired it, under that statement's [OR] clause where it names one. A step fires triggers in turn, to a depth of 1000 programs; a trigger already running is skipped unless [PRAGMA recursive_triggers] is on. [RAISE(action, message)] in a body acts on the row and the statement: - [IGNORE] stops the body without error: a [BEFORE] row is dropped, an [AFTER] row stays, and the writes of the body stay. - [ABORT] undoes the statement and raises [Error (Constraint (Trigger message))]. - [FAIL] stops at the row, keeps the rows before it, and raises [Error (Constraint (Trigger message))]. - [ROLLBACK] rolls back and ends the transaction, and raises [Error (Constraint (Trigger message))].
[CREATE TRIGGER] refuses a body with a [?].
@raise Error [Prepare _] on a parse error, or an unknown table or column. @raise Error [Runtime _] on a transaction command with no transaction to act on, or a statement the schema refuses. @raise Error [Constraint _] on a constraint violation. @raise Invalid_argument on a [SELECT]. *)
val run : t -> string -> params:value list -> on_row:(value list -> unit) -> unit (** [run t sql ~params ~on_row] runs the statements of [sql], separated by [;], as a script piped to the [sqlite3] CLI: the rows of each [SELECT] go to [on_row], and the others run as with {!val-exec}. The script reads the state committed when it starts, not the commits of other handles during it.
@raise Error [Prepare _] on a parse error, or an unknown table or column. @raise Error [Runtime _] on a transaction command with no transaction to act on, or a statement the schema refuses. @raise Error [Constraint _] on a constraint violation. *)
type stmt (** The type for statements parsed once and run many times with different parameters. *)
val prepare : t -> string -> stmt (** [prepare t sql] is the parsed statement [sql], which may have [?] placeholders. It is valid while [t] is open; after {!val-close}, running it raises, except on an {!val-in_memory} handle. A [SELECT] keeps between runs what it works out from its text and the schema, and works it out again at the first run on a changed schema, so each run reads the schema of that run, as sqlite3 recompiles a statement on [SQLITE_SCHEMA]. *)
val exec_stmt : stmt -> params:value list -> unit (** [exec_stmt s ~params] runs the prepared statement [s], not a query, with [params] for its [?] placeholders from left to right.
@raise Error [Prepare _] on an unknown table or column, resolved against the schema at run time; {!prepare} raises parse errors. @raise Error [Runtime _] on a transaction command with no transaction to act on, or a statement the schema refuses. @raise Error [Constraint _] on a constraint violation. @raise Invalid_argument if [s] is a [SELECT], or the handle [s] was prepared on has been closed. *)
val query_stmt : stmt -> params:value list -> value list list (** [query_stmt s ~params] is the rows of the prepared [SELECT] [s] with [params]. @raise Invalid_argument if the handle [s] was prepared on has been closed. *)
val explain : t -> string -> string (** [explain t sql] is like {!val-explain} for SQL text. {!val-query} also accepts [EXPLAIN QUERY PLAN <select>]. Plain [EXPLAIN] is refused, since sqlite3 prints its VDBE program for it. *)end
(** {1:rows Rows}
Tables read and written as lists of {!type-value} by rowid. A write here enforces the constraints and fires the triggers of the table, as the equivalent SQL statement does. *)
(** Rows. *)module Table : sig type db := t
type t = { schema : Schema.Table.t; sql : string } (** The type for tables: the schema a table's [CREATE TABLE] declares, and the statement as the database stores it. A table is a snapshot; an [ALTER TABLE] makes a new one, which a later {!tables} returns. *)
val create_table : db -> sql:string -> unit (** [create_table t ~sql] creates the table of the [CREATE TABLE] statement [sql], stored in [sqlite_master].
@raise Error [Runtime _] if a table, view or index already has the name, since they share one namespace. With [IF NOT EXISTS], an existing table or view is not an error, but an index is. *)
val insert : db -> table:string -> value list -> int64 option (** [insert t ~table values] inserts a row with the column values [values] and is its rowid, or [None] if the row was dropped. In a table with an [INTEGER PRIMARY KEY], an [Int n] in that column sets the rowid and a {!constructor-Null} picks one. A short list is padded with NULLs. As an [INSERT] without [OR], it applies affinity, computes generated columns, enforces each constraint with its declared resolution, and fires row triggers.
@raise Error [Prepare _] if the table doesn't exist. @raise Error [Prepare _] if more values than columns were supplied. @raise Error [Constraint _] on a constraint violation. *)
val delete_row : db -> table:string -> int64 -> unit (** [delete_row t ~table rowid] deletes the row [rowid], if any.
@raise Error [Prepare _] if the table doesn't exist. *)
val read_row : db -> table:string -> int64 -> value list option (** [read_row t ~table rowid] is the values of the row [rowid], one per column, or [None] if there is none, found in O(log n). An [INTEGER PRIMARY KEY] column holds [rowid], and missing trailing columns are {!constructor-Null}.
@raise Error [Prepare _] if the table does not exist. *)
val tables : db -> t list (** [tables db] is every table of [db]: what its [CREATE TABLE] declares, with the indexes of its columns, and the statement stored. *)
val iter_table : db -> string -> f:(int64 -> value list -> unit) -> unit (** [iter_table t name ~f] calls [f rowid values] on each row of [name], with values as for {!read_row}. [f] runs inside the read and must not read or write [t], which raises [Invalid_argument]. An exception of [f] stops the walk.
@raise Error [Prepare _] if the table doesn't exist. *)
val fold_table : db -> string -> init:'a -> f:(int64 -> value list -> 'a -> 'a) -> 'a (** [fold_table t name ~init ~f] folds [f rowid values] over the rows of [name], from [init]. [f] must not use [t], as for {!iter_table}.
@raise Invalid_argument if [f] reads or writes [t]. *)
val read_table : db -> string -> (int64 * value list) list (** [read_table t name] is the rows of [name] as [(rowid, values)] pairs. *)
val parse_create_table : string -> Schema.Table.t option (** [parse_create_table sql] is the schema the [CREATE TABLE] statement [sql] declares, without indexes, or [None] if this engine cannot parse it. *)end
(** {1:provider Catalog provider} *)
val catalog : t -> Catalog.t(** [catalog t] is [t] as a {!Catalog.t}, the interface a store presents to a SQL engine over {!Catalog.Spi}, so that {!Catalog.Spi.union} composes [t] with another store and one query joins the two.
Its tables are the tables and views of [t]. A table's rows come with their rowid, a [WITHOUT ROWID] table's and a view's with none. A table's schema is what its [CREATE TABLE] declares ({!Table.tables}). An equality on indexed columns is answered by the index a query of [t] would seek, and counts no full-scan step; a full scan counts in {!Stats.rows_scanned} as a query's does. The row count is not reported, since a b-tree gives it only by a walk. A cursor holds the rows the table had when the cursor was made.
Each operation is a read of [t] of its own, as {!Raw.query} is. A name that is neither a table nor a view raises [Error (Prepare "no such table: <name>")], and a write or a schema change raises [Error (Runtime _)]: the catalog only reads, and [t] is written through its own functions. *)
(** {1:stats Statistics} *)
(** Query statistics and join memory limits. *)module Stats : sig type budget = Sql.Join.budget = { cells : int; (** The number of boxed values a hash may hold. *) bytes : int; (** The number of text and blob bytes it may hold. *) } (** The type for the size limits of the hash of a join. A hash stops at the first limit it reaches. See {!Sql.Join.budget}. *)
val rows_scanned : t -> int (** [rows_scanned t] is the number of full-scan steps of every query on [t] since {!open_}, as [SQLITE_STMTSTATUS_FULLSCAN_STEP] in sqlite3. A rewind is not a step, so a pass over [n] rows counts [n - 1]; seeks and hash probes do not count; computing a relation counts its reads. A join that seeks its inner table counts nothing, and one that scans it per outer row counts the product, so the difference across a query shows how it read. *)
val page_fetches : t -> int (** [page_fetches t] is the cumulative number of full pages the pager fetched from the database file after cache misses on this handle. Cache hits, dirty pages and pages replayed from a WAL do not count. Subtract before and after a query to measure its file reads. *)
val pages_written : t -> int (** [pages_written t] is the cumulative number of pages the commits on this handle wrote since {!open_}: each commit counts every page it changed once, as one frame of a write-ahead log or one page of the file. Subtract before and after a commit to measure what it wrote. *)
val page_size : t -> int (** [page_size t] is the database page size in bytes. Multiply a {!page_fetches} delta by it for bytes fetched from the database file. *)
val hash_budget : t -> budget (** [hash_budget t] is the limit of the hash of a join on [t]. A hash that exceeds it is dropped, and its source is read with an index seek if it has one, and scanned otherwise. *)
val set_hash_budget : t -> budget -> unit (** [set_hash_budget t b] sets the limit of joins on [t] to [b] from now on. A running query keeps its limit. *)end
(** {1:kv Key-value store}
A string key-value store over tables [(key TEXT, value BLOB)]: one table of the database for {!Kv} itself, and tables of other names with {!Kv.Table}. {!Kv} has the functions of {!Kv.Table} on its own table.
Each table is [CREATE TABLE <name> (key TEXT, value BLOB)], created on the first write or found in the schema. Column names compare without regard to case and types by affinity, so [(key text, value blob)] is the same table. Another table, a view or an index of that name raises [Invalid_argument] naming the table and the expected columns.
New tables also have a nonunique SQL index on [key], so a cold lookup reads the index bucket and matching rows rather than all values. Duplicate keys remain valid: the row with the greatest rowid whose value is text or a blob supplies the value. Existing SQL tables are adopted without a schema write; if no suitable index exists, the first lookup derives membership with a complete table scan. A loaded membership cache answers subsequent lookups.
A write runs as the SQL statement it is, with the constraints, foreign keys and triggers of the table. A function given to a walk runs inside the read and must not use the handle, which raises [Invalid_argument]. *)
(** Key-value store. *)module Kv : sig val find : t -> string -> string option (** [find t key] is the value of [key], or [None]. *)
val put : t -> string -> string -> unit (** [put t key value] sets [key] to [value]. *)
val delete : t -> string -> unit (** [delete t key] removes [key], if present. *)
val mem : t -> string -> bool (** [mem t key] is [true] iff [key] has a value. *)
val iter : t -> f:(string -> string -> unit) -> unit (** [iter t ~f] calls [f key value] on each entry.
@raise Invalid_argument if [f] reads or writes [t]. *)
val fold : t -> init:'a -> f:(string -> string -> 'a -> 'a) -> 'a (** [fold t ~init ~f] folds [f] over the entries, from [init].
@raise Invalid_argument if [f] reads or writes [t]. *)
(** Key-value stores in tables of their own. *) module Table : sig type db = t (** The type for databases. *)
type t (** The type for key-value tables. *)
val v : db -> name:string -> t (** [v db ~name] is the table [name], created if needed. Any name works, written as a quoted identifier.
@raise Invalid_argument if [name] is empty or has a NUL byte. @raise Error [Runtime _] if another table of that name has other columns than [(key TEXT, value BLOB)], or if a view or index has that name. *)
val index : t -> unit (** [index t] ensures a SQL equality index on [t]'s key column. An existing suitable index is reused; otherwise a nonunique index is backfilled from the stored rows in a transaction. Duplicate keys and values are preserved. The operation participates in an enclosing transaction.
Use this explicitly when opening an application-owned table written before KV tables were indexed. Merely adopting an external SQL table with {!v} does not change its indexes.
@raise Error [Readonly _] if the database is read-only. *)
val db : t -> db (** [db t] is the database of [t], for {!with_transaction} and {!val-sync}. *)
val find : t -> string -> string option (** [find t key] is the value of [key], or [None]. *)
val put : t -> string -> string -> unit (** [put t key value] sets [key] to [value]. *)
val delete : t -> string -> unit (** [delete t key] removes [key], if present. *)
val mem : t -> string -> bool (** [mem t key] is [true] iff [key] has a value. *)
val iter : t -> f:(string -> string -> unit) -> unit (** [iter t ~f] calls [f key value] on each entry.
@raise Invalid_argument if [f] reads or writes {!val-db}. *)
val fold : t -> init:'a -> f:(string -> string -> 'a -> 'a) -> 'a (** [fold t ~init ~f] folds [f] over the entries, from [init].
@raise Invalid_argument if [f] reads or writes {!val-db}. *) endend
(** {1:blob Incremental cell reads}
The bytes of a text or blob cell read into a caller's buffer, as {{:https://www.sqlite.org/c3ref/blob_read.html}[sqlite3_blob_read]} reads them: out of the leaf page for the bytes the cell holds, and straight off the overflow chain for the rest, which is never joined into a string. A walk over a table copies each byte it is asked for once, from the page to the buffer, and allocates nothing per row, so a reader streaming a table to a file or a socket holds one buffer whatever the table's size.
{[ let name = Catalog.Col.v "name" Catalog.text Fun.id
let names = Catalog.Table.map "names" Fun.id |> Catalog.Table.col name |> Catalog.Table.seal
let print db = let name = Sqlite.Blob.column db names name and buf = Bytes.create 4096 in Sqlite.Blob.iter db names ~f:(fun row -> let len = min 4096 (Sqlite.Blob.length row name) in Sqlite.Blob.read row name ~off:0 buf ~pos:0 ~len; print_endline (Bytes.sub_string buf 0 len)) ]} *)
(** Incremental cell reads. *)module Blob : sig type db := t
type 'r column (** The type for stored columns of a rowid table whose rows decode to ['r], resolved against the table's schema. *)
val column : db -> 'r Catalog.table -> ('r, _) Catalog.Col.t -> 'r column (** [column db tbl c] is the column [c] of the rowid table [tbl] in [db].
@raise Invalid_argument if [tbl] is no rowid table of [db], or [c] is missing, the rowid, or a VIRTUAL generated column. *)
type 'r row (** The type for the row a walk of a table whose rows decode to ['r] stands on. *)
val iter : db -> 'r Catalog.table -> f:('r row -> unit) -> unit (** [iter db tbl ~f] calls [f] on each row of the rowid table [tbl], in rowid order. The walk is one read, run once: a moving file is settled before it starts, and [f] never sees a row twice. [f] runs inside the read and must not read or write [db], which raises [Invalid_argument], and a row is readable only inside the call of [f] that receives it. An exception of [f] stops the walk and is raised again. The walk counts as a full scan in {!Stats.rows_scanned}.
@raise Invalid_argument if [tbl] is not a rowid table of [db]. *)
val is_null : 'r row -> 'r column -> bool (** [is_null row c] is [true] iff the cell of [c] in [row] is NULL. A row written before an [ALTER TABLE ADD COLUMN] holds the column's default.
@raise Invalid_argument if [row] is read outside its call of [f], or [c] is not a column of the table walked or was resolved against an older schema. *)
val length : 'r row -> 'r column -> int (** [length row c] is the number of bytes of the text or blob cell of [c] in [row], as [sqlite3_blob_bytes].
@raise Invalid_argument as {!is_null} does, and if the cell is NULL or a number, which [sqlite3_blob_open] refuses too. *)
val read : 'r row -> 'r column -> off:int -> bytes -> pos:int -> len:int -> unit (** [read row c ~off dst ~pos ~len] copies the [len] bytes of the cell of [c] in [row] that start at [off] into [dst] at [pos], as [sqlite3_blob_read] does. A cell larger than a buffer is read in pieces at successive offsets.
@raise Invalid_argument as {!length} does, and if the range is outside the cell or [dst]. *)end
(**/**)
module Private : sig (** Internal modules, exported for the tests of this package only, with no stability promise. *)
module Handle = Handle (** The state of an open database. *)
module Decl = Decl (** What a [CREATE TABLE] declares. *)
module Rowid = Rowid (** The rowid of an [INSERT] that gives none. *)
module Rowid_range = Rowid_range (** The rowid range a [WHERE] limits a query to. *)
module Page1 = Page1 (** The database header and the schema table on page 1. *)
module Index = Index (** Index b-trees: the order of their entries, the entry of a row, and key lookups. *)
module Reconnect = Reconnect (** Tables rebuilt from a stored schema. *)
module Introspect = Introspect (** The rows of the introspection [PRAGMA]s and index descriptions. *)
module Fast_path = Fast_path (** Single-table queries answered by b-tree seeks, and the reads they need. *)
module Where_loop = Where_loop (** sqlite3's choice of a loop over one table. *)
module Eqp = Eqp (** EXPLAIN QUERY PLAN trees. *)
module Log_est = Log_est (** sqlite3's logarithmic estimates. *)
module Index_row = Index_row (** What an index holds for a row: partial index admission, expression key values and entries, computed from the columns of the row. *)
module Store = Store (** Row storage in a b-tree: insert, delete, update, read, and uniqueness conflicts. *)
module Transfer = Transfer (** Which [INSERT ... SELECT *] copy records whole, as sqlite3's transfer does. *)
(** The counts [changes()] and [total_changes()] answer. *)
module Seek = Seek (** The index that serves an equality on a table, and its lookups. *)
module Catalog_view = Catalog_view (** The catalog a [SELECT] runs over, and the seven reads a database gives it. *)
module Cursor = Cursor (** Query cursors, the full-scan counter, and the reads of a cursor. *)
module Row = Row (** Rows and their stored records. *)
module Ddl = Ddl (** Schema objects made from a [CREATE] statement and removed: tables, indexes, views and triggers. The handle adds them and rewrites page 1. *)
module Model = Model (** The in-memory model of a stored schema, and constraint violations. *)
module Vdbe_record = Vdbe_record (** Single-table [SELECT]s compiled to {!Sql.Vdbe} programs and run over a cursor of records. *)
module Value_ops = Sql.Value_ops (** SQLite value semantics. *)
module Local_claim = Local_claim (** The write claims on a file that no host lock counts. *)
module Writer_lock = Writer_lock (** SQLite's byte locks on a database file, and how the handles of this process share them. *)
module Stat4 = Stat4 (** The samples [ANALYZE] keeps of an index for [sqlite_stat4]. *)
val handle : t -> Handle.t (** [handle t] is the state of [t]. *)end
(**/**)
(** {1:pool Read handles kept between readings} *)
(** Read handles on one database file, kept between readings.
A process that reads a file again and again pays an open each time, and the open of a file with a long log replays the log's index. A pool keeps the handles a reading ends with and hands one back to the next reading of the same file, by its device and inode: a path another process replaced since (a rebuild, a removal) is read through a handle opened on the file it names now, and the idle handles on the old file are closed. *)module Pool : sig type db := t
type 'e t (** The type for pools of read handles whose opens fail with ['e]. *)
val v : open_:(unit -> (db, 'e) result) -> Eio.Fs.dir_ty Eio.Path.t -> 'e t (** [v ~open_ path] is a pool of handles on the database at [path], each opened by [open_] when no idle handle reads the file [path] names. The switch [open_] opens on is the one that closes them. *)
val use : 'e t -> sw:Eio.Switch.t -> (db -> 'a) -> ('a, 'e) result option (** [use t ~sw f] is [Some (Ok (f h))], [h] a handle of [t] on the file the path names now, given back to [t] when [sw] ends, after what [f] left on [sw] is released, the transaction [f] or a later read left open rolled back; [Some (Error e)] where the open failed with [e]; [None] where no file is at the path. A handle a rollback fails on is closed. [f] raising [Eio.Io] closes [h], which is not given back. *)end