(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** SQLite's value-level semantics over {!Catalog.Value.t}: storage-class comparison order, collated comparison, text conversion, three-valued truth, storage affinity and [CAST], the pattern operators, and the aggregate folds. A pure layer with no dependency on any query representation, so the typed query layer, a SQL frontend and the register VM all fold, coerce and order values the same way. *) val compare_values : Catalog.Value.t -> Catalog.Value.t -> int (** [compare_values a b] orders two values by SQLite's storage-class rule (NULL < number < text < blob; numbers compared exactly across int/real). *) val compare_values_coll : Collation.t -> Catalog.Value.t -> Catalog.Value.t -> int (** [compare_values_coll c a b] orders under the sequence [c] for a text/text comparison, else by {!compare_values}. The sequence is the resolved {!Collation.t} and not the name a [COLLATE] spells: a frontend reads the name once, where the operation that carries it is built, so a comparison costs no lookup per pair. *) val collation_key : Collation.t -> Catalog.Value.t -> Catalog.Value.t (** [collation_key c v] is [v]'s canonical form under the sequence [c]: two text values equal under it share a form (so a caller can bucket / dedup by it with plain equality), anything else unchanged. *) val float_of_value : Catalog.Value.t -> float (** [float_of_value v] is the [REAL] value of a numeric [v] ([Int]/[Float]); it raises [Invalid_argument] on a non-numeric value. *) val real : float -> Catalog.Value.t (** [real f] is the REAL value [f], or {!Catalog.Value.constructor-Null} when [f] is a NaN: SQLite has no NaN in its value model, so a double only becomes a value through this rule (sqlite3VdbeMemSetDouble). An infinity is an ordinary REAL. Every arithmetic result and every fold that answers a double goes through it. *) val text_of_float : float -> string (** [text_of_float f] is [f] as sqlite3 renders a real, through its own printf as [%!.17g]: 17 significant digits, shortened only where sqlite3FpDecode shortens them (so [0.1] stays ["0.1"]), the exponential form outside the decimal exponent range [-4, 16], a point always kept in the mantissa so the text reads back as a real, and [Inf], [-Inf], [NaN] for the non-finite values. *) val text_of_value : Catalog.Value.t -> string (** [text_of_value v] is SQLite's text conversion ([CAST(v AS TEXT)] / list-mode print): [NULL] is the empty string, a float keeps a [.] so it reads back as REAL, TEXT/BLOB are their raw bytes. A non-finite float is spelled as sqlite3's own printf spells it -- ["Inf"], ["-Inf"], ["NaN"] -- not as C's [%g] does. *) val leading_number : string -> Catalog.Value.t (** [leading_number s] is the leading numeric prefix of [s], as SQLite reads text by numeric affinity ([sqlite3AtoF]): an optional sign, digits, an optional [.], and an optional exponent, after leading whitespace -- stopping at the first character that grammar cannot take (so ["5x"] reads as 5, ["5.5e2x"] as 550.0, ["abc"] as 0). Nothing outside the grammar is a number, so ["inf"], ["nan"], ["0x10"] and ["1_0"] read as 0, 0, 0 and 1 rather than as the values OCaml's own parsers give them. The result is {!Catalog.Value.constructor-Int} for a pure integer that fits int64, else {!Catalog.Value.constructor-Float}; never {!Catalog.Value.constructor-Null}, {!Catalog.Value.constructor-Text}, or {!Catalog.Value.constructor-Blob}. *) val whole_number : string -> Catalog.Value.t option (** [whole_number s] is the number [s] spells, or [None] when any text other than whitespace at either end follows it. This is the reading numeric affinity takes ([applyNumericAffinity]), which converts a string only when the whole of it is a number and leaves it text otherwise: [" 12 "] is [Int 12], where ["12abc"] and ["0x10"] are [None]. *) val spells_number : string -> first:int -> length:int -> bool (** [spells_number s ~first ~length] is [true] iff {!whole_number} of the [length] bytes of [s] from [first] is [Some _], read where they are. *) val leading_integer : string -> int64 (** [leading_integer s] is the integer prefix of [s], the narrower reading [CAST(text AS INTEGER)] takes ([sqlite3Atoi64]): an optional sign then digits only, after leading whitespace, stopping at the first non-digit. So ["123e+5"] is [123L] where {!leading_number} reads 12300000.0, and text with no leading digit is [0L]. A prefix beyond int64 saturates at its bound. *) val shift : [ `Left | `Right ] -> int64 -> int64 -> int64 (** [shift dir x n] is sqlite3's [x << n] (for [`Left]) or [x >> n] (for [`Right]) in Int64: a negative [n] shifts the other way, and an [n] of 64 or more clears the value, the right shift being arithmetic so a negative [x] keeps its sign. *) val c_text_of_value : Catalog.Value.t -> string (** [c_text_of_value v] is [v]'s text as a scalar function receives it from [sqlite3_value_text]: {!text_of_value} cut at the first NUL byte. The accessor hands out a bare NUL-terminated C string and does not pass the byte count the value carries, so a function that reads its argument as text sees only the bytes before the first NUL -- [length], [quote], [printf]'s [%s], [unicode], [substr], [replace] and the [LIKE]/[GLOB] operands. The value itself keeps every byte, which is what a comparison, [hex], [octet_length], [instr], [upper] and [||] go on reading, so this is a reading boundary and never a store-time truncation. *) (** A three-valued truth: true, false, or unknown (NULL). *) type tri = T | F | U val tri_of : Catalog.Value.t -> tri (** [tri_of v] is [v]'s truth (lang_expr.html sec.14): [v] cast to NUMERIC as a [CAST] would cast it, false when that is zero and true otherwise, unknown for NULL. A text or blob is read by its longest numeric prefix, so ["1english"] is true where ["english"], [""] and ["0"] are false. *) val value_of_tri : tri -> Catalog.Value.t (** [value_of_tri t] is [1] for true, [0] for false, NULL for unknown. *) val tri_and : tri -> tri -> tri (** [tri_and] is three-valued [AND]: false dominates, unknown is contagious otherwise. *) val tri_or : tri -> tri -> tri (** [tri_or] is three-valued [OR]: true dominates, unknown is contagious otherwise. *) val tri_not : tri -> tri (** [tri_not] is three-valued [NOT]: true and false flip, unknown stays. *) val not_value : Catalog.Value.t -> Catalog.Value.t (** [not_value v] is the three-valued logical [NOT] of [v] as a [1]/[0]/NULL. *) val bool : bool -> Catalog.Value.t (** [bool b] is [1] for [true], [0] for [false]. *) val numeric_agg : string -> Catalog.Value.t list -> Catalog.Value.t (** [numeric_agg name vals] folds the non-NULL aggregate values [vals] for one of [sum]/[total]/[avg]/[min]/[max] (lang_aggfunc.html). [sum] stays an integer only while every value is one, and then raises [Error (Runtime "integer overflow")] if the int64 sum leaves range; any other input makes it real, as [total] and [avg] always are. A string or blob that does not look like a number folds as 0, so no fold rejects a value. [min]/[max] order by {!compare_values} and coerce nothing. An empty [vals] is NULL, except [total], which is [0.0]. An input counts as an integer by the number it denotes, so text spelling a whole number ([" 3 "]) keeps a sum integer where a fractional or exponent spelling (["3.0"], ["3e0"]) or a blob makes it real. lang_aggfunc.html says only "all non-NULL inputs are integers", leaving the storage class and the value readings both open; this is the one its avg() paragraph implies (a string is read as a number) and the one sqlite3 implements, and it decides the overflow rule the same way. It raises {!Catalog.exception-Error} on an aggregate name outside that set. *) (** The fold of SUM, TOTAL and AVG over the non-NULL values of a group, the one {!agg_acc} runs for those names (lang_aggfunc.html). *) module Sum : sig type t (** The type for one fold in progress. *) val v : string -> t (** [v name] is an empty fold of [name], one of ["sum"], ["total"] and ["avg"]. *) val add : t -> Catalog.Value.t -> unit (** [add s v] folds the non-NULL value [v] into [s]. *) val add_real : t -> float -> unit (** [add_real s r] is [add s (Float r)]. *) val add_ints : t -> sum:int -> count:int -> unit (** [add_ints s ~sum ~count] is [count] calls of {!add} on integers whose sum is [sum] and each of whose partial sums an [int] holds. Raises [Invalid_argument] once [s] has folded a real. *) val remove : t -> Catalog.Value.t -> unit (** [remove s v] takes the non-NULL value [v], folded earlier, back out of [s], as a sliding window frame drops a row (func.c, sumInverse). A fold that has folded a real or overflowed stays real, so a SUM keeps answering a real after every real has left. *) val finish : t -> Catalog.Value.t (** [finish s] is the value of the fold. Raises {!Catalog.exception-Error} when a SUM of integers left the range of a 64-bit integer. *) end (** The fold of group_concat and string_agg, as sqlite3 steps values into it and inverts them out of a sliding window frame (func.c, GroupConcatCtx). *) module Group_concat : sig type t (** The type for one fold in progress. *) val v : unit -> t (** [v ()] is an empty fold. *) val add : t -> ?sep:Catalog.Value.t -> Catalog.Value.t -> unit (** [add g ~sep x] steps the value [x] into [g], preceded by the separator [sep], a comma where there is none, unless [x] is taken as a first value: the first of [g], or the first after an inverse emptied its text. A NULL [x] steps nothing and a NULL [sep] separates by nothing (groupConcatStep). *) val remove : t -> Catalog.Value.t -> unit (** [remove g x] takes the value [x], stepped earlier, back out of [g] as a sliding frame drops its row (groupConcatInverse): the leading bytes of the text, as many as [x] has plus one separator's, the length the first value was stepped with while every separator has had that length, else the one stepped before the next value. Where they reach the end, the text is emptied, and the next value stepped is a first one. A NULL [x] takes nothing. *) val finish : t -> Catalog.Value.t (** [finish g] is the text of [g]: [""] where it is empty but holds a value, NULL where it holds none. *) end type agg_acc = Semantics.agg_acc = { step : Catalog.Value.t array -> int -> unit; step_reg : Catalog.Register.t array -> int -> unit; finish : unit -> Catalog.Value.t; } (** One aggregate's running fold over a group's rows ({!Semantics.agg_acc}): [step] over values, [step_reg] over registers read in place. *) val of_values : nargs:int -> step:(Catalog.Value.t array -> int -> unit) -> finish:(unit -> Catalog.Value.t) -> agg_acc (** [of_values ~nargs ~step ~finish] is the fold [step] and [finish] make, stepping registers by reading the [nargs] arguments as values. *) val agg_acc : string -> nargs:int -> coll:Collation.t option -> agg_acc (** [agg_acc name ~nargs ~coll] is a fresh accumulator for the aggregate [name] over rows carrying [nargs] argument values (lang_aggfunc.html). [count] counts the rows whose first argument is not NULL, and [~nargs:0] is a star [count], which counts every row; [group_concat]/[string_agg] join the non-NULL first arguments, each preceded by the separator its own row carried (the second argument, [","] when the call has none), the first element's separator going unused; every other name folds the non-NULL first arguments through {!numeric_agg}'s rules. [coll] is the collating sequence the fold's own comparison runs under ([None] = binary value order). Only [min] and [max] compare, and they are exactly the two aggregates sqlite3 marks SQLITE_FUNC_NEEDCOLL (src/func.c), so [min(v COLLATE NOCASE)] folds the case together while a sequence reaching any other name orders nothing and is spent on the caller's [DISTINCT] dedup or on nothing at all. This is the single fold policy: [DISTINCT], [FILTER] and an in-call [ORDER BY] select and order the rows before they are stepped, so a window frame and a [GROUP BY] group fold the same call the same way. It raises {!Catalog.exception-Error} on an aggregate name outside that set. *) type affinity = [ `Blob | `Integer | `Numeric | `Real | `Text ] (** What a column can hold, from the type it was declared with: storage applies the affinity, so a numeric column holds numbers and text no number spells, a text column holds text, and an undeclared one holds anything. This is what decides whether a comparison converts an operand, and so whether equality between two columns is transitive. *) val equal_affinity : affinity -> affinity -> bool (** [equal_affinity a b] is whether two columns compare the same way. *) val affinity_of_type : string -> affinity (** [affinity_of_type ty] is the storage affinity of a declared type name (datatype3.html sec.3.1): a name containing [INT] is [`Integer], CHAR/CLOB/ TEXT is [`Text], BLOB or [""] is [`Blob], REAL/FLOA/DOUB is [`Real], else [`Numeric]. *) val column_affinity : Catalog.Spi.t -> string -> string -> affinity option (** [column_affinity cat table col] is what [col] on [table] can hold, read off its declared type ({!affinity_of_type}), or [None] for an unknown table, a column the schema does not name, or a backend that tracks no schemas -- a relation nothing can be assumed about, which a comparison therefore converts neither end of. The one reading of a declared type as an affinity, so a planner deciding whether an equality is transitive, a typed query lowering a comparison, and a SQL frontend doing the same cannot disagree about what a column compares as. *) val apply_affinity : affinity -> Catalog.Value.t -> Catalog.Value.t (** [apply_affinity aff v] applies the column affinity [aff] to a value being written: NUMERIC/INTEGER read well-formed numeric text as a number and store a real with no fractional part as an integer, TEXT renders a number as text, REAL coerces a number to float; a BLOB, NULL, and non-numeric text are unchanged. *) val cast : string -> Catalog.Value.t -> Catalog.Value.t (** [cast ty v] is [CAST(v AS ty)] by the target affinity (lang_expr.html#castexpr): NULL is preserved; text/blob to a numeric type parses a leading numeric prefix. *) val is_real : Catalog.Value.t -> bool (** [is_real v] is whether [v] reads as a real rather than an integer: a float, or a text or blob whose leading number has a fractional part, an exponent, or a magnitude past int64. This is what makes [%] answer a real, so it reads a prefix as arithmetic does: ["5.5x"] is real where ["5x"] is not. *) val numeric_affinity : Catalog.Value.t -> Catalog.Value.t (** [numeric_affinity v] is the arithmetic coercion: a number passes through, text becomes the integer or real it spells, or [0] if it is not numeric. *) val numeric_type : Catalog.Value.t -> Catalog.Value.t option (** [numeric_type v] is [v] as [sqlite3_value_numeric_type] reads a function argument: the number itself for an INTEGER or a REAL, the number it spells for text that spells one in full ({!whole_number}), and [None] for a NULL, a blob and any other text. It is the gate every function of the math table opens with (func.c: [math1Func], [math2Func], [logFunc], [ceilingFunc], [signFunc]); each of them answers NULL -- by returning with no result set -- where this is [None]. *) val num_coerce : Catalog.Value.t -> Catalog.Value.t (** [num_coerce v] is the comparison-affinity coercion: a text becomes a number only when the whole of it is one, else it is unchanged (so a non-numeric string does not spuriously equal a number). A blob is never converted, and so keeps its place above every number in the storage-class order. *) val compare_affinity : affinity option -> affinity option -> affinity option (** [compare_affinity a b] is the single affinity a comparison between operands of affinities [a] and [b] applies to {e both} of them (datatype3.html sec.4.2; [sqlite3CompareAffinity] as [comparisonAffinity] calls it, src/expr.c): where both operands carry one it is [`Numeric] if either is numeric and [`Blob] otherwise, where one carries one it is that one, and where neither does it is [None]. One affinity for the pair, not one per operand, and that is what gives a comparison its direction: a [`Text] operand against one with no affinity makes the comparison [`Text], which renders the {e other} operand as text. [None] is an expression that is not a column -- a literal, an arithmetic result, a function call, a [COLLATE]-free unary plus -- and is distinct from [`Blob], which is what a column with no declared type carries. *) val coerce_compare : affinity option -> Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t * Catalog.Value.t (** [coerce_compare aff a b] is [a] and [b] with the comparison affinity [aff] applied to both, ready for {!compare_values} (the [OP_Eq]..[OP_Ge] preamble, src/vdbe.c): a numeric affinity reads a text operand as the number it spells ({!num_coerce}), [`Text] renders a numeric operand as text but only when the other operand is already text, and [`Blob] / [None] convert nothing. *) val compared : affinity -> Catalog.Value.t -> Catalog.Value.t (** [compared aff v] is the constant [v] as its comparison with a column of affinity [aff] reads it: a constant has none, so the column's applies (datatype3.html section 4.2), a numeric column reading a text that spells a number in full as that number ({!num_coerce}) and a TEXT column reading a number as its text. Nothing else moves. *) val key_value : affinity list -> Catalog.Value.t -> Catalog.Value.t (** [key_value affs v] is [v] under each of [affs] in turn ({!compared}), as OP_Affinity converts a key before a seek (src/vdbe.c, applyAffinity): an index holds its values so, which makes a key so converted one lookup that answers the comparison exactly. *) val compare_operands : ?aff:affinity -> ?coll:Collation.t -> Catalog.Value.t -> Catalog.Value.t -> int (** [compare_operands ?aff ?coll a b] is the order a comparison operator puts its two operands in: [aff] applied to both ({!coerce_compare}), then {!compare_values_coll} under [coll] (default: {!compare_values}). This is what [OP_Eq]..[OP_Ge] do between reading their registers and answering (src/vdbe.c), so a caller deciding a comparison itself decides it as the VM would. *) val is_value : ?aff:affinity -> ?coll:Collation.t -> Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t (** [is_value a b] is SQLite's NULL-safe equality [a IS b] as [1]/[0] (never NULL): two NULLs are equal, a NULL and a non-NULL are not, else {!compare_operands}. [IS] reads an affinity and a collating sequence exactly as [=] does, so [?aff] and [?coll] mean what they do there; the defaults are no affinity and the binary sequence. *) val intify : Catalog.Value.t -> int64 (** [intify v] is SQLite's integer coercion of a value: a float truncates, text reads its leading number, anything non-numeric is [0]. *) val like_match : ?escape:int -> string -> string -> bool (** [like_match pattern s] is SQL [LIKE] as sqlite3's patternCompare computes it over the code points sqlite3Utf8Read decodes from the two C strings: [%] matches any run, [_] one character, and an ASCII letter matches itself in either case. [~escape] is a code point that makes the next character match literally; when it is [%] or [_], that wildcard is a literal. 0, the default, is no escape. *) val glob_match : string -> string -> bool (** [glob_match pattern s] is SQL [GLOB] as sqlite3's patternCompare computes it, case-sensitive: [*] any run, [?] one character, [[..]] a class of code points with [-] ranges, negated by a leading [^] and taking a closing bracket as a literal member when that comes first. A class no bracket closes matches nothing at all. *) val like_op : ?escape:Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t (** [like_op a b] is [a LIKE b] as [1]/[0]/NULL, as sqlite3's likeFunc answers it. [~escape] is the optional ESCAPE value: NULL makes the answer NULL. @raise Catalog.Error [Runtime _] ["LIKE or GLOB pattern too complex"] when [b]'s text is longer than 50000 bytes, and ["ESCAPE expression must be a single character"] when [~escape]'s text is not one UTF-8 character. *) val glob_op : Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t (** [glob_op a b] is [a GLOB b] as [1]/[0]/NULL. @raise Catalog.Error [Runtime _] ["LIKE or GLOB pattern too complex"] when [b]'s text is longer than 50000 bytes. *) val concat_op : Catalog.Value.t -> Catalog.Value.t -> Catalog.Value.t (** [concat_op a b] is [a || b]: NULL if either is NULL, else the text forms concatenated. *) val distinct_values : Catalog.Value.t list -> Catalog.Value.t list (** [distinct_values vs] keeps the first occurrence of each value by {!compare_values} equality -- a [DISTINCT] aggregate's argument values. *)