(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** SQL over any catalog. [Sql] parses the SQLite dialect and runs it on a connection ({!type-t}) over a {!Catalog.t}: any store that implements {!Catalog.Spi.S}, such as the in-memory reference backend {!Catalog.of_mem}, a B-tree file in the SQLite format, a Parquet file or an Irmin tree. The value semantics (type affinity, collation, three-valued logic, the built-in functions, date and time, and json1) follow the sqlite3 documentation. A [SELECT] runs the whole read dialect: joins, aggregates with [GROUP BY] and [HAVING], window functions, compounds such as [UNION], [WITH] including recursive ones, correlated and [FROM] subqueries, and [VALUES] and table-function sources. {!exec} also runs [CREATE TABLE], [DROP TABLE], [INSERT] from [VALUES] or a [SELECT], [UPDATE] and [DELETE], with their [OR] and [ON CONFLICT] resolutions, upserts and [CHECK] constraints, fires triggers and enforces foreign keys. Every refusal raises {!Catalog.exception-Error}: a statement that does not parse or names nothing raises [Error (Prepare _)], and one this engine does not run raises [Error (Unsupported _)]. *) module Ast = Ast (** SQL syntax trees, as {!parse} produces them and {!select} runs them. *) module Json : sig (** sqlite3's JSON text, read and written over nox-json's values, so a codec of [Json.Codec] reads and writes the JSON the JSON functions read and write. The reader is sqlite3's: JSON5 is read, strings may hold any byte, raw control characters included, and [Infinity], [NaN] and their variants in any case read as [9e999] and [null]. A number keeps the text sqlite3 writes for it ([1.50], [-0], an integer past 2{^ 53}) as its lexeme, and a string has its escapes read. The writer is sqlite3's: [\b], [\f], [\n], [\r], [\t] or a lower-case [\u00xx] for a control character, DEL and other bytes as they are, and a number as the lexeme it was read from. *) val of_string : 'a Json.codec -> string -> ('a, Json.Error.t) result (** [of_string c s] reads the JSON or JSON5 text [s] with [c]. A text that is neither is ["malformed JSON"] at the byte where sqlite3's parser stops, the position json_error_position() counts. *) val of_string_exn : 'a Json.codec -> string -> 'a (** [of_string_exn] is {!of_string} raising [Json.Error]. *) val to_string : ?indent:int -> 'a Json.codec -> 'a -> string (** [to_string c v] is [v] as the JSON text json() writes, or with [~indent:n] as json_pretty(v, n spaces) writes it: an array's elements and an object's members one to a line, each [n] spaces deeper per level. It takes nox-json's knob; json_pretty()'s indent of any text is the SQL function's own. There is no [?preserve]: the reader keeps no layout. *) end module Jsonb = Jsonb (** SQLite's JSONB binary format, which the JSON functions read and write: its values, codecs and cursors. *) (** {1:semantics sqlite3's value semantics} *) module Collation = Collation (** Collating sequences for text comparison, shared by the expression layer and by a store's index key order. *) module Encoding = Encoding (** Text encodings a database stores its TEXT values in, and the conversions and BINARY order each implies. *) module Order = Order (** The order of one index key column: its collating sequence and its direction. *) module Decimal = Decimal (** The decimal spelling of a REAL, as sqlite3 computes it, used to render a double as text and to read a literal back. *) module Value_ops = Value_ops (** SQLite's value-level semantics over a {!Catalog.Value.t}: truth, affinity, [CAST], the pattern operators and the aggregate folds. *) module Sqlite3_semantics = Sqlite3_semantics (** SQLite's semantics over registers: the comparison, truth and arithmetic the register VM runs by. *) (** {1:engine The engine} The intermediate representation every query lowers to, and the machines that run it over any {!Catalog.t}. *) module Ir = Ir (** The positional query intermediate representation and its compiler to {!Vdbe}. *) module Vdbe = Vdbe (** The register virtual machine queries compile to and run on. *) module Closure = Closure (** {!Ir.query} and {!Ir.grouped} plans compiled to closures, with the VM for the shapes it does not compile. *) module Join = Join (** How a join reads its inner relation: the choice between an index seek and a hash, how much of a relation a hash may hold, and the cursors that read it. *) module Row = Row (** A query's result row, read in place inside the call that receives it. *) (** {1:parse Parsing} *) val parse : string -> (Ast.stmt list, string) result (** [parse sql] are the statements of [sql], separated by [;]. This is [Error msg] for the first that does not parse, with [msg] in sqlite3's words. *) (** {1:connection Connections} *) type t = Connection.t (** The type for connections. A connection runs statements over a {!Catalog.t} and holds what sqlite3 keeps on its connection beside the store: the counts [changes()] and [total_changes()] answer, the rowid [last_insert_rowid()] answers, and the limit on a recursive CTE. A store holds none of it, so two connections over one catalog count apart. *) val v : ?recursion_cap:int -> Catalog.t -> t (** [v ~recursion_cap cat] is a connection over [cat], with every count zero. [recursion_cap] is the number of rows a recursive CTE may produce before a statement raises [Error (Runtime _)] (defaults to [1_000_000]). @raise Invalid_argument if [recursion_cap] is not positive. *) val pp : t Fmt.t (** [pp ppf t] formats [t] as [connection(t1,t2,...)], naming the tables of its catalog. *) val catalog : t -> Catalog.t (** [catalog t] is the catalog [t] runs over. *) val changes : t -> int64 (** [changes t] is the number of rows the last [INSERT], [UPDATE] or [DELETE] run on [t] changed, as [changes()] answers it (lang_corefunc.html#changes). Any other statement leaves it alone. *) val total_changes : t -> int64 (** [total_changes t] is the number of rows every [INSERT], [UPDATE] and [DELETE] run on [t] changed, as [total_changes()] answers it (lang_corefunc.html#total_changes). *) val last_insert_rowid : t -> int64 (** [last_insert_rowid t] is the rowid of the last row an [INSERT] run on [t] put into a table that has one, or [0], as [last_insert_rowid()] answers it (lang_corefunc.html#last_insert_rowid). *) val close : t -> unit (** [close t] rolls back the transaction [t] has open, if any, as sqlite3 does when a connection is closed (sqlite3_close). [t] is in autocommit afterwards. *) (** {1:run Running} *) (** The type for the outcome of a statement. *) type outcome = | Rows of Catalog.Value.t list list (** The rows of a [SELECT]. *) | Done (** A statement with no rows. *) val exec : t -> string -> outcome (** [exec t sql] runs the statements of [sql] in order on [t], each prepared once the one before it ran, and is the outcome of the last one. A placeholder in [sql] reads NULL, as an unbound parameter does in sqlite3; {!query} binds them. It runs [SELECT], [CREATE TABLE], [CREATE INDEX], [CREATE VIEW], [CREATE TRIGGER], their [DROP], [INSERT], [UPDATE] and [DELETE], the [PRAGMA]s that read the schema ([table_info], [table_xinfo], [index_list], [index_info], [index_xinfo], [foreign_key_list]), check it ([foreign_key_check], and [integrity_check] and [quick_check], which check each row against its table, the store keeping its own indexes), or read and set the connection's flags ([foreign_keys], [defer_foreign_keys], [recursive_triggers]), each also a table-valued function [pragma_], and [BEGIN], [COMMIT], [ROLLBACK], [SAVEPOINT], [RELEASE] and [ROLLBACK TO] over the store's transactions ({!Catalog.Spi.begin_transaction}). Every table, index, view and trigger is kept as the text of the statement that made it, which the schema table [sqlite_master] reads back ({!Catalog.Spi.definitions}), and each [INSERT], [UPDATE] and [DELETE] fires the triggers of its table for each row it writes (lang_createtrigger.html). A row it writes takes what its table declares before the store sees it: each column's affinity, an omitted column's [DEFAULT], the generated columns and a [STRICT] table's types, and meets its [NOT NULL], [CHECK] and unique keys, resolved by the statement's [OR] clause, the constraint's [ON CONFLICT] or the [INSERT]'s upsert (lang_conflict.html, lang_upsert.html). Under [PRAGMA foreign_keys] it meets the foreign keys of its table and of the tables that reference it, and takes their [ON DELETE] and [ON UPDATE] actions: an immediate key is judged when the statement ends, a deferred one when the transaction commits (foreignkeys.html). Each statement that writes is atomic: one that fails leaves the store as it found it. An [INSERT], [UPDATE] or [DELETE] sets {!changes} to the rows it changed, and to [0] where it fails. @raise Catalog.Error on a parse error, a name that resolves to nothing, a constraint a row breaks, or a statement it does not run. *) val query : t -> string -> params:Catalog.Value.t list -> Catalog.Value.t list list (** [query t sql ~params] is [select t s ~params] for the one statement [s] of [sql]. It raises [Error (Prepare _)] if [sql] is not exactly one [SELECT]. *) val select : t -> Ast.select -> params:Catalog.Value.t list -> Catalog.Value.t list list (** [select t s ~params] is the rows of [s] on [t]. [params] are the values of the placeholders of [s], numbered as sqlite3 numbers them: a [?NNN] reads the [NNN]th value and a bare [?] the one after the largest so far. A placeholder past the end of [params] reads NULL. *) val eval : t -> Ast.expr -> Catalog.Value.t (** [eval t e] is the value of [e] outside any row, such as a cell of an [INSERT ... VALUES] tuple. A placeholder reads NULL, a subquery runs on [t], and a column reference raises {!Catalog.exception-Error}. *) val explain_select : t -> Ast.select -> string (** [explain_select t s] is the plan of [s] on [t], after the rewrites {!select} applies, as one line per source in scan order, such as [SCAN t] or [SEARCH t USING INDEX i]. It raises [Error (Prepare _)] if a name of [s] resolves to nothing. *) (** {1:typed Typed queries} A {!Catalog.Query} statement run over any catalog: its tree ({!Catalog.Query.view}) is lowered straight to {!Ir}, with no SQL text in between, and its rows are decoded through the statement. *) val run : Catalog.t -> 'o Catalog.Query.stmt -> 'o list (** [run cat q] executes [q] over [cat] and decodes the result rows. When the store reports an index serving [q]'s equality predicates ({!Catalog.Spi.index_scan}), the scan uses it; the engine re-checks every predicate either way. It raises {!Catalog.exception-Error} when [q] names a table or column [cat] does not have, has no {!Catalog.Query.val-from}, reads a column that is not a {!Catalog.Query.key} over a group, or breaks the single [LEFT JOIN] rule. *) val iter : Catalog.t -> 'o Catalog.Query.stmt -> f:('o -> unit) -> unit (** [iter cat q ~f] calls [f] on each row of [run cat q], in that order. A query with no [ORDER BY], [DISTINCT], [OFFSET] or grouping hands each row to [f] as the scan produces it and holds none. An exception of [f] stops the scan and is raised again. [f] must not write [cat]: the rows it is then handed are unspecified. *) val explain : Catalog.t -> 'o Catalog.Query.stmt -> string (** [explain cat q] is the access path {!val-run} takes, one line per table: [SCAN t], or [SEARCH t USING INDEX i] when the store serves an equality predicate from an index ({!Catalog.Spi.best_index_for}). *) val text_of_query : 'o Catalog.Query.stmt -> string * Catalog.Value.t list (** [text_of_query q] is [q] as one SQLite [SELECT], with a [?] parameter for each literal, and the parameters' values in order: how a store that runs SQL itself, as a SQLite database does, runs [q]. The text is otherwise unspecified; {!Catalog.Query.decode} reads the rows it answers. @raise Catalog.Error [Prepare _] as {!val-run} does. *) val update : Catalog.t -> 'r Catalog.table -> where:('r Catalog.Query.src -> bool Catalog.Query.expr) -> ('r -> 'r) -> unit (** [update cat t ~where f] rewrites every row satisfying [where] as [f row] ({!Catalog.rewrite}): the stored row is decoded, transformed and encoded back, and columns outside the typed view keep their stored values. Rows are identified the store's own way ({!Catalog.Spi.update}): by rowid in a numbered store, by key in a keyed one such as an Irmin tree. [where] is evaluated exactly as {!val-run} evaluates a [WHERE]. It raises {!Catalog.exception-Error} on an unknown table or column, a store constraint violation, or a read-only store. *) val delete : Catalog.t -> 'r Catalog.table -> where:('r Catalog.Query.src -> bool Catalog.Query.expr) -> unit (** [delete cat t ~where] removes every row satisfying [where]. It raises {!Catalog.exception-Error} on an unknown table or column, or a read-only store. *) (** {1:fmt Formatting} Each formatter prints SQL text that parses again to the same tree. *) val ident : string -> string (** [ident name] is [name] as {!pp_ident} formats it. *) val pp_ident : string Fmt.t (** [pp_ident ppf name] formats [name] as an identifier: bare if every character may appear in an unquoted identifier and [name] is no keyword, and double-quoted with its quotes doubled otherwise. @raise Invalid_argument if [name] holds the byte [0x00], which ends SQL text. *) val pp_expr : Ast.expr Fmt.t (** [pp_expr ppf e] formats [e] with every subexpression in parentheses. *) val pp_select : Ast.select Fmt.t (** [pp_select ppf s] formats the [SELECT] [s]. *) (**/**) (* The parser, resolver, planner and lowering, which the sqlite package shares. Unstable. *) module Private : sig module Alter = Alter module Alter_text = Alter_text module Autoinc = Autoinc module Collate = Collate module Conflict = Conflict module Connection = Connection module Column_tokens = Column_tokens module Create_table = Create_table module Datetime = Datetime module Engine = Engine module Func = Func module Integrity = Integrity module Introspect = Introspect module Json1 = Json1 module Lexer = Lexer module Lower = Lower module Param_number = Param_number module Pragma = Pragma module Pragma_value = Pragma_value module Parser = Parser module Plan = Plan module Query = Query module Render = Render module Resolve = Resolve module Schema_table = Schema_table module Self_ref = Self_ref module Strict = Strict module Table = Table module Value_op = Value_op module View = View module Trigger = Trigger module Semantics = Semantics module Vdbe_core = Vdbe_core module Ir_core = Ir_core module Closure_core = Closure_core module Row_core = Row_core module Join_core = Join_core module Window = Window module Write = Write module Foreign_key = Foreign_key module Tbl_hash = Tbl_hash end (**/**)