(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Error = Catalog.Error module Ident = Catalog.Ident module Spi = Catalog.Spi module Value = Catalog.Value open Value let float_of_value = function | Int i -> Int64.to_float i | Float f -> f | _ -> invalid_arg "float_of_value" let real f = if Float.is_nan f then Null else Float f let is_digit c = c >= '0' && c <= '9' (* The index after the run of digits starting at [i]. *) let rec skip_digits s n i = if i < n && is_digit s.[i] then skip_digits s n (i + 1) else i (* The decimal exponent written at [i] ([e]/[E], optional sign, digits), saturated: a literal may spell an exponent wider than an [int], and every value past the few hundred that reach a double is the same infinity or the same zero. *) let exponent_at s n i = let neg = i + 1 < n && s.[i + 1] = '-' in let j = if i + 1 < n && (s.[i + 1] = '+' || s.[i + 1] = '-') then i + 2 else i + 1 in let e = ref 0 and k = ref j in while !k < n && is_digit s.[!k] do if !e < 100_000 then e := (!e * 10) + (Char.code s.[!k] - Char.code '0'); incr k done; if neg then - !e else !e (* The index after a valid exponent ([e]/[E], optional sign, at least one digit) starting at [i], or [i] itself when there is none -- so an incomplete [5e] leaves the [e] out of the number. *) let exp_end s n i = if i < n && (s.[i] = 'e' || s.[i] = 'E') then let j = if i + 1 < n && (s.[i + 1] = '+' || s.[i + 1] = '-') then i + 2 else i + 1 in let k = skip_digits s n j in if k > j then k else i else i let is_space = function | ' ' | '\t' | '\n' | '\r' | '\011' | '\012' -> true | _ -> false (* The index after the run of whitespace starting at [i], which sqlite3 ignores at both ends of a number. *) let rec skip_space s n i = if i < n && is_space s.[i] then skip_space s n (i + 1) else i (* The value of the number spelled in [s] from [start] to [i3], an exponent read no further than [stop]: its sign at [start], its integer digits from [s0] to [i1], its fraction, after a [.] when [dot], to [i2], and its exponent to [i3]. It is [Int] for a pure integer that fits int64 and [Float] otherwise, through {!Decimal.real}: sqlite3AtoF's own reading, which truncates what its significand cannot hold rather than rounding it. OCaml's [float_of_string] rounds correctly instead, so on a literal of twenty significant digits the two land on neighbouring doubles. *) let spelled s ~start ~s0 ~i1 ~i2 ~i3 ~dot ~stop = let as_real () = let digits = String.sub s s0 (i1 - s0) ^ if dot then String.sub s (i1 + 1) (i2 - i1 - 1) else "" in let fraction = if dot then i2 - i1 - 1 else 0 in let exponent = (if i3 > i2 then exponent_at s stop i2 else 0) - fraction in Float (Decimal.real ~negative:(s.[start] = '-') ~digits ~exponent) in if dot || i3 > i2 then as_real () else match Int64.of_string_opt (String.sub s start (i3 - start)) with | Some v -> Int v | None -> as_real () (* The number [s] leads with and the index just past it, or [None] when none does. This is the one text-to-number reading in the package: the grammar [sqlite3AtoF] documents, an optional sign, digits, an optional single [.] and an optional [e]/[E] exponent, requiring at least one mantissa digit, after leading whitespace. Nothing else is a number, so ["inf"], ["nan"], ["0x10"] and ["1_0"] are not -- all four of which OCaml's own [float_of_string] and [Int64.of_string] accept, which is why neither may be handed a SQL string directly. Its value is {!spelled}. With [whole], a number followed by anything but whitespace is refused before its value is read. The number is looked for between [first] and [stop], and [found] is handed its extent where there is one, [none] answered where not. *) let scan ~whole s ~first ~stop ~found ~none = let n = stop in let start = skip_space s n first in let s0 = if start < n && (s.[start] = '+' || s.[start] = '-') then start + 1 else start in let i1 = skip_digits s n s0 in let i2, dot = if i1 < n && s.[i1] = '.' then (skip_digits s n (i1 + 1), true) else (i1, false) in (* the mantissa needs a digit before or after the [.]: with no integer digits ([i1 = s0]), only a fractional digit ([i2 > i1 + 1], past the [.]) qualifies *) if i1 = s0 && i2 <= i1 + 1 then none else let i3 = exp_end s n i2 in if whole && skip_space s n i3 <> n then none else found s ~start ~s0 ~i1 ~i2 ~i3 ~dot ~stop let with_value s ~start ~s0 ~i1 ~i2 ~i3 ~dot ~stop = Some (spelled s ~start ~s0 ~i1 ~i2 ~i3 ~dot ~stop, i3) let scan_number s = scan ~whole:false s ~first:0 ~stop:(String.length s) ~found:with_value ~none:None let leading_number s = match scan_number s with Some (v, _) -> v | None -> Int 0L let whole_number s = match scan ~whole:true s ~first:0 ~stop:(String.length s) ~found:with_value ~none:None with | Some (v, _) -> Some v | None -> None let spelt _ ~start:_ ~s0:_ ~i1:_ ~i2:_ ~i3:_ ~dot:_ ~stop:_ = true let spells_number s ~first ~length = scan ~whole:true s ~first ~stop:(first + length) ~found:spelt ~none:false let leading_integer s = let n = String.length s in let start = skip_space s n 0 in let neg = start < n && s.[start] = '-' in let s0 = if start < n && (s.[start] = '+' || neg) then start + 1 else start in let stop = skip_digits s n s0 in if stop = s0 then 0L else match Int64.of_string_opt (String.sub s start (stop - start)) with | Some v -> v | None -> if neg then Int64.min_int else Int64.max_int let text_of_float f = if Float.is_nan f then "NaN" else if f = Float.infinity then "Inf" else if f = Float.neg_infinity then "-Inf" else Decimal.to_string (Decimal.of_float f) let text_of_value = function | Null -> "" | Int n -> Int64.to_string n | Float f -> text_of_float f | Text s | Blob s -> s let shift dir x n = let n = Int64.to_int n in let lsl_ x n = if n >= 64 then 0L else Int64.shift_left x n in let asr_ x n = if n >= 64 then if x < 0L then -1L else 0L else Int64.shift_right x n in match dir with | `Left -> if n >= 0 then lsl_ x n else asr_ x (-n) | `Right -> if n >= 0 then asr_ x n else lsl_ x (-n) (* Storage-class ordering lives in the package that owns the value type, so the frontend and the engine core cannot drift apart on what a comparison means. *) let compare_values = Value.compare (* [compare_values] with a collating sequence applied to a text/text comparison. The sequence is irrelevant to non-text operands, which compare as usual. It is the resolved sequence and not the name a [COLLATE] spells: reading the name is the frontend's job, done once where the comparison is built, so this never re-reads a constant per pair compared. *) let compare_values_coll c a b = match (a, b) with | Text x, Text y -> Collation.compare_text c x y | _ -> compare_values a b (* A value's canonical form under the sequence [c]: text is mapped so two values equal under the sequence share a form (and order by it), anything else is unchanged. Lets a caller bucket / dedup by a collated key with plain equality. *) let collation_key c v = match v with Text s -> Text (Collation.key c s) | _ -> v (* The text a scalar function receives from sqlite3_value_text: the same conversion, cut at the first NUL. The accessor returns a bare C string and passes no length, so the bytes at and after the first NUL are not there to be read even though the value still carries them. *) let c_text_of_value v = let s = text_of_value v in match String.index_opt s '\000' with Some i -> String.sub s 0 i | None -> s (* sqlite3_value_numeric_type: the storage class a function argument lands on once numeric affinity has been applied to it. A number is itself; text is the number it spells in full, or nothing; a NULL and a blob are never numeric, since applyNumericAffinity is reached through a [MEM_Str] test. *) let numeric_type = function | (Int _ | Float _) as v -> Some v | Text s -> whole_number s | Null | Blob _ -> None (* Three-valued logic for WHERE/AND/OR/NOT/HAVING. A value's truth is the value "cast to a NUMERIC value in the same way as a CAST expression", false when that is zero and true otherwise, NULL staying unknown (lang_expr.html sec.14). Casting text to NUMERIC takes "the longest possible prefix ... that can be interpreted as" a number, so the section's own list holds: ['english'] and ['0'] are false where ['1english'] is true. This is a wider coercion than numeric affinity, which converts only a well-formed number and would make ['1english'] false. *) type tri = T | F | U let tri_of v = match v with | Null -> U | Int 0L -> F | Int _ -> T | Float f -> if f = 0. then F else T | Text _ | Blob _ -> ( match leading_number (text_of_value v) with | Int 0L | Float 0. -> F | _ -> T) let value_of_tri = function T -> Int 1L | F -> Int 0L | U -> Null let tri_and a b = match (a, b) with F, _ | _, F -> F | T, T -> T | _ -> U let tri_or a b = match (a, b) with T, _ | _, T -> T | F, F -> F | _ -> U let tri_not = function T -> F | F -> T | U -> U let not_value v = value_of_tri (tri_not (tri_of v)) let bool v = if v then Int 1L else Int 0L (* Whether [s] folded to upper case contains the upper-case [sub]: a literal substring test, folding byte by byte rather than a copy of [s]. *) let contains_sub_ci s sub = let n = String.length s and m = String.length sub in let rec at i j = j = m || Char.uppercase_ascii (String.unsafe_get s (i + j)) = String.unsafe_get sub j && at i (j + 1) in let rec from i = i + m <= n && (at i 0 || from (i + 1)) in from 0 type affinity = [ `Blob | `Integer | `Numeric | `Real | `Text ] let equal_affinity : affinity -> affinity -> bool = ( = ) (* A declared type name's storage affinity (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, anything else NUMERIC. *) let affinity_of_type ty : affinity = let has sub = contains_sub_ci ty sub in if has "INT" then `Integer else if has "CHAR" || has "CLOB" || has "TEXT" then `Text else if has "BLOB" || ty = "" then `Blob else if has "REAL" || has "FLOA" || has "DOUB" then `Real else `Numeric (* What [col] on [table] can hold, from the type it was declared with: the one place the storage-level schema is read as an affinity, so the planner, the typed query layer and a SQL frontend cannot disagree about what a column compares as. A backend that states no schema, or a name that is no column of it, describes something nothing can be assumed about -- and a comparison against that converts neither operand. *) let column_affinity cat table col = Option.bind (Spi.schema cat table) (fun s -> Option.map (fun (c : Spi.Schema.column) -> affinity_of_type c.Spi.Schema.decl_type) (List.find_opt (fun (c : Spi.Schema.column) -> Ident.equal c.Spi.Schema.name col) s.Spi.Schema.columns)) (* A real a NUMERIC/INTEGER column stores as an integer instead (sqlite3VdbeIntegerAffinity): one with no fractional part that the trip through int64 leaves unchanged, which a magnitude of 2^63 or more never is. So 2.0 is stored as 2, while 1.5 and 1e300 stay reals. *) let integer_affinity = function | Float f when Float.is_integer f && Float.abs f < 0x1p63 -> Int (Int64.of_float f) | v -> v (* Apply a column's storage affinity to a value being written (datatype3 sec.3): NUMERIC/INTEGER read a well-formed numeric TEXT as a number and store a whole real as an integer, TEXT renders a number as text, REAL coerces a number to float; a BLOB, NULL, and non-numeric text are unchanged. *) let apply_affinity (aff : affinity) v = let numify s = match whole_number s with Some n -> n | None -> v in match (aff, v) with | _, Null -> v | `Blob, _ -> v | `Text, (Int _ | Float _) -> Text (text_of_value v) | `Text, _ -> v | (`Numeric | `Integer), Text s -> integer_affinity (numify s) | (`Numeric | `Integer), _ -> integer_affinity v | `Real, Text s -> ( match whole_number s with Some n -> Float (float_of_value n) | None -> v) | `Real, Int i -> Float (Int64.to_float i) | `Real, _ -> v (* Leading numeric prefix of [s] as a float, 0. if none. *) let numeric_prefix s = float_of_value (leading_number s) (* doubleToInt64 (vdbemem.c): a real truncates toward zero, and one past the int64 range is held to it. OCaml leaves Int64.of_float unspecified there: x86-64 answers min_int for both signs, arm64 saturates. *) let int64_of_float f = if Float.is_nan f then 0L else if f <= -9223372036854775808. then Int64.min_int else if f >= 9223372036854775807. then Int64.max_int else Int64.of_float f (* CAST(v AS ty) per the target affinity (lang_expr.html#castexpr). NULL is preserved; text/blob to a numeric type parses a leading numeric prefix. *) let cast ty v = match (affinity_of_type ty, v) with | _, Null -> Null | `Text, _ -> Text (text_of_value v) | `Blob, Blob _ -> v | `Blob, _ -> Blob (text_of_value v) | `Integer, Int _ -> v | `Integer, Float f -> Int (int64_of_float f) | `Integer, _ -> Int (leading_integer (text_of_value v)) | `Real, Int i -> Float (Int64.to_float i) | `Real, Float _ -> v | `Real, _ -> Float (numeric_prefix (text_of_value v)) | `Numeric, (Int _ | Float _) -> v | `Numeric, _ -> let s = text_of_value v in let f = numeric_prefix s in (* sqlite3's NUMERIC affinity collapses an integral value to INTEGER: integer-syntax text up to the int64 range, but float-syntax text (with a '.' or exponent) only within +/-2^51, the lossless float<->int window of sqlite3RealSameAsInt. A non-integral or larger value stays REAL. *) let float_syntax = String.exists (function '.' | 'e' | 'E' -> true | _ -> false) s in let limit = if float_syntax then 0x1p51 else 9.2e18 in if Float.is_integer f && Float.abs f < limit then Int (Int64.of_float f) else Float f (* 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 ([computeNumericType]). This is what decides whether [%] answers a real, so it follows the prefix reading arithmetic uses: ['5.5x'] is real where ['5x'] and ['inf'] are not. *) let is_real = function | Float _ -> true | Text s | Blob s -> ( match leading_number s with Float _ -> true | _ -> false) | _ -> false (* Numeric affinity: integers and reals pass through; text becomes the integer or real it spells (an integer if it has no fractional/exponent part), or 0 if it is not numeric -- matching how sqlite3 coerces an operand in arithmetic. *) let numeric_affinity v = match v with | Int _ | Float _ -> v | _ -> ( match leading_number (text_of_value v) with | Int n -> Int n | Float f -> Float f | _ -> Int 0L) (* Comparison-affinity coercion: convert a text operand to a number only when the whole of it is one, otherwise leave it unchanged. Unlike {!numeric_affinity} (arithmetic, where non-numeric text is 0), a non-numeric string stays text so it does not spuriously equal a number. A blob is never coerced -- [applyNumericAffinity] converts a string and nothing else, so a blob keeps its place above every number in the storage-class order. *) let num_coerce v = match v with | Text s -> ( match whole_number s with Some n -> n | None -> v) | _ -> v (* Whether an affinity is one of the numeric ones (sqlite3IsNumericAffinity: NUMERIC, INTEGER and REAL sit above TEXT in the affinity order). *) let numeric_affinity_p = function | `Numeric | `Integer | `Real -> true | `Blob | `Text -> false (* The ONE affinity a comparison of two operands applies to both of them (sqlite3CompareAffinity, called from comparisonAffinity, src/expr.c): - both operands carry an affinity: NUMERIC if either of them is numeric, else BLOB - one carries one: that one, whichever end it is on - neither: none Not one affinity per operand. That distinction is the whole of the TEXT direction: a TEXT-affinity operand against one carrying none makes the comparison TEXT, which converts the operand that has no affinity of its own. *) let compare_affinity a b = match (a, b) with | Some a, Some b -> if numeric_affinity_p a || numeric_affinity_p b then Some `Numeric else Some `Blob | (Some _ as one), None | None, (Some _ as one) -> one | None, None -> None (* Apply a comparison's affinity to both its operands, as OP_Eq..OP_Ge do (src/vdbe.c) just before sqlite3MemCompare: - a numeric affinity reads a text operand as the number it spells ({!num_coerce}), leaving text that spells none as text - TEXT renders a numeric operand as text, and only when the other operand is already text: the flag it tests is MEM_Str on either register, so comparing two numbers under TEXT affinity compares them as numbers - BLOB and none convert nothing A blob is text to neither rule: applyNumericAffinity is reached through a MEM_Str test and a blob does not carry it, so a blob keeps its place above every number and every string whatever its bytes spell. *) let coerce_compare aff a b = let is_str = function Text _ -> true | _ -> false in let stringify v = match v with Int _ | Float _ -> Text (text_of_value v) | _ -> v in match aff with | Some (`Numeric | `Integer | `Real) -> (num_coerce a, num_coerce b) | Some `Text when is_str a || is_str b -> (stringify a, stringify b) | Some `Text | Some `Blob | None -> (a, b) (* A constant compared with a column has no affinity of its own, so the column's applies to it (datatype3.html section 4.2). *) let compared aff v = match (aff, v) with | (`Integer | `Real | `Numeric), Text _ -> num_coerce v | `Text, (Int _ | Float _) -> apply_affinity `Text v | _ -> v let key_value affs v = List.fold_left (fun v a -> compared a v) v affs (* The order a comparison operator puts its two operands in: the affinity applied to both, then the storage-class order under the sequence named. This is the whole of what [OP_Eq]..[OP_Ge] do between reading their registers and answering (src/vdbe.c), so every caller that decides a comparison itself rather than through the VM decides it the same way. *) let compare_operands ?aff ?coll a b = let a, b = coerce_compare aff a b in match coll with | Some c -> compare_values_coll c a b | None -> compare_values a b (* SQLite's NULL-safe equality [a IS b]: two NULLs are equal, a NULL and a non-NULL are not, else the ordinary comparison of the two operands -- which takes an affinity exactly as [=] does, [comparisonAffinity] (src/expr.c) listing [TK_IS] and [TK_ISNOT] beside [TK_EQ]. Always 1 or 0, never NULL. *) let is_value ?aff ?coll va vb = bool (match (va, vb) with | Null, Null -> true | Null, _ | _, Null -> false | _ -> compare_operands ?aff ?coll va vb = 0) (* [v] as an int64 -- SQLite's integer coercion of a value, sqlite3VdbeIntValue: a float as doubleToInt64 takes it, text its leading integer as sqlite3Atoi64 reads it, so '1e3' is 1, and anything non-numeric is 0. *) let intify = function | Int i -> i | Float f -> int64_of_float f | v -> leading_integer (text_of_value v) (* A real sum as sqlite3 keeps one since 3.43, with Kahan-Babuska-Neumaier compensation (func.c, kahanBabuskaNeumaierStep): [rsum] is the running total and [rerr] the low-order bits each addition lost, added back at the end. A plain running sum drifts in its last digits over many terms, so the same SUM would answer a different real here than in sqlite3. *) type kbn = { mutable rsum : float; mutable rerr : float } let kbn_add k r = let s = k.rsum in let t = s +. r in if Float.abs s > Float.abs r then k.rerr <- k.rerr +. (s -. t +. r) else k.rerr <- k.rerr +. (r -. t +. s); k.rsum <- t (* An integer past 2^52 is added in two parts, the multiple of 16384 and the rest, as sqlite3 adds it. *) let kbn_add_int k i = if i <= -4503599627370496L || i >= 4503599627370496L then ( let small = Int64.rem i 16384L in kbn_add k (Int64.to_float (Int64.sub i small)); kbn_add k (Int64.to_float small)) else kbn_add k (Int64.to_float i) (* The sum set to the integer [i] (kahanBabuskaNeumaierInit), split as [kbn_add_int] splits it but with the rest as the error term, which is not the state adding the two parts leaves. *) let kbn_init k i = if i <= -4503599627370496L || i >= 4503599627370496L then ( let small = Int64.rem i 16384L in k.rsum <- Int64.to_float (Int64.sub i small); k.rerr <- Int64.to_float small) else ( k.rsum <- Int64.to_float i; k.rerr <- 0.) let kbn_value k = if Float.is_finite k.rerr then k.rsum +. k.rerr else k.rsum (* The state of one SUM, TOTAL or AVG, stepped a value at a time by [add], or by the typed steps a compiled plan calls on a row it read unboxed, which are [add]'s own arms for an integer and a real. *) module Sum = struct type t = { name : string; mutable n : int; mutable isum : int64; mutable approx : bool; mutable overflowed : bool; k : kbn; } let v name = { name; n = 0; isum = 0L; approx = false; overflowed = false; k = { rsum = 0.; rerr = 0. }; } let start s = kbn_init s.k s.isum; s.approx <- true let add_int64 s i = if not s.approx then begin let r = Int64.add s.isum i in if s.isum >= 0L = (i >= 0L) && r >= 0L <> (s.isum >= 0L) then begin s.overflowed <- true; start s; kbn_add_int s.k i end else s.isum <- r end else kbn_add_int s.k i let add_real_value s r = if not s.approx then start s else s.overflowed <- false; kbn_add s.k r let add s v = s.n <- s.n + 1; (* Whether an input is an integer is decided after coercion, because sqlite3 reads it through sqlite3_value_numeric_type: a string spelling a whole number is an integer input, keeps the sum an integer, and stays liable to the overflow exception. It is [num_coerce] and not [numeric_affinity] that decides it -- only a whole string counts, so a fractional or exponent spelling is real and a string that is not a number is not an integer. The real sum still takes arithmetic affinity, where such a string folds as zero. *) match num_coerce v with | Int i -> add_int64 s i | _ -> add_real_value s (float_of_value (numeric_affinity v)) let add_real s r = s.n <- s.n + 1; add_real_value s r let add_int s i = s.n <- s.n + 1; add_int64 s (Int64.of_int i) (* [count] integers whose sum is [sum], each partial sum of which an int holds: before any real, [add] keeps the integers' exact sum, so adding them one by one leaves what adding their sum leaves. *) let add_ints s ~sum ~count = if s.approx then invalid_arg "Value_ops.Sum.add_ints: the sum is real"; s.n <- s.n + count; add_int64 s (Int64.of_int sum) (* The integer [i] taken off the real sum, the way sumInverse adds -i, which for min_int is two terms. *) let sub_real_int s i = if i <> Int64.min_int then kbn_add_int s.k (Int64.neg i) else ( kbn_add_int s.k Int64.max_int; kbn_add_int s.k 1L) (* func.c, sumInverse: an integer fold subtracts exactly until the difference leaves the int64 range, which is then an overflow as in [add_int64]; a real fold adds the value negated. Nothing here clears [approx] or [overflowed], so a real once folded keeps the answer real after it leaves. *) let remove s v = s.n <- s.n - 1; match num_coerce v with | Int i when not s.approx -> let r = Int64.sub s.isum i in if s.isum >= 0L <> (i >= 0L) && r >= 0L <> (s.isum >= 0L) then begin s.overflowed <- true; start s; sub_real_int s i end else s.isum <- r | Int i -> sub_real_int s i | _ -> kbn_add s.k (-.float_of_value (numeric_affinity v)) let total s = if s.approx then kbn_value s.k else Int64.to_float s.isum let finish s = match s.name with (* A running total that has gone NaN -- a fold over both infinities -- is answered as NULL, the way sqlite3's finalizers hand their double to sqlite3_result_double; an overflow to Inf is a value and stays. *) | "sum" -> if s.n = 0 then Null else if not s.approx then Int s.isum else if s.overflowed then Error.fail_runtime "integer overflow" else real (total s) | "total" -> real (total s) | _ -> if s.n = 0 then Null else real (total s /. float_of_int s.n) end (* sqlite3's GroupConcatCtx (func.c): the text joined so far, how many values it holds, the length of the separator the first value was stepped with, and, once a separator of another length is stepped, the length of the one before each value after the first. [started] is the buffer's mxAlloc: set by a step, cleared by an inverse that empties the text, and a step that finds it clear takes its value as a first one, with no separator. Lengths are in bytes, the text being UTF-8 as sqlite3_value_text reads it. *) module Group_concat = struct type t = { text : Buffer.t; mutable started : bool; mutable count : int; mutable first_sep : int; mutable sep_lengths : int list option; } let v () = { text = Buffer.create 64; started = false; count = 0; first_sep = 0; sep_lengths = None; } (* groupConcatStep *) let add g ?sep value = match value with | Null -> () | value -> let first = not g.started in g.started <- true; (match sep with | None -> if first then g.first_sep <- 1 else Buffer.add_char g.text ',' | Some sep when first -> g.first_sep <- String.length (text_of_value sep) | Some sep -> ( let n = match sep with | Null -> 0 | sep -> let s = text_of_value sep in Buffer.add_string g.text s; String.length s in (* pnSepLengths holds the separator before each value after the first: [count - 1] of them, then this one *) let before ls = List.init (max 0 (g.count - 1)) (fun i -> Option.value (List.nth_opt ls i) ~default:g.first_sep) in let track ls = if g.count > 0 then Some (before ls @ [ n ]) else Some [] in match g.sep_lengths with | Some ls -> g.sep_lengths <- track ls | None when n <> g.first_sep -> g.sep_lengths <- track [] | None -> ())); g.count <- g.count + 1; Buffer.add_string g.text (text_of_value value) (* groupConcatInverse *) let remove g value = match value with | Null -> () | value -> let n = String.length (text_of_value value) in g.count <- g.count - 1; let n = match g.sep_lengths with | Some ls when g.count > 0 -> g.sep_lengths <- Some (List.drop 1 ls); n + Option.value (List.nth_opt ls 0) ~default:0 | Some _ -> n | None -> n + g.first_sep in let len = Buffer.length g.text in let kept = if n >= len then "" else Buffer.sub g.text n (len - n) in Buffer.clear g.text; Buffer.add_string g.text kept; if kept = "" then ( g.started <- false; g.sep_lengths <- None) (* groupConcatValue *) let finish g = if Buffer.length g.text > 0 then Text (Buffer.contents g.text) else if g.count > 0 then Text "" else Null end (* SUM/AVG/MIN/MAX/TOTAL over the non-NULL argument values of a group, folded one value at a time (lang_aggfunc.html). SUM "is an integer value if all non-NULL inputs are integers"; any other input makes it "a floating point value which is an approximation of the mathematical sum", which TOTAL and AVG always are. A string or blob "that does not look like a number" is "interpreted as 0", so one stray value skews a fold rather than aborting the query: every input contributes the number it leads with, through {!numeric_affinity}. SUM and MIN/MAX over no values are NULL, TOTAL is 0.0. MIN/MAX are the first and last value an ORDER BY on the column would return, so they order by storage class and never coerce, and they keep the earliest of equal values. Being the only two folds here that compare, they are the only two that read [coll]: an ORDER BY on the column runs under a collating sequence, and so does the fold that answers its ends. SUM over all-integer values stays an integer, but -- unlike [+], which promotes on overflow -- sqlite3 raises "integer overflow" when the int64 sum leaves range. The integer sum runs alone until the first non-integer or the first overflow, which start the real sum from it (func.c, sumStep); a non-integer arriving after an overflow moves the answer onto the real sum, which never overflows, so the overflow is remembered rather than raised where it happens. *) (* The register a fold reads, as a value: the boxed path every fold has. *) let reg_value = Catalog.Register.to_value let numeric_acc ~coll name = let extreme keep = let cmp = match coll with Some c -> compare_values_coll c | None -> compare_values in let text_cmp = match coll with | Some c -> Collation.compare_text c | None -> String.compare in let best = ref Null and seen = ref false in let step v = if (not !seen) || keep (cmp v !best) then ( best := v; seen := true) in (* a text or an integer against a best of its class compares in place, and is boxed only where it wins, as minmaxStep copies only the winner (func.c); any other pair compares as values *) let step_reg (m : Catalog.Register.t) = match (m.kind, !best) with | Text, Text b when !seen -> if keep (text_cmp m.s b) then best := Text m.s | Int, Int b when !seen -> let i = Int64.of_int m.i in if keep (Int64.compare i b) then best := Int i | _ -> step (reg_value m) in (step, step_reg, fun () -> !best) in match name with | "sum" | "total" | "avg" -> let s = Sum.v name in let step_reg (m : Catalog.Register.t) = match m.kind with | Int -> Sum.add_int s m.i | Real -> Sum.add_real s m.r | Null | Bigint | Text | Blob -> Sum.add s (reg_value m) in (Sum.add s, step_reg, fun () -> Sum.finish s) | "min" -> extreme (fun c -> c < 0) | "max" -> extreme (fun c -> c > 0) | _ -> Error.fail_prepare "unknown aggregate %s()" name let numeric_agg name vals = let step, _, finish = numeric_acc ~coll:None name in List.iter step vals; finish () type agg_acc = Semantics.agg_acc = { step : Value.t array -> int -> unit; step_reg : Catalog.Register.t array -> int -> unit; finish : unit -> Value.t; } let of_values ~nargs ~step ~finish = let cell = Array.make (max 1 nargs) Null in let step_reg regs base = for i = 0 to nargs - 1 do cell.(i) <- reg_value regs.(base + i) done; step cell 0 in { step; step_reg; finish } (* One aggregate's fold over a group's rows, a row at a time (lang_aggfunc.html). [count] counts the rows whose first argument is not NULL, and a star [count] -- no argument at all, [nargs = 0] -- counts every row; [group_concat]/[string_agg] join the non-NULL first arguments; every other name folds them through {!numeric_acc}. Duplicate arguments, a FILTER and an in-call ORDER BY are the caller's to apply before a row gets here, so this is only "given the rows, fold them" and one call cannot mean two things depending on which caller runs it. [count] and {!numeric_acc}'s folds read a row of registers in place; the others read it as values ({!of_values}). The separator of [group_concat(X, Y)] is read per row, not once for the group: sqlite3 3.54.0 puts element i's own Y in front of element i, and never uses the first element's. lang_aggfunc.html only says Y is used as the separator between instances of X, so the binary settles what a Y that varies from row to row means. [coll] is the sequence the fold's own comparison runs under, which only a fold that compares reads: [min] and [max], the two sqlite3 marks SQLITE_FUNC_NEEDCOLL (src/func.c). Counting, summing and joining order nothing, so a sequence reaching one of those is spent on the caller's DISTINCT dedup or on nothing at all. *) (* group_concat: each non-NULL X, preceded by its own row's Y (a comma when there is no Y) unless it is the first. *) let concat_acc ~nargs = let g = Group_concat.v () in let step row base = let sep = if nargs > 1 then Some row.(base + 1) else None in Group_concat.add g ?sep row.(base) in of_values ~nargs ~step ~finish:(fun () -> Group_concat.finish g) let agg_acc name ~nargs ~coll = if nargs = 0 then let n = ref 0 in { step = (fun _ _ -> incr n); step_reg = (fun _ _ -> incr n); finish = (fun () -> Int (Int64.of_int !n)); } else match name with | "count" -> let n = ref 0 in { step = (fun row base -> match row.(base) with Null -> () | _ -> incr n); step_reg = (fun regs base -> if not (Catalog.Register.is_null regs.(base)) then incr n); finish = (fun () -> Int (Int64.of_int !n)); } | "group_concat" | "string_agg" -> concat_acc ~nargs | _ -> let step, step_reg, finish = numeric_acc ~coll name in { step = (fun row base -> match row.(base) with Null -> () | v -> step v); step_reg = (fun regs base -> let m = regs.(base) in if not (Catalog.Register.is_null m) then step_reg m); finish; } (* The distinct values of [vs], by {!compare_values} equality, keeping the first occurrence -- a [DISTINCT] aggregate's argument values. *) let distinct_values vs = let seen = ref [] in List.filter (fun v -> if List.exists (fun u -> compare_values u v = 0) !seen then false else ( seen := v :: !seen; true)) vs (* LIKE and GLOB, ported from sqlite3's func.c (patternCompare, likeFunc). Both operands are C strings, read as sqlite3Utf8Read (utf.c) reads code points: the byte at the end reads as the NUL that ends them. *) let c_byte s i = if i < String.length s then Char.code (String.unsafe_get s i) else 0 (* sqlite3Utf8Trans1: the value bits of a lead byte from 0xc0 up. *) let utf8_lead b = if b < 0xe0 then b land 0x1f else if b < 0xf0 then b land 0x0f else if b < 0xf8 then b land 0x07 else if b < 0xfc then b land 0x03 else if b < 0xfe then b land 0x01 else 0 (* The code point at [i], as sqlite3Utf8Read decodes it: a byte below 0xc0 is itself, a lead byte takes every continuation byte after it (in 32 bits), and a result below 0x80, a surrogate, 0xfffe or 0xffff is 0xfffd. *) let utf8_char s i = let b = c_byte s i in if b < 0xc0 then b else begin let c = ref (utf8_lead b) and j = ref (i + 1) in while c_byte s !j land 0xc0 = 0x80 do c := ((!c lsl 6) + (c_byte s !j land 0x3f)) land 0xffff_ffff; incr j done; let c = !c in if c < 0x80 || c land 0xffff_f800 = 0xd800 || c land 0xffff_fffe = 0xfffe then 0xfffd else c end (* The offset past the character at [i] (SQLITE_SKIP_UTF8). *) let utf8_next s i = if c_byte s i < 0xc0 then i + 1 else begin let j = ref (i + 1) in while c_byte s !j land 0xc0 = 0x80 do incr j done; !j end (* sqlite3Utf8CharLen: the characters before the first NUL. *) let utf8_length s = let rec go i n = if c_byte s i = 0 then n else go (utf8_next s i) (n + 1) in go 0 0 let ascii_lower c = if c >= 0x41 && c <= 0x5a then c + 0x20 else c let ascii_upper c = if c >= 0x61 && c <= 0x7a then c - 0x20 else c (* sqlite3's compareInfo with the matchOther argument: the run and one-character wildcards (0 when an escape has turned one off), whether [[..]] classes exist, ASCII case folding, and the escape (or [[]) code point, 0 for none. *) type pattern = { all : int; one : int; set : bool; nocase : bool; other : int } let glob_pattern = { all = 0x2a; one = 0x3f; set = true; nocase = false; other = 0x5b } let like_pattern ?(escape = 0) () = { all = (if escape = 0x25 then 0 else 0x25); one = (if escape = 0x5f then 0 else 0x5f); set = false; nocase = true; other = escape; } (* patternCompare's three answers. *) let pc_match = 0 let pc_nomatch = 1 let pc_nowildcard = 2 (* The members of a class from [pi] up to its []] against the code point [c], [prior] the last single member (0 after a range) and [seen] whether one matched: the offset past the []], negated when [c] matched none, and 0 when no []] closes the class. *) let rec class_members p pi c ~prior ~seen = let c2 = utf8_char p pi in let pi = utf8_next p pi in if c2 = 0 then 0 else if c2 = 0x5d then if seen then pi else -pi else let next = c_byte p pi in if c2 = 0x2d && next <> 0x5d && next <> 0 && prior > 0 then let hi = utf8_char p pi in class_members p (utf8_next p pi) c ~prior:0 ~seen:(seen || (c >= prior && c <= hi)) else class_members p pi c ~prior:c2 ~seen:(seen || c = c2) (* The class whose members start at [pi], just past its [[], against the code point [c]: the offset past its []] when [c] is in it (out of it, after a leading [^]), [-1] when it is not or no []] closes it. A []] first is a member. *) let class_match p pi c = let invert = utf8_char p pi = 0x5e in let pi = if invert then utf8_next p pi else pi in let close_first = utf8_char p pi = 0x5d in let pi = if close_first then utf8_next p pi else pi in let r = class_members p pi c ~prior:0 ~seen:(close_first && c = 0x5d) in if r = 0 || r > 0 = invert then -1 else abs r (* patternCompare: the pattern [p] from [pi] against [s] from [si]. After a run wildcard it looks in [s] for the next literal and recurses from each place it is found, and any answer but NOMATCH ends the search: a failure past a later run wildcard is NOWILDCARDMATCH, which no earlier one can mend. That bounds the work, where retrying every split is exponential in the wildcards. [escaped] is the offset past the last escaped character, which a one-character wildcard there does not act as. *) let rec pattern_compare k p pi s si escaped = let c = utf8_char p pi in if c = 0 then if c_byte s si = 0 then pc_match else pc_nomatch else let pi = utf8_next p pi in if c = k.all then pattern_run k p pi s si else if c = k.other && not k.set then let c = utf8_char p pi in if c = 0 then pc_nomatch else let pi = utf8_next p pi in pattern_literal k p pi s si pi c else if c = k.other then let c = utf8_char s si in if c = 0 then pc_nomatch else let pi = class_match p pi c in if pi < 0 then pc_nomatch else pattern_compare k p pi s (utf8_next s si) escaped else pattern_literal k p pi s si escaped c and pattern_literal k p pi s si escaped c = let c2 = utf8_char s si in if c = c2 || (k.nocase && c < 0x80 && c2 < 0x80 && ascii_lower c = ascii_lower c2) || (c = k.one && pi <> escaped && c2 <> 0) then pattern_compare k p pi s (utf8_next s si) escaped else pc_nomatch (* Past a run wildcard: further run wildcards are skipped and each one-character wildcard takes a character, then the next literal is searched for. *) and pattern_run k p pi s si = let c = utf8_char p pi in if c = 0 then pc_match else if c = k.all then pattern_run k p (utf8_next p pi) s si else if c = k.one then if c_byte s si = 0 then pc_nowildcard else pattern_run k p (utf8_next p pi) s (utf8_next s si) else if c = k.other && not k.set then let pi = utf8_next p pi in let c = utf8_char p pi in if c = 0 then pc_nowildcard else pattern_search k p (utf8_next p pi) s si c else if c = k.other then pattern_class_run k p pi s si else pattern_search k p (utf8_next p pi) s si c (* A class right after a run wildcard: tried from every character. *) and pattern_class_run k p pi s si = if c_byte s si = 0 then pc_nowildcard else let r = pattern_compare k p pi s si (-1) in if r <> pc_nomatch then r else pattern_class_run k p pi s (utf8_next s si) (* The places in [s] holding [c] (in either ASCII case when folding), each followed by the rest of the pattern from [pi]. *) and pattern_search k p pi s si c = if c < 0x80 then begin let lo = if k.nocase then ascii_lower c else c in let up = if k.nocase then ascii_upper c else c in let len = String.length s in let si = ref si and r = ref pc_nowildcard and go = ref true in while !go && !si < len do let b = Char.code (String.unsafe_get s !si) in incr si; if b = 0 then go := false else if b = lo || b = up then begin let m = pattern_compare k p pi s !si (-1) in if m <> pc_nomatch then begin r := m; go := false end end done; !r end else let c2 = utf8_char s si in if c2 = 0 then pc_nowildcard else let si = utf8_next s si in if c2 <> c then pattern_search k p pi s si c else let r = pattern_compare k p pi s si (-1) in if r <> pc_nomatch then r else pattern_search k p pi s si c let pattern_matches k pattern s = pattern_compare k pattern 0 s 0 (-1) = pc_match (* SQL [LIKE], as sqlite3's patternCompare with likeInfoNorm. *) let like_match ?escape pattern s = pattern_matches (like_pattern ?escape ()) pattern s (* SQL [GLOB], as sqlite3's patternCompare with globInfo. *) let glob_match pattern s = pattern_matches glob_pattern pattern s (* SQLITE_MAX_LIKE_PATTERN_LENGTH, the default of SQLITE_LIMIT_LIKE_PATTERN_LENGTH. *) let like_pattern_limit = 50_000 (* likeFunc's first check: the pattern's sqlite3_value_bytes, every byte of its text before any NUL cut, NULL included. *) let check_pattern_length b = let n = match b with Null -> 0 | v -> String.length (text_of_value v) in if n > like_pattern_limit then Error.fail_runtime "LIKE or GLOB pattern too complex" (* [a LIKE b]: as likeFunc (func.c) calls it, like(b, a, escape). The pattern length is checked first, then the escape: NULL answers NULL, anything but one UTF-8 character is refused, and the code point it decodes to is the escape. Then NULL if either operand is NULL, else the match as 1/0. Subject, pattern and escape are read through sqlite3_value_text, so all three are C strings and a NUL in any of them ends it. *) let like_op ?escape a b = check_pattern_length b; let escape = match escape with | None -> Some 0 | Some Null -> None | Some e -> let e = c_text_of_value e in if utf8_length e <> 1 then Error.fail_runtime "ESCAPE expression must be a single character"; Some (utf8_char e 0) in match (escape, a, b) with | None, _, _ | _, Null, _ | _, _, Null -> Null | Some escape, _, _ -> bool (like_match ~escape (c_text_of_value b) (c_text_of_value a)) (* [a GLOB b]: likeFunc with globInfo, so the same pattern length check, then NULL if either operand is NULL, else the match as 1/0. *) let glob_op a b = check_pattern_length b; match (a, b) with | Null, _ | _, Null -> Null | _ -> bool (glob_match (c_text_of_value b) (c_text_of_value a)) (* [a || b]: NULL if either operand is NULL, else the text forms concatenated. *) let concat_op a b = match (a, b) with | Null, _ | _, Null -> Null | _ -> Text (text_of_value a ^ text_of_value b)