Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(* SQLite's built-in scalar and table-valued functions, over {!Catalog.Value.t}. A pure value-level layer (no AST, no evaluator): the dispatcher {!apply} maps a function name and its already-evaluated argument values to a result, sharing the value semantics in {!Value_ops}, so every caller applies a function the same way. *)
open Catalog.Valueopen Value_ops
type value = Catalog.Value.t
let series_cap = 10_000_000let format_cap = 1_000_000
(* [generate_series(start [, stop [, step]])] yields one [value] column from [start] to [stop] inclusive, stepping by [step], as seriesFilter computes it (series.c): each argument read as sqlite3_value_int64 reads it, a NULL one giving no rows, an absent [stop] 4294967295, a zero or absent [step] 1, and a negative one walking down from [start]. The span is counted unsigned, so no range wraps. A range of more than [series_cap] rows cannot be materialised eagerly and is refused rather than hanging. *)let generate_series_rows (args : value list) : value list list = let start, stop, step = match args with | [] -> Catalog.Error.fail_prepare "first argument to \"generate_series()\" missing or unusable" | [ a ] -> (a, Int 4294967295L, Int 1L) | [ a; b ] -> (a, b, Int 1L) | [ a; b; c ] -> (a, b, c) | _ -> Catalog.Error.fail_prepare "too many arguments on generate_series() - max 3" in if List.exists (function Null -> true | _ -> false) [ start; stop; step ] then [] else let start = intify start and stop = intify stop in let step = match intify step with 0L -> 1L | n -> n in let down = step < 0L in if (down && start < stop) || ((not down) && start > stop) then [] else (* both differences fit an unsigned int64, as does [|step|] *) let span = if down then Int64.sub start stop else Int64.sub stop start in let stride = if down then Int64.neg step else step in let count = Int64.succ (Int64.unsigned_div span stride) in if count = 0L || Int64.unsigned_compare count (Int64.of_int series_cap) > 0 then Catalog.Error.fail_runtime "generate_series: range too large to materialise"; List.init (Int64.to_int count) (fun i -> [ Int (Int64.add start (Int64.mul step (Int64.of_int i))) ])
(* The table-valued functions, by name. *)let table_functions = [ "generate_series" ]
type table_function = { columns : string list; hidden : string list; rows : value list -> value list list; arguments : value list -> value list;}
(* The values generate_series's hidden columns hold for a call (series.c, seriesColumn): the arguments as seriesFilter reads them, an absent stop 4294967295 and a zero or absent step 1. *)let series_arguments args = let int = function Null -> Null | v -> Int (intify v) in let nth i default = match List.nth_opt args i with Some v -> int v | None -> default in let step = match nth 2 (Int 1L) with Int 0L -> Int 1L | v -> v in [ nth 0 Null; nth 1 (Int 4294967295L); step ]
let table_function name = match name with | "generate_series" -> { columns = [ "value" ]; hidden = [ "start"; "stop"; "step" ]; rows = generate_series_rows; arguments = series_arguments; } | _ -> Catalog.Error.fail_prepare "no such table-valued function: %s" name
let find_table_function name = if List.exists (Catalog.Ident.equal name) table_functions then Some (table_function (String.lowercase_ascii name)) else None
(* Number of UTF-8 characters (each malformed byte sequence counts as one), matching SQLite's length() on TEXT. *)let utf8_length s = Uutf.String.fold_utf_8 (fun n _ _ -> n + 1) 0 s
(* upper/lower fold ASCII only by default (lang_corefunc.html); other bytes pass through, matching SQLite built without ICU. *)let ascii_upper = String.map (fun c -> if c >= 'a' && c <= 'z' then Char.chr (Char.code c - 32) else c)
let ascii_lower = String.map (fun c -> if c >= 'A' && c <= 'Z' then Char.chr (Char.code c + 32) else c)
let round_value x n = let n = max 0 (min 30 n) in if (not (Float.is_finite x)) || Float.abs x > 4503599627370496.0 then Float x else if n = 0 then Float (Float.round x) else Float (Decimal.to_float (Decimal.of_float_places x ~places:n))
(* Trim characters in [set] (default a single space, per SQLite) from [side] of [s]. Byte-based, exact for ASCII; multi-byte trim sets are a TODO. *)let trim_value side set s = let is_trim c = String.contains set c in let n = String.length s in let i = ref 0 and j = ref n in if side <> `Right then while !i < !j && is_trim s.[!i] do incr i done; if side <> `Left then while !j > !i && is_trim s.[!j - 1] do decr j done; String.sub s !i (!j - !i)
let typeof_name = function | Null -> "null" | Int _ -> "integer" | Float _ -> "real" | Text _ -> "text" | Blob _ -> "blob"
(* sqlite3_value_double: the double a value reads as. Text and blob take the number they lead with (sqlite3VdbeRealValue through sqlite3AtoF, which stops at the first non-numeric character), so ['4x'] is 4.0 and text leading with no number is 0.0. This is the widest of the three readings of numeric text, and the one every function outside the math table coerces with. *)let as_float = function | Int i -> Int64.to_float i | Float f -> f | v -> ( match leading_number (text_of_value v) with | Int n -> Int64.to_float n | Float f -> f | _ -> 0.)
let trim_func side v set = match (v, set) with | Null, _ | _, Null -> Null | _ -> Text (trim_value side (text_of_value set) (text_of_value v))
(* Every function of the math table opens with sqlite3_value_numeric_type and answers NULL -- by setting no result at all -- for an argument that is not then INTEGER or REAL (func.c: math1Func, math2Func, logFunc, ceilingFunc, signFunc). So a NULL, a blob and text that does not spell a whole number have no answer, while text that does is read as its number. *)let numeric_arg v = Option.map float_of_value (numeric_type v)
(* A real-valued math function of one argument. Past the gate, math1Func calls libm and hands the double straight to sqlite3_result_double, which stores a REAL unless it is a NaN ({!Value_ops.real}). An overflow to an infinity is an ordinary REAL: the errno check lang_mathfunc.html describes is not in the implementation. *)let math1 f v = match numeric_arg v with None -> Null | Some x -> Value_ops.real (f x)
let math2 f a b = match (numeric_arg a, numeric_arg b) with | Some x, Some y -> Value_ops.real (f x y) | _ -> Null
(* The logarithms are the ones that reject the argument rather than the result: logFunc returns with no result for an argument at or below zero, so ln(0) is NULL and never the -Inf libm answers. In the two-argument log(B,X) the base must clear the same bar and log(B) must be positive too, which rules out every base at or below 1. *)let log1 f v = match numeric_arg v with | Some x when x > 0. -> Value_ops.real (f x) | _ -> Null
let log2_arg b x = match (numeric_arg b, numeric_arg x) with | Some b, Some x when b > 0. && log b > 0. && x > 0. -> Value_ops.real (log x /. log b) | _ -> Null
(* ceil/floor/trunc are the ones that keep the storage class the gate landed on: ceilingFunc returns an INTEGER argument unchanged and rounds a REAL to a REAL (func7.test: floor(17) -> 17, ceil(42.2) -> 43.0). Numeric text takes whichever class it spells, so ceil('4') is the integer 4 and ceil('4.2') the real 5.0. *)let round_like f v = match numeric_type v with | None -> Null | Some (Int _ as n) -> n | Some n -> Value_ops.real (f (float_of_value n))
(* SQLite hex() and the X'..' blob literal use uppercase hex; Hex.encode is lowercase. *)let hex_of_string s = String.uppercase_ascii (Hex.encode s)
(* Code point of the first character of a UTF-8 string, for unicode(). *)let first_cp s = Uutf.String.fold_utf_8 (fun acc _ d -> match acc with | Some _ -> acc | None -> ( match d with | `Uchar u -> Some (Uchar.to_int u) | `Malformed _ -> Some (Uchar.to_int Uchar.rep))) None s
let fn_coalesce args = match List.find_opt (fun v -> v <> Null) args with | Some v -> v | None -> Null
(* NULL for NULL, else apply [f] to the text form. *)let fn_text_map f v = match v with Null -> Null | _ -> Text (f (text_of_value v))
(* length(X): characters for TEXT (lang_corefunc.html), bytes for BLOB, the length of the string form for numbers, NULL for NULL. lengthFunc walks the TEXT case as a C string and stops at the first NUL, where the BLOB case reads sqlite3_value_bytes and counts every byte. *)let fn_length v = match v with | Null -> Null | Text _ -> Int (Int64.of_int (utf8_length (c_text_of_value v))) | Blob s -> Int (Int64.of_int (String.length s)) | Int _ | Float _ -> Int (Int64.of_int (String.length (text_of_value v)))
(* octet_length(X): the number of bytes in X's text/blob representation (so multi-byte UTF-8 counts each byte), NULL for NULL. *)let fn_octet_length = function | Null -> Null | v -> Int (Int64.of_int (String.length (text_of_value v)))
(* unhex(X): the blob whose bytes are the hex digit pairs of X; NULL if X has an odd length or any non-hex character. unhexFunc walks a C string, so the digit count is of the bytes before the first NUL. *)let fn_unhex = function | Null -> Null | v -> let s = c_text_of_value v in let n = String.length s in if n mod 2 <> 0 || not (String.for_all Ascii.is_hex_digit s) then Null else begin let b = Bytes.create (n / 2) in for i = 0 to (n / 2) - 1 do Bytes.set b i (Char.chr (int_of_string ("0x" ^ String.sub s (2 * i) 2))) done; Blob (Bytes.unsafe_to_string b) end
(* zeroblob(N): a blob of N zero bytes, N clamped at 0. The argument is read as an integer with no NULL case of its own, so a NULL reads as 0 and the answer is the empty blob -- the same coercion randomblob() takes to its one-byte floor. *)let fn_zeroblob v = Blob (String.make (max 0 (Int64.to_int (intify v))) '\000')
(* The generator randomblob(N) draws from. sqlite3 keeps one per process, seeded from the operating system the first time anything asks it for bytes (sqlite3_randomness); this is one per domain, seeded the same way on first use, so two domains never share the mutable state and no run replays the last. Seeding a shared generator at load time would do neither. *)let entropy = Domain.DLS.new_key Random.State.make_self_initlet random_bits () = Random.State.bits64 (Domain.DLS.get entropy)
(* randomblob(N): a blob of N pseudo-random bytes, "if N is less than 1 then a 1-byte random blob is returned" (lang_corefunc.html). N is coerced like any other numeric argument, so NULL reads as zero and lands on that floor. *)let fn_randomblob v = let n = max 1 (Int64.to_int (intify v)) in let state = Domain.DLS.get entropy in Blob (String.init n (fun _ -> Char.chr (Random.State.bits state land 0xff)))
(* random(): "a pseudo-random integer between -9223372036854775808 and +9223372036854775807" (lang_corefunc.html), which is 64 random bits read as a signed integer, from the generator randomblob() already draws from. *)let fn_random () = Int (random_bits ())
(* instr(X, Y) as instrFunc computes it (func.c): the 1-based position of the first Y in X, 0 if there is none, 1 for an empty Y, NULL if either is NULL. Two blobs are searched by byte; anything else is read as text, a blob's bytes as they are, and searched by character, a match starting only where a character does. *)let fn_instr x y = match (x, y) with | Null, _ | _, Null -> Null | _ -> let text = match (x, y) with Blob _, Blob _ -> false | _ -> true in let hay = text_of_value x and needle = text_of_value y in let nh = String.length hay and nn = String.length needle in let next i = if text then ( let j = ref (i + 1) in while !j < nh && Char.code hay.[!j] land 0xc0 = 0x80 do incr j done; !j) else i + 1 in let rec matches i k = k >= nn || (hay.[i + k] = needle.[k] && matches i (k + 1)) in let rec find i n = if nn > nh - i then 0 else if matches i 0 then n else find (next i) (n + 1) in Int (Int64.of_int (if nn = 0 then 1 else find 0 1))
(* The byte after the character at [i] of [s], as SQLITE_SKIP_UTF8 steps: a lead byte takes the continuation bytes after it, any other byte is a character alone. *)let skip_utf8 s i = let n = String.length s in if Char.code s.[i] < 0xc0 then i + 1 else let j = ref (i + 1) in while !j < n && Char.code s.[!j] land 0xc0 = 0x80 do incr j done; !j
(* The byte [k] characters on from [i] in [s], or its end. *)let advance s i k = let n = String.length s in let i = ref i and k = ref k in while !k > 0L && !i < n do i := skip_utf8 s !i; k := Int64.pred !k done; !i
(* The characters of [s], as SQLITE_SKIP_UTF8 counts them. *)let utf8_length s = let rec count i k = if i >= String.length s then k else count (skip_utf8 s i) (k + 1) in count 0 0
(* substr's start and length as substrFunc settles them (func.c), in int64 arithmetic: [p1] the 1-based start (negative counts back from [len]), [p2] the length (negative reads backwards from the start), to the 0-based offset and the count of units to take. *)let substr_range ~len p1 p2 = let p1, p2 = if p1 < 0L then let p1 = Int64.add p1 len in if p1 < 0L then (0L, if p2 < 0L then 0L else Int64.add p2 p1) else (p1, p2) else if p1 > 0L then (Int64.pred p1, p2) else if p2 > 0L then (p1, Int64.pred p2) else (p1, p2) in if p2 < 0L then let p2 = if p2 < Int64.neg p1 then p1 else Int64.neg p2 in (Int64.sub p1 p2, p2) else (p1, p2)
let substr_blob s p1 p2 = let len = Int64.of_int (String.length s) in let p1, p2 = substr_range ~len p1 p2 in let p1, p2 = if p1 >= len then (0L, 0L) else (p1, Int64.min p2 (Int64.sub len p1)) in Blob (String.sub s (Int64.to_int p1) (Int64.to_int p2))
(* substrFunc measures the text only when the start counts from its end. *)let substr_text s p1 p2 = let len = if p1 < 0L then Int64.of_int (utf8_length s) else 0L in let p1, p2 = substr_range ~len p1 p2 in let start = advance s 0 p1 in let stop = advance s start p2 in Text (String.sub s start (stop - start))
(* substr(X, Y[, Z]) as substrFunc computes it (func.c): Y and Z read as sqlite3_value_int64 reads them, Z the rest of X when omitted. A blob is cut in bytes; anything else is the text sqlite3_value_text gives, cut at its first NUL, in characters. A NULL argument answers NULL. *)let fn_substr x y rest = match (x, y, rest) with | Null, _, _ | _, Null, _ | _, _, Null :: _ -> Null | _ -> ( let p1 = intify y in let p2 = match rest with z :: _ -> intify z | [] -> Int64.max_int in match x with | Blob s -> substr_blob s p1 p2 | _ -> substr_text (c_text_of_value x) p1 p2)
(* abs(X): type-preserving; the most-negative integer overflows (func-18.32); text/blob coerce to a number. *)let fn_abs v = match v with | Null -> Null | Int i -> if i = Int64.min_int then Catalog.Error.fail_runtime "integer overflow" else Int (Int64.abs i) | Float f -> Float (Float.abs f) | _ -> Float (Float.abs (as_float v))
let fn_round1 v = match v with Null -> Null | _ -> round_value (as_float v) 0
let fn_round2 v d = match (v, d) with | Null, _ | _, Null -> Null | _ -> (* digits are read as an integer, held to 0..30 by [round_value] *) let n = intify d in round_value (as_float v) (if n > 30L then 30 else if n < 0L then 0 else Int64.to_int n)
(* replace(X, Y, Z): all non-overlapping; empty Y returns X; NULL is contagious. replaceFunc measures the pattern as a C string ([zPattern[0]==0] is the empty test), so a pattern that is one NUL is empty and the subject comes back whole -- with every byte, since the copy is bounded by sqlite3_value_bytes. *)let fn_replace x y z = match (x, y, z) with | Null, _, _ | _, Null, _ | _, _, Null -> Null | _ -> let hay = text_of_value x and needle = c_text_of_value y in if needle = "" then Text hay else Text (Re.replace_string Re.(compile (str needle)) ~by:(text_of_value z) hay)
(* sign(X): -1/0/+1 as an integer whatever the argument's class, past the same numeric gate (signFunc), so sign('4') is 1 where sign('abc') is NULL. *)let fn_sign v = match numeric_arg v with | None -> Null | Some f -> Int (if f < 0. then -1L else if f > 0. then 1L else 0L)
(* quote(X): the SQL literal for X. sqlite3QuoteValue renders the TEXT case through sqlite3_value_text and a C-string format, so it stops at the first NUL, while the BLOB case reads the bytes and their count. *)let fn_quote v = Text (match v with | Null -> "NULL" (* quote() renders an overflowed real as sqlite3's roundtrippable 9.0e+999 sentinel, not the "Inf" text form. *) | Float f when f = Float.infinity -> "9.0e+999" | Float f when f = Float.neg_infinity -> "-9.0e+999" | Int _ | Float _ -> text_of_value v | Text _ -> let s = c_text_of_value v in "'" ^ String.concat "''" (String.split_on_char '\'' s) ^ "'" | Blob s -> "X'" ^ hex_of_string s ^ "'")
(* char(X, ...) as charFunc writes it (func.c): each argument read as an integer, one outside 0..0x10ffff taken as U+FFFD, and every other encoded in the UTF-8 form for its value, a surrogate included. *)let fn_char args = let b = Buffer.create 8 in let add c = Buffer.add_char b (Char.chr c) in List.iter (fun v -> let x = intify v in let c = if x < 0L || x > 0x10ffffL then 0xfffd else Int64.to_int x in if c < 0x80 then add c else if c < 0x800 then ( add (0xc0 + ((c lsr 6) land 0x1f)); add (0x80 + (c land 0x3f))) else if c < 0x10000 then ( add (0xe0 + ((c lsr 12) land 0x0f)); add (0x80 + ((c lsr 6) land 0x3f)); add (0x80 + (c land 0x3f))) else ( add (0xf0 + ((c lsr 18) land 0x07)); add (0x80 + ((c lsr 12) land 0x3f)); add (0x80 + ((c lsr 6) land 0x3f)); add (0x80 + (c land 0x3f)))) args; Text (Buffer.contents b)
(* unicode(X): the code point of X's first character. unicodeFunc reads the C string and answers nothing when its first byte is the terminator, so a value whose first byte is a NUL has no first character. *)let fn_unicode v = match v with | Null -> Null | _ -> ( match first_cp (c_text_of_value v) with | Some cp -> Int (Int64.of_int cp) | None -> Null)
(* concat/concat_ws: NULL arguments are skipped (func9.test); concat_ws takes the separator first and is NULL if the separator is NULL. *)let fn_concat args = Text (String.concat "" (List.filter_map (function Null -> None | v -> Some (text_of_value v)) args))
let fn_concat_ws sep rest = match sep with | Null -> Null | _ -> Text (String.concat (text_of_value sep) (List.filter_map (function Null -> None | v -> Some (text_of_value v)) rest))
let fn_extreme ~take ~coll = function | [] -> Null | v :: vs -> if List.exists (fun x -> x = Null) (v :: vs) then Null else List.fold_left (fun best x -> if take (compare_values_coll coll best x) then x else best) v vs
(* printf/format: sqlite3's printf (sqlite/src/printf.c, sqlite3_str_vappendf with the arguments of an SQL call), conversion by conversion. An integer is read as sqlite3_value_int64 reads it, a real as sqlite3_value_double, a string as sqlite3_value_text, and a missing argument as 0, 0.0 or NULL. A conversion sqlite3 has no entry for ends the text where it stands. *)type fmt_spec = { left : bool; (** [-], or a negative [*] width *) sign : char option; (** [+] or space: what a non-negative number leads with *) alt : bool; (** [#], flag_alternateform *) alt2 : bool; (** [!], flag_altform2 *) zero : bool; (** [0] *) thousands : bool; (** [,], cThousand *) width : int; prec : int; (** [-1] when none was given *)}
let is_continuation c = Char.code c land 0xc0 = 0x80
let count_continuations s ~off ~len = let n = ref 0 in for i = off to off + len - 1 do if is_continuation s.[i] then incr n done; !n
(* The bytes of the first [n] characters of [s], as SQLITE_SKIP_UTF8 steps: a lead byte of 0xc0 or more takes the continuation bytes after it. *)let utf8_prefix s n = let len = String.length s in let rec go i n = if n = 0 || i >= len then i else if Char.code s.[i] >= 0xc0 then let rec skip j = if j < len && is_continuation s.[j] then skip (j + 1) else j in go (skip (i + 1)) (n - 1) else go (i + 1) (n - 1) in go 0 n
let spaces buf n = if n > 0 then Buffer.add_string buf (String.make n ' ')
(* The general output of a conversion: [s] in the field [width] wide, with spaces on the side [left] does not name. *)let emit buf ~left ~width s = let pad = width - String.length s in if pad > 0 && not left then spaces buf pad; Buffer.add_string buf s; if pad > 0 && left then spaces buf pad
(* The width adjust_width_for_utf8 makes under [!]: a field counted in characters, one more for each continuation byte of [s]. *)let utf8_width spec s = if spec.alt2 && spec.width > 0 then spec.width + count_continuations s ~off:0 ~len:(String.length s) else spec.width
(* Commas between the groups of three of [digits], counted from the right. *)let group_thousands digits = let n = String.length digits in let b = Buffer.create (n + (n / 3)) in String.iteri (fun i c -> if i > 0 && (n - i) mod 3 = 0 then Buffer.add_char b ','; Buffer.add_char b c) digits; Buffer.contents b
(* The digits of [mag], unsigned, in the base and case of [conv]. *)let radix_digits conv mag = match conv with | 'x' -> Fmt.str "%Lx" mag | 'X' | 'p' -> Fmt.str "%LX" mag | 'o' -> Fmt.str "%Lo" mag | _ -> Fmt.str "%Lu" mag
(* etORDINAL's suffix: st, nd and rd for a last digit of 1, 2 and 3 outside the teens, th otherwise. *)let ordinal_suffix mag = let x = Int64.to_int (Int64.unsigned_rem mag 10L) in let tens = Int64.to_int (Int64.unsigned_rem (Int64.unsigned_div mag 10L) 10L) in let x = if x >= 4 || tens = 1 then 0 else x in String.sub "thstndrd" (x * 2) 2
(* The prefix [#] puts before a non-zero radix: 0x, 0X or 0. *)let radix_prefix = function | 'x' | 'p' -> "0x" | 'X' -> "0X" | 'o' -> "0" | _ -> ""
(* The magnitude a conversion prints and the sign it leads with: a signed conversion of a negative value is its two's-complement negation with a minus, any other value is its own bits. *)let integer_sign spec conv v = let signed = conv = 'd' || conv = 'i' || conv = 'r' in if signed && Int64.compare v 0L < 0 then (Int64.neg v, Some '-') else if signed then (v, spec.sign) else (v, None)
let pad_zeros prec digits = let n = String.length digits in if prec > n then String.make (prec - n) '0' ^ digits else digits
(* The precision of an integer conversion: under the zero flag, the width less the sign, if that is more. *)let integer_precision spec sign = let sign_width = if sign = None then 0 else 1 in if spec.zero && spec.prec < spec.width - sign_width then spec.width - sign_width else spec.prec
(* The digits [conv] writes of [mag], an ordinal's suffix included, padded with zeros to [prec] and grouped by [,] for d, i and u. *)let integer_digits spec conv mag ~prec = let digits = radix_digits conv mag in let digits = if conv = 'r' then digits ^ ordinal_suffix mag else digits in let body = pad_zeros prec digits in if spec.thousands && (conv = 'd' || conv = 'i' || conv = 'u') then group_thousands body else body
(* etDECIMAL, etRADIX, etORDINAL and etPOINTER: d i u x X o r p. *)let fmt_integer buf spec conv v = let mag, sign = integer_sign spec conv v in let body = integer_digits spec conv mag ~prec:(integer_precision spec sign) in let body = match sign with Some c -> String.make 1 c ^ body | None -> body in let body = if spec.alt && not (Int64.equal mag 0L) then radix_prefix conv ^ body else body in emit buf ~left:spec.left ~width:spec.width body
(* An exponent as printf writes it: two digits, three past 100. *)let add_exponent b ~upper exp = Buffer.add_char b (if upper then 'E' else 'e'); Buffer.add_char b (if exp < 0 then '-' else '+'); let exp = abs exp in if exp >= 100 then Buffer.add_char b (Char.chr (Char.code '0' + (exp / 100))); let exp = exp mod 100 in Buffer.add_char b (Char.chr (Char.code '0' + (exp / 10))); Buffer.add_char b (Char.chr (Char.code '0' + (exp mod 10)))
(* A float's decimal as the conversion lays it out: the sign it leads with, its digits and the place of its point. *)type real = { lead : char option; digits : string; point : int }
(* The digits of the integer part of [r], from [e2], the power of ten of its leading place, down: with [,] a comma after each group of three, and zeros past the digits [r] has. Answers how many digits it took. *)let add_integer_part b spec r e2 = let n = String.length r.digits in if e2 < 0 then begin Buffer.add_char b '0'; 0 end else if spec.thousands then begin for e = e2 downto 0 do let j = e2 - e in Buffer.add_char b (if j < n then r.digits.[j] else '0'); if e mod 3 = 0 && e > 1 then Buffer.add_char b ',' done; min (e2 + 1) n end else begin let j = min (e2 + 1) n in Buffer.add_string b (String.sub r.digits 0 j); if e2 + 1 > j then Buffer.add_string b (String.make (e2 + 1 - j) '0'); j end
(* The digits after the point: the zeros before the first significant one, the digits left from [j], then, unless [rtz], zeros to the precision. *)let add_fraction b r ~e2 ~j ~prec ~rtz = let prec = ref prec in if e2 < -1 && !prec > 0 then begin let nn = min (-1 - e2) !prec in Buffer.add_string b (String.make nn '0'); prec := !prec - nn end; if !prec > 0 then begin let nn = min (String.length r.digits - j) !prec in if nn > 0 then begin Buffer.add_string b (String.sub r.digits j nn); prec := !prec - nn end; if !prec > 0 && not rtz then Buffer.add_string b (String.make !prec '0') end
(* [s] without its trailing zeros, and without its point once nothing follows it, which [!] keeps with one zero after it. *)let drop_trailing_zeros ~alt2 s = let stop = ref (String.length s) in while s.[!stop - 1] = '0' do decr stop done; if s.[!stop - 1] <> '.' then String.sub s 0 !stop else if alt2 then String.sub s 0 !stop ^ "0" else String.sub s 0 (!stop - 1)
(* [s] in the field: spaces on the side [-] does not name, or under the zero flag zeros after the sign. *)let pad_real buf spec ~signed s = let pad = spec.width - String.length s in if pad <= 0 then Buffer.add_string buf s else if spec.left then begin Buffer.add_string buf s; spaces buf pad end else if not spec.zero then begin spaces buf pad; Buffer.add_string buf s end else begin let adj = if signed then 1 else 0 in Buffer.add_string buf (String.sub s 0 adj); Buffer.add_string buf (String.make pad '0'); Buffer.add_string buf (String.sub s adj (String.length s - adj)) end
(* The layout of etFLOAT and etEXP once etGENERIC has chosen between them. *)let layout_real spec r ~exponential ~upper ~prec ~rtz = let b = Buffer.create 32 in Option.iter (Buffer.add_char b) r.lead; let e2 = if exponential then 0 else r.point - 1 in let j = add_integer_part b spec r e2 in let dp = prec > 0 || spec.alt || spec.alt2 in if dp then Buffer.add_char b '.'; let e2 = if e2 < 0 then e2 else -1 in add_fraction b r ~e2 ~j ~prec ~rtz; let s = Buffer.contents b in let s = if rtz && dp then drop_trailing_zeros ~alt2:spec.alt2 s else s in if not exponential then s else begin let b = Buffer.create (String.length s + 5) in Buffer.add_string b s; add_exponent b ~upper (r.point - 1); Buffer.contents b end
(* NaN and the infinities, which sqlite3FpDecode leaves to printf: NaN, or null under the zero flag; Inf with its sign. An infinity under the zero flag is no special value: it prints as 9e+999. *)let special_real spec x = if Float.is_nan x then Some (if spec.zero then "null" else "NaN") else if Float.abs x = Float.infinity && not spec.zero then if x < 0. then Some "-Inf" else Some (match spec.sign with | Some c -> String.make 1 c ^ "Inf" | None -> "Inf") else None
(* The digits sqlite3FpDecode gives [x] at [round], and the sign the conversion writes: none for a negative value that prints as zero under [#] in %f. *)let decode_real spec ~fixed ~round x = let negative, digits, point = if Float.abs x = Float.infinity then (x < 0., "9", 1000) else let d = Decimal.decode ~round ~max:(if spec.alt2 then 20 else 16) x in (d.negative, d.digits, d.point) in let lead = if not negative then spec.sign else if spec.alt && spec.sign = None && fixed && point <= round then None else Some '-' in { lead; digits; point }
(* etFLOAT, etEXP and etGENERIC: f e E g G. The digits are sqlite3FpDecode's ({!Decimal.decode}): at most 16 significant ones, 20 under [!], rounded half up on the decimal digits. *)let fmt_real buf spec conv x = match special_real spec x with | Some s -> emit buf ~left:spec.left ~width:spec.width s | None -> let prec = if spec.prec < 0 then 6 else spec.prec in let upper = conv = 'E' || conv = 'G' in let s = match conv with | 'f' -> let r = decode_real spec ~fixed:true ~round:(-prec) x in layout_real spec r ~exponential:false ~upper ~prec ~rtz:spec.alt2 | 'e' | 'E' -> let r = decode_real spec ~fixed:false ~round:(prec + 1) x in layout_real spec r ~exponential:true ~upper ~prec ~rtz:spec.alt2 | _ -> let prec = max prec 1 in let r = decode_real spec ~fixed:false ~round:prec x in let exp = r.point - 1 and rtz = not spec.alt in if exp < -4 || exp > prec - 1 then layout_real spec r ~exponential:true ~upper ~prec:(prec - 1) ~rtz else layout_real spec r ~exponential:false ~upper ~prec:(prec - 1 - exp) ~rtz in let signed = s.[0] = '-' || s.[0] = '+' || s.[0] = ' ' in pad_real buf spec ~signed s
(* etCHARX: the first character of [s], a whole UTF-8 character of up to four bytes, or one NUL byte for a NULL or empty argument, written as many times as the precision says, at least once; the width counts characters. *)let fmt_char buf spec s = let s = Option.value s ~default:"" in let len = if s = "" then 0 else if Char.code s.[0] land 0xc0 <> 0xc0 then 1 else let rec go i = if i < 4 && i < String.length s && is_continuation s.[i] then go (i + 1) else i in go 1 in let ch = if len = 0 then "\000" else String.sub s 0 len in let width = if spec.prec <= 1 then spec.width else begin let width = spec.width - (spec.prec - 1) in let width = if width > 1 && not spec.left then begin spaces buf (width - 1); 0 end else width in for _ = 1 to spec.prec - 1 do Buffer.add_string buf ch done; width end in emit buf ~left:spec.left ~width:(utf8_width { spec with alt2 = true; width } ch) ch
(* etSTRING: the argument's first [prec] bytes, or characters under [!]. *)let fmt_string buf spec s = let s = Option.value s ~default:"" in let len = if spec.prec < 0 then String.length s else if spec.alt2 then utf8_prefix s spec.prec else min spec.prec (String.length s) in let s = String.sub s 0 len in emit buf ~left:spec.left ~width:(utf8_width spec s) s
let hex_digits = "0123456789abcdef"
(* The bytes of [arg] a precision of [prec] takes: its characters under [!], its bytes otherwise, all of it when there is none. *)let precision_prefix spec arg = if spec.prec < 0 then String.length arg else if spec.alt2 then utf8_prefix arg spec.prec else min spec.prec (String.length arg)
(* [arg] with each [q] doubled; under [unistr] also a backslash doubled and a control character written as \u00XX. *)let escape_quotes ~q ~unistr arg = let b = Buffer.create (String.length arg + 8) in String.iter (fun c -> if c = q then ( Buffer.add_char b c; Buffer.add_char b c) else if unistr && c = '\\' then Buffer.add_string b "\\\\" else if unistr && Char.code c <= 0x1f then begin Buffer.add_string b "\\u00"; Buffer.add_char b hex_digits.[Char.code c lsr 4]; Buffer.add_char b hex_digits.[Char.code c land 15] end else Buffer.add_char b c) arg; Buffer.contents b
(* %q, %Q and %w, etESCAPE_q, etESCAPE_Q and etESCAPE_w: the argument's first [prec] bytes, or characters under [!], with each quote doubled; %Q puts them in single quotes, and is NULL's own "NULL"; a NULL is "(NULL)" to the others. Under [#], %q and %Q also write a control character as unistr() reads it, \u00XX, and a backslash as two, %Q only when a control character is there, quoting as unistr('...'). %w takes no [#]. *)let fmt_escape buf spec conv s = let arg, quoted = match s with | None -> ((if conv = 'Q' then "NULL" else "(NULL)"), false) | Some s -> (s, conv = 'Q') in let arg = String.sub arg 0 (precision_prefix spec arg) in let unistr = spec.alt && conv <> 'w' && (conv = 'q' || String.exists (fun c -> Char.code c <= 0x1f) arg) in let body = escape_quotes ~q:(if conv = 'w' then '"' else '\'') ~unistr arg in let s = match (quoted, unistr) with | true, true -> "unistr('" ^ body ^ "')" | true, false -> "'" ^ body ^ "'" | false, _ -> body in emit buf ~left:spec.left ~width:(utf8_width spec s) s
(* The bytes of [e] a JSON escape's precision takes: under [!] the precision counts characters, and a character it ends inside is taken whole. *)let json_extent spec e = let len = String.length e in if spec.prec < 0 then len else if not spec.alt2 then min spec.prec len else begin let px = ref spec.prec and i = ref 0 in while !i < !px && !i < len do if is_continuation e.[!i] then incr px; incr i done; if !i = !px then while !px < len && is_continuation e.[!px] do incr px done; min !px len end
(* [e]'s first [stop] bytes escaped as a JSON string's contents: a quote, a backslash and a control character after a backslash, as \b \t \n \f \r or \u00XX. *)let add_json_escaped buf e stop = let j = ref 0 in for i = 0 to stop - 1 do let ch = Char.code e.[i] in if ch <= 0x1f || e.[i] = '"' || e.[i] = '\\' then begin Buffer.add_substring buf e !j (i - !j); j := i + 1; Buffer.add_char buf '\\'; if ch > 0x1f then Buffer.add_char buf e.[i] else if (1 lsl ch) land 0x3700 <> 0 then Buffer.add_char buf "btn?fr".[ch - 8] else begin Buffer.add_string buf "u00"; Buffer.add_char buf hex_digits.[ch lsr 4]; Buffer.add_char buf hex_digits.[ch land 0xf] end end done; if !j < stop then Buffer.add_substring buf e !j (stop - !j)
(* The field of a JSON escape written from [start]: counted in characters under [!], padded on the left unless [-] or nothing was written. *)let pad_json buf spec start = let n = Buffer.length buf - start in let len = if spec.alt2 && n > 0 then n - count_continuations (Buffer.contents buf) ~off:start ~len:n else n in let sp = spec.width - len in if sp > 0 then if (not spec.left) && n > 0 then begin let written = Buffer.sub buf start n in Buffer.truncate buf start; spaces buf sp; Buffer.add_string buf written end else spaces buf sp
(* %j and %J, etESCAPE_j and etESCAPE_J: the argument's first [prec] bytes, or characters under [!], escaped as a JSON string's contents; %J puts them in double quotes, and is NULL's "null", where %j writes nothing. *)let fmt_json buf spec conv s = let start = Buffer.length buf in (match s with | None -> if conv = 'J' then Buffer.add_string buf "null" | Some e -> if conv = 'J' then Buffer.add_char buf '"'; add_json_escaped buf e (json_extent spec e); if conv = 'J' then Buffer.add_char buf '"'); if spec.width > 0 then pad_json buf spec start
(* A width or precision as the C int it is cast to: the low 32 bits, read signed. *)let c_int v = Int32.to_int (Int64.to_int32 v)
(* A literal width or precision: its digits read into an unsigned 32-bit value, wrapping, then its sign bit dropped. *)let literal_bound f n i = let j = ref i and v = ref 0 in while !j < n && f.[!j] >= '0' && f.[!j] <= '9' do v := ((!v * 10) + Char.code f.[!j] - Char.code '0') land 0xffffffff; incr j done; (!v land 0x7fffffff, !j)
let checked_bound v = if v > format_cap then Catalog.Error.fail_runtime "format: width or precision too large"; v
(* The flags, width and precision of the directive just past the [%] at [i], read as sqlite3's loop reads them, with the index of the conversion character, [n] when the text ends first. *)let fmt_parse_spec f n ~int_arg i = let at j = if j < n then f.[j] else '\000' in let left = ref false and sign = ref None and alt = ref false in let alt2 = ref false and zero = ref false and thousands = ref false in let width = ref 0 and prec = ref (-1) in let j = ref i and fin = ref false in while not !fin do (match at !j with | '-' -> left := true | '+' -> sign := Some '+' | ' ' -> sign := Some ' ' | '#' -> alt := true | '!' -> alt2 := true | '0' -> zero := true | ',' -> thousands := true | 'l' -> incr j; if at !j = 'l' then incr j; fin := true | '1' .. '9' -> let w, k = literal_bound f n !j in width := w; j := k; if at k <> '.' && at k <> 'l' then fin := true else decr j | '*' -> let w = c_int (int_arg ()) in if w < 0 then begin left := true; width := if w >= -2147483647 then -w else 0 end else width := w; if at (!j + 1) <> '.' && at (!j + 1) <> 'l' then begin incr j; fin := true end | '.' -> incr j; if at !j = '*' then begin let p = c_int (int_arg ()) in prec := if p >= 0 then p else if p >= -2147483647 then -p else -1; incr j end else begin let p, k = literal_bound f n !j in prec := p; j := k end; if at !j = 'l' then decr j else fin := true | _ -> fin := true); if not !fin then begin incr j; if !j >= n then fin := true end done; let spec = { left = !left; sign = !sign; alt = !alt; alt2 = !alt2; zero = !zero; thousands = !thousands; width = checked_bound !width; prec = checked_bound !prec; } in (spec, !j)
(* Write one conversion [conv] under [spec], taking its argument; [false] for a conversion sqlite3 has no entry for, where the text ends. *)let fmt_conv buf spec conv ~int_arg ~real_arg ~text_arg = match conv with | 'd' | 'i' | 'u' | 'x' | 'X' | 'o' | 'r' | 'p' -> fmt_integer buf spec conv (int_arg ()); true | 'f' | 'e' | 'E' | 'g' | 'G' -> fmt_real buf spec conv (real_arg ()); true | 'n' -> true | '%' -> emit buf ~left:spec.left ~width:spec.width "%"; true | 'c' -> fmt_char buf spec (text_arg ()); true | 's' | 'z' -> fmt_string buf spec (text_arg ()); true | 'q' | 'Q' | 'w' -> fmt_escape buf spec conv (text_arg ()); true | 'j' | 'J' -> fmt_json buf spec conv (text_arg ()); true | _ -> false
(* The readers of a printf call's arguments, each taking the next one as sqlite3_value_int64, sqlite3_value_double or sqlite3_value_text reads it, and a missing one as 0, 0.0 or NULL. *)let printf_args rest = let pending = ref rest in let arg () = match !pending with | x :: tl -> pending := tl; Some x | [] -> None in let int_arg () = match arg () with Some v -> intify v | None -> 0L in let real_arg () = match arg () with Some v -> as_float v | None -> 0. in let text_arg () = match arg () with | None | Some Null -> None | Some v -> Some (c_text_of_value v) in (int_arg, real_arg, text_arg)
let fn_format args = match args with | [] | Null :: _ -> Null | fmt :: rest -> let f = c_text_of_value fmt in let n = String.length f in let buf = Buffer.create (n * 2) in let int_arg, real_arg, text_arg = printf_args rest in let rec go i = if i >= n then () else if f.[i] <> '%' then begin let k = match String.index_from_opt f i '%' with Some k -> k | None -> n in Buffer.add_substring buf f i (k - i); go k end else if i + 1 >= n then Buffer.add_char buf '%' else let spec, j = fmt_parse_spec f n ~int_arg (i + 1) in let conv = if j < n then f.[j] else '\000' in if fmt_conv buf spec conv ~int_arg ~real_arg ~text_arg then go (j + 1) in go 0; (* sqlite3StrAccumFinish answers NULL for an accumulator that never grew, so a printf that writes nothing is NULL, not ''. *) if Buffer.length buf = 0 then Null else Text (Buffer.contents buf)
(* ── JSON (json1) ────────────────────────────────────────────── *)
(* The json1 functions by name ({!Json1}), each answering its value and whether sqlite3 tags it with the JSON subtype. *)let json_answer name args : Json1.answer option = let module J = Json1 in let blob = String.starts_with ~prefix:"jsonb" name in match (name, args) with | ("json" | "jsonb"), [ v ] -> Some (J.json ~blob v) | "json_quote", [ v ] -> Some (J.quote v) | ("json_array" | "jsonb_array"), args -> Some (J.array ~blob args) | ("json_object" | "jsonb_object"), args -> Some (J.object_ ~blob args) | "json_array_length", [ v ] -> Some (J.array_length v None) | "json_array_length", [ v; p ] -> Some (J.array_length v (Some p)) | "json_type", [ v ] -> Some (J.type_ v None) | "json_type", [ v; p ] -> Some (J.type_ v (Some p)) | "json_valid", [ v ] -> Some (J.valid v None) | "json_valid", [ v; f ] -> Some (J.valid v (Some f)) | "json_pretty", [ v ] -> Some (J.pretty v None) | "json_pretty", [ v; i ] -> Some (J.pretty v (Some i)) | "json_error_position", [ v ] -> Some (J.error_position v) | ("json_extract" | "jsonb_extract"), ([] | [ _ ]) -> Some (Null, false) | "json_extract", v :: paths -> Some (J.extract Extract v paths) | "jsonb_extract", v :: paths -> Some (J.extract Extract_blob v paths) | "->", [ v; p ] -> Some (J.extract Arrow_json v [ p ]) | "->>", [ v; p ] -> Some (J.extract Arrow_sql v [ p ]) | ("json_remove" | "jsonb_remove"), [] -> Some (Null, false) | ("json_remove" | "jsonb_remove"), v :: paths -> Some (J.remove ~blob v paths) | ("json_insert" | "jsonb_insert"), args -> Some (J.edit Insert ~blob args) | ("json_replace" | "jsonb_replace"), args -> Some (J.edit Replace ~blob args) | ("json_set" | "jsonb_set"), args -> Some (J.edit Set ~blob args) | ("json_array_insert" | "jsonb_array_insert"), args -> Some (J.edit Array_insert ~blob args) | _ -> None
let json_arrow ~as_text jv pv = match json_answer (if as_text then "->>" else "->") [ jv; pv ] with | Some (v, _) -> v | None -> Null
(* The name of a call answering [name]'s value with its JSON text as JSONB ({!Json1.embed}). It starts with a byte no SQL text spells, so only {!json_arguments} makes one. *)let json_tagged name = "\000" ^ name
(* Does argument [i] of [name] read the JSON subtype (sqlite3_value_subtype in json.c): every value of the constructors, an object's values and not its labels, an editor's values and not its paths. *)let reads_json_subtype name i = match name with | "json_array" | "jsonb_array" | "json_quote" -> true | "json_object" | "jsonb_object" -> i land 1 = 1 | "json_insert" | "jsonb_insert" | "json_replace" | "jsonb_replace" | "json_set" | "jsonb_set" | "json_array_insert" | "jsonb_array_insert" -> i > 0 && i land 1 = 0 | _ -> false
(* Does a call of [name] answer tagged text: sqlite3_result_subtype in json.c. *)let tags_json = function | "json" | "json_array" | "json_array_insert" | "json_extract" | "json_insert" | "json_object" | "json_quote" | "json_remove" | "json_replace" | "json_set" -> true | _ -> false
(* An argument whose value comes straight from a tagging call answers it as JSONB, through the branches a value flows through unchanged (a CASE, an [iif], a [coalesce] or [ifnull]), so the reader embeds JSON exactly where sqlite3's tag reaches it. *)let rec json_argument (e : Ast.expr) : Ast.expr = match e with | Func (f, a) when tags_json f -> Func (json_tagged f, a) (* the jsonb_ aggregates answer the JSONB of the text the json_ ones tag *) | Func ((("json_group_array" | "json_group_object") as f), a) -> Func ("jsonb" ^ String.sub f 4 (String.length f - 4), a) | Binary (Json_get, a, b) -> Func (json_tagged "->", [ a; b ]) | Func ((("coalesce" | "ifnull") as f), a) -> Func (f, List.map json_argument a) | Func ("iif", [ c; t; f ]) -> Func ("iif", [ c; json_argument t; json_argument f ]) | Case (base, branches, els) -> Case ( base, List.map (fun (c, r) -> (c, json_argument r)) branches, Option.map json_argument els ) | Collate (e, c) -> Collate (json_argument e, c) | e -> e
let json_arguments name args = let name = if String.length name > 1 && name.[0] = '\000' then String.sub name 1 (String.length name - 1) else name in List.mapi (fun i a -> if reads_json_subtype name i then json_argument a else a) args
let deterministic = function | "random" | "randomblob" | "changes" | "total_changes" | "last_insert_rowid" | "sqlite_version" | "sqlite_source_id" | "current_timestamp" | "current_date" | "current_time" -> false | _ -> true
(* The names SQLite's function table carries an aggregate under, at any argument count. A name is looked up at the count written and then, having missed, at any count at all (sqlite3FindFunction with nArg = -2, src/resolve.c), which is what tells a name of no function from a known one applied at an arity it does not have. *)let aggregate_name = function | "count" | "sum" | "avg" | "total" | "group_concat" | "string_agg" | "min" | "max" | "json_group_array" | "jsonb_group_array" | "json_group_object" | "jsonb_group_object" -> true | _ -> false
let aggregate name ~nargs = match name with | "count" -> nargs <= 1 | "sum" | "avg" | "total" | "min" | "max" -> nargs = 1 | "group_concat" -> nargs = 1 || nargs = 2 | "string_agg" -> nargs = 2 | "json_group_array" | "jsonb_group_array" -> nargs = 1 | "json_group_object" | "jsonb_group_object" -> nargs = 2 | _ -> false
let implemented = [ "abs"; "acos"; "acosh"; "asin"; "asinh"; "atan"; "atan2"; "atanh"; "ceil"; "ceiling"; "char"; "coalesce"; "concat"; "concat_ws"; "cos"; "cosh"; "current_date"; "current_time"; "current_timestamp"; "date"; "datetime"; "degrees"; "exp"; "floor"; "format"; "glob"; "hex"; "ifnull"; "iif"; "instr"; "json"; "json_array"; "json_array_insert"; "json_array_length"; "json_error_position"; "json_extract"; "json_insert"; "json_object"; "json_pretty"; "json_quote"; "json_remove"; "json_replace"; "json_set"; "json_type"; "json_valid"; "jsonb"; "jsonb_array"; "jsonb_array_insert"; "jsonb_extract"; "jsonb_insert"; "jsonb_object"; "jsonb_remove"; "jsonb_replace"; "jsonb_set"; "julianday"; "length"; "like"; "likelihood"; "likely"; "ln"; "log"; "log10"; "log2"; "lower"; "ltrim"; "match"; "max"; "min"; "mod"; "nullif"; "octet_length"; "pi"; "pow"; "power"; "printf"; "quote"; "radians"; "random"; "randomblob"; "replace"; "round"; "rtrim"; "sign"; "sin"; "sinh"; "sqrt"; "strftime"; "substr"; "tan"; "tanh"; "time"; "trim"; "trunc"; "typeof"; "unhex"; "unicode"; "unixepoch"; "unlikely"; "upper"; "zeroblob"; ]
(* Scalar builtins whose answer is the state of a connection -- its last insert rowid, its change counters, the library's own version -- which no value layer holds. A backend answers them through its catalog's [scalar_function]; they are functions all the same, and the schema is shared with sqlite3, so a resolver has to see them as functions, and {!apply} reached without a backend's answer says it has none. *)let of_connection = [ "changes"; "last_insert_rowid"; "sqlite_source_id"; "sqlite_version"; "total_changes"; ]
let exists name = let name = String.lowercase_ascii name in List.mem name implemented || List.mem name of_connection
let takes name ~nargs = match String.lowercase_ascii name with | "current_date" | "current_time" | "current_timestamp" | "pi" | "random" -> nargs = 0 | "abs" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp" | "floor" | "hex" | "json" | "jsonb" | "json_error_position" | "json_quote" | "length" | "likely" | "ln" | "log10" | "log2" | "lower" | "octet_length" | "quote" | "radians" | "randomblob" | "sign" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" | "typeof" | "unhex" | "unicode" | "unlikely" | "upper" | "zeroblob" -> nargs = 1 | "atan2" | "glob" | "ifnull" | "instr" | "likelihood" | "match" | "mod" | "nullif" | "pow" | "power" -> nargs = 2 | "iif" | "replace" -> nargs = 3 | "json_array_length" | "json_pretty" | "json_type" | "json_valid" | "log" | "ltrim" | "round" | "rtrim" | "trim" -> nargs = 1 || nargs = 2 | "like" -> nargs = 2 || nargs = 3 (* min and max are the scalar over two or more; the single-argument spelling is the fold, which {!aggregate} answers and no scalar arm reaches *) | "max" | "min" | "substr" -> nargs >= 2 | "coalesce" | "concat_ws" -> nargs >= 2 | "concat" -> nargs >= 1 (* The rest take every count: a variadic arm reads the whole argument list (char, the printf pair, the json constructors and the six date and time functions), and a name of {!of_connection} has no arm to state a count at all. *) | _ -> true
(* The names SQLite's function table carries a built-in window function under, at any argument count (src/window.c, windowFuncs[]). Read off {!Window.value}'s own arms, the way {!takes} is read off {!apply}'s: a name that is answered there is carried here, and a name carried here is answered there. *)let window_name = function | "cume_dist" | "dense_rank" | "first_value" | "lag" | "last_value" | "lead" | "nth_value" | "ntile" | "percent_rank" | "rank" | "row_number" -> true | _ -> false
let window name ~nargs = match String.lowercase_ascii name with | "cume_dist" | "dense_rank" | "percent_rank" | "rank" | "row_number" -> nargs = 0 | "first_value" | "last_value" | "ntile" -> nargs = 1 | "nth_value" -> nargs = 2 | "lag" | "lead" -> nargs >= 1 && nargs <= 3 | _ -> false
let window_misuse name = Fmt.str "misuse of window function %s()" name
let reads_the_clock name args = match String.lowercase_ascii name with | ("date" | "time" | "datetime" | "julianday" | "unixepoch" | "strftime") as name -> Datetime.reads_the_clock name args | _ -> false
let unresolved name = if List.mem name of_connection then Catalog.Error.fail_prepare "function %s() is not supported yet" name else if List.mem name implemented || aggregate_name name || window_name name then Catalog.Error.fail_prepare "wrong number of arguments to function %s()" name else Catalog.Error.fail_prepare "no such function: %s" name
let date_call ?now ?zone name = let over name args = Datetime.call ?now ?zone name args in match String.lowercase_ascii name with | ("date" | "time" | "datetime" | "julianday" | "unixepoch" | "strftime") as n -> Some (over n) | ("current_timestamp" | "current_date" | "current_time") as n -> let now_of = match n with | "current_timestamp" -> "datetime" | "current_date" -> "date" | _ -> "time" in Some (function [] -> over now_of [ Text "now" ] | _ -> unresolved n) | _ -> None
(* [coll] is the sequence the call compares its arguments under -- what [sqlite3GetFuncCollSeq] answers inside a function body. sqlite3 sets it from an argument's postfix COLLATE for the three functions marked SQLITE_FUNC_NEEDCOLL and leaves it the default for every other, which never asks. *)let apply ?(coll = Collation.default) name args = match (name, args) with | "coalesce", _ :: _ :: _ -> fn_coalesce args (* like(Y, X [, E]) is the function form of [X LIKE Y [ESCAPE E]] -- the pattern is the first argument (lang_corefunc.html). *) | "like", [ y; x ] -> like_op x y | "like", [ y; x; e ] -> like_op ~escape:e x y | "glob", [ y; x ] -> glob_op x y (* sqlite3 registers match() only for a virtual table to overload (sqlite3_overload_function, func.c:2354), and the stub it installs refuses every call as it runs (sqlite3InvalidFunction, main.c:2198) *) | "match", [ _; _ ] -> Catalog.Error.fail_runtime "unable to use function MATCH in the requested context" | "length", [ v ] -> fn_length v | "instr", [ x; y ] -> fn_instr x y | "substr", x :: y :: rest -> fn_substr x y rest | "upper", [ v ] -> fn_text_map ascii_upper v | "lower", [ v ] -> fn_text_map ascii_lower v | "abs", [ v ] -> fn_abs v | "round", [ v ] -> fn_round1 v | "round", [ v; d ] -> fn_round2 v d | "trim", [ v ] -> fn_text_map (trim_value `Both " ") v | "ltrim", [ v ] -> fn_text_map (trim_value `Left " ") v | "rtrim", [ v ] -> fn_text_map (trim_value `Right " ") v | "trim", [ v; set ] -> trim_func `Both v set | "ltrim", [ v; set ] -> trim_func `Left v set | "rtrim", [ v; set ] -> trim_func `Right v set | "replace", [ x; y; z ] -> fn_replace x y z | "ifnull", [ a; b ] -> if a <> Null then a else b (* nullif(X, Y): NULL if X = Y (so nullif(1, NULL) is 1, since 1=NULL is not true), else X. *) | "nullif", [ a; b ] -> ( (* NULLIF(a,b) is a unless a and b are non-NULL and compare equal *) match (a, b) with | Null, _ | _, Null -> a | _ -> if compare_values_coll coll a b = 0 then Null else a) | "typeof", [ v ] -> Text (typeof_name v) (* Optimizer-hint no-ops (lang_corefunc.html): they return their first argument unchanged. *) | ("likely" | "unlikely"), [ x ] -> x | "likelihood", [ x; _ ] -> x (* Math functions (lang_mathfunc.html); all real-valued except ceil/floor/ trunc, which keep the class of their argument. *) | "sqrt", [ v ] -> math1 sqrt v | ("pow" | "power"), [ a; b ] -> math2 Float.pow a b | "mod", [ a; b ] -> math2 Float.rem a b | ("ceil" | "ceiling"), [ v ] -> round_like Float.ceil v | "floor", [ v ] -> round_like Float.floor v | "trunc", [ v ] -> round_like Float.trunc v | "exp", [ v ] -> math1 exp v | "ln", [ v ] -> log1 log v | ("log10" | "log"), [ v ] -> log1 log10 v | "log2", [ v ] -> log1 Float.log2 v | "log", [ b; v ] -> log2_arg b v | "sin", [ v ] -> math1 sin v | "cos", [ v ] -> math1 cos v | "tan", [ v ] -> math1 tan v | "asin", [ v ] -> math1 asin v | "acos", [ v ] -> math1 acos v | "atan", [ v ] -> math1 atan v | "atan2", [ y; x ] -> math2 atan2 y x | "sinh", [ v ] -> math1 sinh v | "cosh", [ v ] -> math1 cosh v | "tanh", [ v ] -> math1 tanh v | "asinh", [ v ] -> math1 Float.asinh v | "acosh", [ v ] -> math1 Float.acosh v | "atanh", [ v ] -> math1 Float.atanh v | "degrees", [ v ] -> math1 (fun r -> r *. 180. /. Float.pi) v | "radians", [ v ] -> math1 (fun d -> d *. Float.pi /. 180.) v | "pi", [] -> Float Float.pi | "sign", [ v ] -> fn_sign v | "hex", [ v ] -> fn_text_map hex_of_string v | "unhex", [ v ] -> fn_unhex v | "octet_length", [ v ] -> fn_octet_length v | "zeroblob", [ v ] -> fn_zeroblob v | "randomblob", [ v ] -> fn_randomblob v | "random", [] -> fn_random () | "quote", [ v ] -> fn_quote v | "char", args -> fn_char args | "unicode", [ v ] -> fn_unicode v | "concat", _ :: _ -> fn_concat args | "concat_ws", sep :: (_ :: _ as rest) -> fn_concat_ws sep rest | ("printf" | "format"), args -> fn_format args | ( ( "json" | "jsonb" | "json_quote" | "json_array" | "jsonb_array" | "json_object" | "jsonb_object" | "json_array_length" | "json_type" | "json_valid" | "json_extract" | "jsonb_extract" | "->" | "->>" | "json_remove" | "jsonb_remove" | "json_insert" | "jsonb_insert" | "json_replace" | "jsonb_replace" | "json_set" | "jsonb_set" | "json_array_insert" | "jsonb_array_insert" | "json_pretty" | "json_error_position" ), args ) -> ( match json_answer name args with | Some (v, _) -> v | None -> unresolved name) | _, args when String.length name > 1 && name.[0] = '\000' -> ( let name = String.sub name 1 (String.length name - 1) in match json_answer name args with | Some a -> Json1.embed a | None -> unresolved name) (* Scalar max/min (two or more arguments): NULL if any argument is NULL, else the largest/smallest by SQLite value ordering under [coll]. *) | "max", (_ :: _ :: _ as args) -> fn_extreme ~take:(fun c -> c < 0) ~coll args | "min", (_ :: _ :: _ as args) -> fn_extreme ~take:(fun c -> c >= 0) ~coll args (* The date and time functions are one name-keyed lookup rather than arms of their own ({!date_call}), because a backend holding a clock has to be able to answer the same nine names from it. With none injected they answer here what they always did: 'now' is NULL, and 'localtime' and 'utc' are no-ops. *) | _ -> ( match date_call name with | Some date -> date args | None -> unresolved (String.lowercase_ascii name))