(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module type SEMANTICS = sig include Semantics.S val by_class : affinity option -> Catalog.Register.kind -> bool val above_numbers : affinity option -> string -> bool val spells_number : string -> first:int -> length:int -> bool val stores_reals : affinity -> bool module Sum : sig type t val v : string -> t val add : t -> Catalog.Value.t -> unit val add_real : t -> float -> unit val add_ints : t -> sum:int -> count:int -> unit val finish : t -> Catalog.Value.t end end module type S = sig type affinity type hooks type query type grouped type program type _ ty = Int : int ty | Real : float ty val run_grouped : ?hooks:hooks -> ?arrival:bool -> ?params:Catalog.Value.t array -> ?first:bool -> ?keep:(Catalog.Value.t -> bool) -> ?affinity:(int * int -> affinity option) -> grouped -> Catalog.Cursor.t array -> Catalog.Value.t list list type plan val plan : ?hooks:hooks -> query -> plan val order : plan -> int list val compiled : plan -> bool val iter_rows : ?params:Catalog.Value.t array -> ?regs:(program -> Catalog.Register.t array) -> plan -> Catalog.Cursor.t array -> f:(Row_core.row -> unit) -> unit end module Make (Sem : SEMANTICS) (I : Ir_core.S with type affinity = Sem.affinity and type collation = Sem.collation and type op = Sem.op and type raise_action = Sem.action) = struct module Cursor = Catalog.Cursor module Register = Catalog.Register module Value = Catalog.Value type affinity = Sem.affinity type hooks = I.hooks type query = I.query type grouped = I.grouped type program = I.program (* A query compiled to closures (Feeley and Lapalme, "Using closures for code generation", 1987): each node of the plan becomes, once, the OCaml closure that evaluates it, built from the closures of its children, so evaluating a row is a chain of direct calls with no opcode to dispatch on. The leaves read a source's columns through {!Cursor.reader}s taken when the plan is built. A column's storage class is the row's, not the schema's, so every typed path guards on the class it reads and hands a row of any other class to the register path the VM itself takes ({!Semantics.REGISTER.compare_with}, the semantics' value-level folds): the answer is the VM's on every row, and only the rows of the expected class are cheaper. *) (* A storage class an unboxed path reads, and how. *) type _ ty = Int : int ty | Real : float ty let class_of : type a. a ty -> Register.kind = function | Int -> Register.Int | Real -> Register.Real (* The value [r] read, of class [ty], and sqlite3MemCompare of it against [k], as {!Semantics.REGISTER.compare} orders two values of the class. Each case reads the cell and compares in place, so a real is never boxed on the way. *) let[@inline] get : type a. a ty -> Cursor.reader -> a = fun ty r -> match ty with Int -> r.int.int_value | Real -> r.real.real_value let[@inline] compare_to : type a. a ty -> Cursor.reader -> a -> int = fun ty r k -> match ty with | Int -> Int.compare r.int.int_value k | Real -> Float.compare r.real.real_value k let value : type a. a ty -> a -> Value.t = fun ty v -> match ty with Int -> Value.Int (Int64.of_int v) | Real -> Value.Float v (* ---- Operands ---------------------------------------------------------- *) (* An expression compiled for a run: [run ()] computes its value for the current row into [out], which is the same register at every row. *) type node = { run : unit -> unit; out : Register.t } (* A comparison operand: a column of the one source, a value fixed for the statement (a literal, a bound parameter), or an expression over the row. *) type operand = Column of Cursor.reader | Const of Register.t | Value of node let mem_of v = let m = Register.v () in Register.set_value m v; m let const_of v = Const (mem_of v) let nop () = () (* What a run binds a plan to: the reader of each column of its one source, the node loading each column into a register, its cursor, and the bound parameters. *) type binding = { col : int -> Cursor.reader; load : int -> node; cursor : Cursor.t; params : Value.t array; } (* The node of each column an expression reads: the column loaded as [Column] loads it, at most once a row however many expressions read it, [row] telling it when the cursor has moved. *) let loads (c : Cursor.t) row = let nodes = ref [] in fun j -> match List.assoc_opt j !nodes with | Some n -> n | None -> let out = Register.v () and seen = ref (-1) and column = c.column in let run () = if !seen <> !row then begin column j out; seen := !row end in let n = { run; out } in nodes := (j, n) :: !nodes; n (* A plan is compiled in two stages: the walk of the IR, which decides every node's code and raises [I.Unsupported] for a shape it does not compile, runs once, and leaves a function of the run's {!binding} that builds the node's closure with no further look at the IR. *) type 'a staged = binding -> 'a let param params i = if i >= 0 && i < Array.length params then params.(i) else Value.Null let require : I.hooks option -> I.hooks = function | Some h -> h | None -> raise I.Unsupported (* [f] of the values of the staged [args], each computed, left to right, before any is read. *) let call f args = fun bnd -> let args = List.map (fun a -> a bnd) args and out = Register.v () in let run () = List.iter (fun a -> a.run ()) args; Register.set_value out (f (List.map (fun a -> Register.to_value a.out) args)) in { run; out } (* [n] computed at the first row that asks for it, and read as it stands at every later one. *) let once n = let kept = ref false and run = n.run in let run () = if not !kept then begin run (); kept := true end in { n with run } (* Read the operand's current value into a register. *) let loader = function | Const m -> fun (_ : Register.t) -> m | Value n -> let run = n.run and out = n.out in fun (_ : Register.t) -> run (); out | Column r -> fun scratch -> ignore (r.read () : Register.kind); r.load scratch; scratch (* ---- Filters ----------------------------------------------------------- *) let holds : I.binop -> int -> bool = function | Eq -> fun c -> c = 0 | Ne -> fun c -> c <> 0 | Lt -> fun c -> c < 0 | Le -> fun c -> c <= 0 | Gt -> fun c -> c > 0 | Ge -> fun c -> c >= 0 | _ -> raise I.Unsupported (* The comparison the VM's [If_cmp]/[If_cmp_aff] decides: NULL on either side drops the row, and the two registers are ordered under the pair's affinity. *) let generic_compare ~settled op (cmp : I.comparison) a b = let holds = holds op in let order = match cmp.aff with | None -> Sem.compare | aff -> if settled then Sem.compare_settled aff else Sem.compare_with aff in let la = loader a and lb = loader b in let ma = Register.v () and mb = Register.v () in fun () -> let x = la ma and y = lb mb in (not (Register.is_null x || Register.is_null y)) && holds (order x y) (* A column against a constant of class [ty]: a row of that class compares unboxed -- {!Semantics.REGISTER.compare_with} orders two values of one numeric class by {!Semantics.REGISTER.compare} under every affinity -- and any other row takes the register path. *) let typed_compare : type a. a ty -> I.binop -> Cursor.reader -> a -> (unit -> bool) -> unit -> bool = fun ty op r k slow -> let holds = holds op and cls = class_of ty in fun () -> match r.read () with | Register.Null -> false | c when c = cls -> holds (compare_to ty r k) | _ -> slow () (* A column against a text or a blob [k]: a row of [k]'s class compares its bytes where the reader left them, an equality by length first, and any other row takes the register path. *) let bytes_compare op (k : Register.t) (r : Cursor.reader) slow = let cls = k.kind and s = k.s in let test = match op with | I.Eq -> fun () -> Cursor.equal_bytes (r.str ()) s | I.Ne -> fun () -> not (Cursor.equal_bytes (r.str ()) s) | op -> let h = holds op in fun () -> h (Cursor.compare_bytes (r.str ()) s) in fun () -> match r.read () with | Register.Null -> false | c when c = cls -> test () | _ -> slow () (* A column against a text [k] spelling no number under a numeric affinity, which leaves [k] as it is and orders every number below it ({!Semantics.REGISTER.compare_with}): a row of numbers, or of a text that spells one, compares below [k], any other text by its bytes where the reader left them, and a blob takes the register path. *) let below_numbers op (k : Register.t) (r : Cursor.reader) slow = let h = holds op and s = k.s in let below = h (-1) in fun () -> match r.read () with | Register.Null -> false | Register.Int | Register.Bigint | Register.Real -> below | Register.Text -> let c = r.str () in if Sem.spells_number c.bytes ~first:c.first ~length:c.length then below else h (Cursor.compare_bytes c s) | Register.Blob -> slow () let flip : I.binop -> I.binop = function | Lt -> Gt | Le -> Ge | Gt -> Lt | Ge -> Le | op -> op (* Two columns: a row holding integers on both sides, or reals on both, compares unboxed -- {!Semantics.REGISTER.compare_with} orders two values of one numeric class by {!Semantics.REGISTER.compare} under every affinity -- and any other row takes the register path, both values already read. *) let column_column op (cmp : I.comparison) (ra : Cursor.reader) (rb : Cursor.reader) = let h = holds op in let order = match cmp.aff with None -> Sem.compare | aff -> Sem.compare_with aff in let ma = Register.v () and mb = Register.v () in fun () -> match ra.read () with | Register.Null -> false | ka -> ( match (ka, rb.read ()) with | _, Register.Null -> false | Register.Int, Register.Int -> h (Int.compare ra.int.int_value rb.int.int_value) | Register.Real, Register.Real -> h (Float.compare ra.real.real_value rb.real.real_value) | _ -> ra.load ma; rb.load mb; h (order ma mb)) (* [b] as a comparison under [aff] reads it, converted once ({!Sem.settle}): a literal's copy at the run's start, a constant expression's value once it is first computed. *) let settle aff = function | Const k -> let m = Register.v () in Register.copy ~dst:m ~src:k; Sem.settle aff m; Const m | Value n -> let kept = ref false and run = n.run and out = n.out in let run () = run (); if not !kept then begin Sem.settle aff out; kept := true end in Value { n with run } | Column _ as b -> b (* A comparison [a op b]. Where [settled], [b] is a constant the comparison's affinity converts once ({!settle}) rather than at every row, and only [a] is read as a number at each. *) let compare_pred ~settled op (cmp : I.comparison) a b = let b = if settled then settle cmp.aff b else b in let column_const op r (k : Register.t) = (* the slow path re-reads nothing: the reader holds the row's value *) let scratch = Register.v () in let order = match cmp.aff with None -> Sem.compare | aff -> Sem.compare_with aff in let h = holds op in let slow () = r.Cursor.load scratch; (not (Register.is_null k)) && h (order scratch k) in let aff = cmp.aff in match k.kind with | Register.Null -> fun () -> false | Register.Int when Sem.by_class aff Int -> typed_compare Int op r k.i slow | Register.Real when Sem.by_class aff Real -> typed_compare Real op r k.r slow (* a text or a blob the affinity leaves as it is compares by its bytes against a row of its class *) | (Register.Blob | Register.Text) when Sem.by_class aff k.kind -> bytes_compare op k r slow | Register.Text when Sem.above_numbers aff k.s -> below_numbers op k r slow | _ -> ( fun () -> match r.read () with Register.Null -> false | _ -> slow ()) in match (a, b) with | Column r, Const k -> column_const op r k | Const k, Column r -> column_const (flip op) r k | Column ra, Column rb when Sem.by_class cmp.aff Int && Sem.by_class cmp.aff Real -> column_column op cmp ra rb | _ -> generic_compare ~settled op cmp a b (* A comparison the VM's jumps decide: an operator of the six, under the binary sequence. *) let compare_op op (cmp : I.comparison) = match op with | I.(Eq | Ne | Lt | Le | Gt | Ge) when Option.is_none cmp.coll -> () | _ -> raise I.Unsupported (* A staged node returns the closure it built, never a partial application of itself: a row's call of one goes through the currying stubs. *) let always () = true (* ---- Expressions ------------------------------------------------------- *) (* An expression's value for the current row, as the VM's program for it computes it: an operator's operands left to right, then its arithmetic ({!Semantics.REGISTER.arith}, the [Arith] opcode's) or the [hooks] operation its [Call] applies, once a row, into the node's own register. A literal's register is made with the plan, and a parameter's at each run. Any other constant is computed once a run ({!I.constant}): where the run first reaches it if it {!I.calls} a function, as the run is bound otherwise. *) let rec eval hooks e : node staged = match e with | I.Lit _ | I.Param _ -> node hooks e | e when I.constant e -> let n = node hooks e in if I.calls e then fun bnd -> once (n bnd) else fun bnd -> let n = n bnd in n.run (); { n with run = nop } | _ -> node hooks e and node hooks : I.expr -> node staged = function | I.Col (0, j) -> fun bnd -> bnd.load j | I.Rowid 0 -> fun bnd -> let rowid = bnd.cursor.rowid and out = Register.v () in let run () = match rowid () with | Some id -> Register.set_int64 out id | None -> Register.set_null out in { run; out } | I.Lit v -> let n = { run = nop; out = mem_of v } in fun _ -> n | I.Param i -> fun bnd -> { run = nop; out = mem_of (param bnd.params i) } | I.Arith (op, a, b) -> let op = I.arith_of op in let a = eval hooks a and b = eval hooks b in fun bnd -> let a = a bnd and b = b bnd and out = Register.v () in let ra = a.run and rb = b.run and x = a.out and y = b.out in let run () = ra (); rb (); Sem.arith op out x y in { run; out } | I.Null_value (want_null, e) -> let e = eval hooks e in fun bnd -> let e = e bnd and out = Register.v () in let re = e.run and x = e.out in let run () = re (); Register.set_value out (Value.Int (if Register.is_null x = want_null then 1L else 0L)) in { run; out } | I.Cast (e, ty) -> unary hooks ((require hooks).cast ty) e | I.Not e -> unary hooks Sem.not_ e | I.Cmp (op, c, a, b) -> binary hooks (Sem.compare_value (I.cmp_of op) c.aff c.coll) a b | I.Logic (And, a, b) -> binary hooks Sem.and_ a b | I.Logic (Or, a, b) -> binary hooks Sem.or_ a b | I.Logic (Op op, a, b) -> binary hooks ((require hooks).op op) a b | I.Is (c, a, b) -> binary hooks (Sem.is_eq c.aff c.coll) a b | I.In (a, c, cands) -> let in_list = Sem.in_list c.aff c.coll in call (fun vs -> in_list (List.hd vs) (List.tl vs)) (List.map (eval hooks) (a :: cands)) | I.Func (name, coll, args) -> let h = require hooks in call (h.call name coll) (List.map (eval hooks) args) | I.Case (arms, els) -> case hooks arms els | _ -> raise I.Unsupported (* A searched [CASE], as the VM codes it: each arm's test filters as a [WHERE] does, the first that holds has its result computed and copied out, and none holding computes the [ELSE], or gives NULL. A test or a result after the arm taken is not computed. *) and case hooks arms els = let arms = List.map (fun (p, r) -> (predicate hooks p, eval hooks r)) arms and els = Option.map (eval hooks) els in fun bnd -> let out = Register.v () in let arms = List.map (fun (p, r) -> (p bnd, r bnd)) arms in let last = match els with | None -> fun () -> Register.set_null out | Some e -> let e = e bnd in let re = e.run and x = e.out in fun () -> re (); Register.copy ~dst:out ~src:x in let arm (holds, r) next = let rr = r.run and x = r.out in fun () -> if holds () then begin rr (); Register.copy ~dst:out ~src:x end else next () in { run = List.fold_right arm arms last; out } and unary hooks f e = let e = eval hooks e in fun bnd -> let e = e bnd and out = Register.v () in let re = e.run and x = e.out in let run () = re (); Register.set_value out (f (Register.to_value x)) in { run; out } and binary hooks f a b = let a = eval hooks a and b = eval hooks b in fun bnd -> let a = a bnd and b = b bnd and out = Register.v () in let ra = a.run and rb = b.run and x = a.out and y = b.out in let run () = ra (); rb (); Register.set_value out (f (Register.to_value x) (Register.to_value y)) in { run; out } and operand hooks : I.expr -> operand staged = function | I.Col (0, j) -> fun b -> Column (b.col j) | I.Lit v -> let k = const_of v in fun _ -> k | I.Param i -> fun b -> const_of (param b.params i) | e -> let v = eval hooks e in fun b -> Value (v b) and predicate hooks : I.predicate -> (unit -> bool) staged = function | I.Always -> fun _ -> always | I.And (a, b) -> let a = predicate hooks a and b = predicate hooks b in fun bnd -> let a = a bnd and b = b bnd in fun () -> a () && b () | I.Compare (op, cmp, a, b) -> compare_op op cmp; (* under an affinity that converts text, a constant compared with a value that is not is read second and settled, as the VM's [If_cmp_settled] reads it *) let op, a, b, settled = match cmp.aff with | aff when Sem.settles aff && I.settles b && not (I.constant a) -> (op, a, b, true) | aff when Sem.settles aff && I.settles a && not (I.constant b) -> (flip op, b, a, true) | _ -> (op, a, b, false) in let a = operand hooks a and b = operand hooks b in fun bnd -> compare_pred ~settled op cmp (a bnd) (b bnd) (* [IS NULL] keeps the rows whose value is NULL, [IS NOT NULL] the others, which is all a row's storage class says *) | I.Null_test (want_null, e) -> ( let e = operand hooks e in fun bnd -> match e bnd with | Column r -> fun () -> Register.(r.read () = Null) = want_null | Value { run; out } -> fun () -> run (); Register.is_null out = want_null | Const m -> let keep = Register.is_null m = want_null in fun () -> keep) (* a row matches a disjunction where it matches either side, a NULL comparison matching neither *) | I.Or (a, b) -> let a = predicate hooks a and b = predicate hooks b in fun bnd -> let a = a bnd and b = b bnd in fun () -> a () || b () (* a bare [WHERE e] keeps the rows whose value is true as [If_not] tests it ({!Semantics.REGISTER.truth}) *) | I.Truthy e -> ( let e = operand hooks e in fun bnd -> match e bnd with | Value { run; out } -> fun () -> run (); Sem.truth out | Column r -> let m = Register.v () in fun () -> ignore (r.read () : Register.kind); r.load m; Sem.truth m | Const m -> let keep = Sem.truth m in fun () -> keep) (* ---- Aggregates -------------------------------------------------------- *) type agg = { step : unit -> unit; finish : unit -> Value.t } (* The value-level fold of [name] the semantics make, fed the reader's value of a row. *) let general name ~coll (r : Cursor.reader) = let acc : Semantics.agg_acc = Sem.aggregate name ~nargs:1 ~coll in let m = Register.v () and cell = [| Value.Null |] in let feed v = cell.(0) <- v; acc.step cell 0 in let row () = r.load m; feed (Register.to_value m) in (feed, row, acc.finish) (* MIN or MAX: the rows hold values of class [ty] until one does not, folded unboxed; from the first other one on, the value-level fold takes over, seeded with the extreme so far, which the earlier rows would have left it with. *) type 'a lane = { mutable best : 'a; mutable seen : bool; mutable spilt : bool; } let extreme : type a. a ty -> init:a -> string -> coll:_ -> Cursor.reader -> agg = fun ty ~init name ~coll r -> let better = if String.equal name "max" then fun c -> c > 0 else fun c -> c < 0 in let cls = class_of ty in let feed, row, finish = general name ~coll r in let l = { best = init; seen = false; spilt = false } in let spill () = l.spilt <- true; if l.seen then feed (value ty l.best) in let step () = match r.read () with | Register.Null -> () | c when c = cls && not l.spilt -> if (not l.seen) || better (compare_to ty r l.best) then begin l.best <- get ty r; l.seen <- true end | _ -> if not l.spilt then spill (); row () in let finish () = if l.spilt then finish () else if l.seen then value ty l.best else Value.Null in { step; finish } let count_star () = let n = ref 0 in { step = (fun () -> incr n); finish = (fun () -> Value.Int (Int64.of_int !n)); } let count (r : Cursor.reader) = let n = ref 0 in { step = (fun () -> match r.read () with Register.Null -> () | _ -> incr n); finish = (fun () -> Value.Int (Int64.of_int !n)); } (* SUM, TOTAL or AVG: the rows hold integers until one does not, summed into an [int] while every partial sum fits one; the first other row, or the first sum that would not fit, hands that exact sum to the value-level fold ({!Sem.Sum.add_ints}), which takes every later row, a real unboxed. Before any real, the value-level fold keeps an exact integer sum too, so it ends where it would have ended fed one row at a time. *) let sum name (r : Cursor.reader) = let s = Sem.Sum.v name in let isum = ref 0 and count = ref 0 and ints = ref true in let m = Register.v () in let flush () = if !ints then begin ints := false; if !count > 0 then Sem.Sum.add_ints s ~sum:!isum ~count:!count end in let value () = flush (); r.load m; Sem.Sum.add s (Register.to_value m) in let step () = match r.read () with | Register.Null -> () | Register.Int when !ints -> let v = r.int.int_value in let t = !isum + v in if !isum >= 0 = (v >= 0) && t >= 0 <> (v >= 0) then value () else begin isum := t; incr count end | Register.Real -> flush (); Sem.Sum.add_real s r.real.real_value | _ -> value () in { step; finish = (fun () -> flush (); Sem.Sum.finish s); } (* A node read as a column is: [read] computes it for the row, and its register answers the cells, the bytes and the load. *) let node_reader (n : node) : Cursor.reader = let int = { Cursor.int_value = 0 } and real = { Cursor.real_value = 0. } in let bytes = { Cursor.bytes = ""; first = 0; length = 0 } in let run = n.run and out = n.out in let read () = run (); (match out.kind with | Register.Int -> int.int_value <- out.i | Register.Real -> real.real_value <- out.r | _ -> ()); out.kind in let str () = bytes.bytes <- out.s; bytes.length <- String.length out.s; bytes in { Cursor.read; int; real; str; load = (fun m -> Register.copy ~dst:m ~src:out); } (* The reader of an aggregate's argument: a column's own, or the node of an expression over the row, computed when the fold reads it. *) let argument hooks (bnd : binding) = function | I.Col (0, j) -> bnd.col j | e -> node_reader (eval hooks e bnd) let compile_agg hooks bnd affinity (a : I.agg) = if a.distinct || Option.is_some a.filter || a.order <> [] then raise I.Unsupported; match (a.name, a.args) with | "count", [] -> count_star () | "count", [ e ] -> count (argument hooks bnd e) | (("min" | "max") as name), [ e ] -> ( (* The lane MIN/MAX starts in: a REAL column's values are reals, every other column's and expression's mostly integers. A wrong guess costs speed, never the answer. *) let r = argument hooks bnd e in match e with | I.Col (0, j) when match affinity (0, j) with | Some aff -> Sem.stores_reals aff | None -> false -> extreme Real ~init:0. name ~coll:a.coll r | _ -> extreme Int ~init:0 name ~coll:a.coll r) (* the lanes are {!SEMANTICS.Sum}'s, which {!Semantics.S.aggregate} folds these names through *) | (("sum" | "total" | "avg") as name), [ e ] -> sum name (argument hooks bnd e) | _ -> raise I.Unsupported let sequence = function | [||] -> fun () -> () | [| a |] -> a.step | [| a; b |] -> let a = a.step and b = b.step in fun () -> a (); b () | aggs -> fun () -> for i = 0 to Array.length aggs - 1 do aggs.(i).step () done (* ---- Plans ------------------------------------------------------------- *) (* How many times the plan reads each column of the source, by the column operands of its filter and of the expressions [exprs] it reads through readers. *) let column_uses filter exprs = let cols = ref [] in let expr = function I.Col (0, j) -> cols := j :: !cols | _ -> () in let rec pred = function | I.And (a, b) | I.Or (a, b) -> pred a; pred b | I.Compare (_, _, a, b) -> expr a; expr b | I.Null_test (_, e) | I.Truthy e -> expr e | _ -> () in pred filter; List.iter expr exprs; let cols = !cols in fun j -> List.length (List.filter (Int.equal j) cols) (* The reader of each column a plan reads: the source's own where one place reads it, and where several do, one that reads the row's value once and answers the others from it, [row] telling it when the cursor has moved. *) let columns (c : Cursor.t) row uses = let shared = ref [] in fun j -> if uses j < 2 then c.reader j else match List.assoc_opt j !shared with | Some r -> r | None -> let r = c.reader j in let seen = ref (-1) and kind = ref (Register.Null : Register.kind) in let r = { r with Cursor.read = (fun () -> if !seen <> !row then begin kind := r.read (); seen := !row end; !kind); } in shared := (j, r) :: !shared; r (* The groups of a GROUP BY, ordered as the VM orders them: by {!Value.compare}, under which an integer and the real of the same value are one key. *) module Groups = Map.Make (struct type t = Value.t let compare = Value.compare end) (* A group's aggregates, fresh for each group, over the plan's readers. *) type group = { aggs : agg array; step : unit -> unit } (* A GROUP BY's scan: each kept row's key read through [kr], a row whose key equals the previous row's stepping that row's group, any other finding or opening its group; a group keeps the key of the first row that opened it. The groups come out in key order, each as its key then its aggregates. *) let grouped_by (kr : Cursor.reader) ~group ~finish ~scan = let m = Register.v () in fun () -> let groups = ref Groups.empty in let last_key = ref Value.Null and last = ref None in scan (fun () -> ignore (kr.read () : Register.kind); kr.load m; let key = Register.to_value m in let grp = match !last with | Some grp when Value.compare !last_key key = 0 -> grp | _ -> let grp = match Groups.find_opt key !groups with | Some grp -> grp | None -> let grp = group () in groups := Groups.add key grp !groups; grp in last_key := key; last := Some grp; grp in grp.step ()); List.map (fun (key, grp) -> Array.append [| key |] (finish grp)) (Groups.bindings !groups) (* Whether the key loaded in [m] is the key [k] holds, as [Value.compare] decides: read in place where both are of one class, so a row of the current group boxes nothing. *) let same_key (m : Register.t) (k : Register.t) = match (m.kind, k.kind) with | Null, Null -> true | Int, Int -> m.i = k.i | Bigint, Bigint -> Int64.equal m.big k.big | Real, Real -> m.r = k.r | Text, Text | Blob, Blob -> String.equal m.s k.s | _ -> Value.compare (Register.to_value m) (Register.to_value k) = 0 (* A GROUP BY's scan over rows that come grouped, each group's rows one after another, as a loop that yields the GROUP BY's order reads them: one group is held at a time, closed when a row's key differs from the one it holds, and the groups come out in the order they arrived, each as its key, the first row's, then its aggregates. *) let adjacent_groups (kr : Cursor.reader) ~group ~finish ~scan = let m = Register.v () and held = Register.v () in fun () -> let out = ref [] and current = ref None in let close () = match !current with | Some (key, grp) -> out := Array.append [| key |] (finish grp) :: !out | None -> () in scan (fun () -> ignore (kr.read () : Register.kind); kr.load m; let grp = match !current with | Some (_, grp) when same_key m held -> grp | Some _ | None -> close (); let grp = group () in Register.copy ~dst:held ~src:m; current := Some (Register.to_value m, grp); grp in grp.step ()); close (); List.rev !out let compile ?hooks ~adjacent ~params ~affinity (g : I.grouped) (cursors : Cursor.t array) = (match (g.arities, g.joins, g.ncols, g.rep) with | [ _ ], [], 0, None when Array.length cursors = 1 -> () | _ -> raise I.Unsupported); (* one key column, compared binary; a COLLATE on it runs on the VM *) let key = match g.group_by with | [] -> None | [ I.Col (0, k) ] when List.for_all Option.is_none g.group_colls -> Some k | _ -> raise I.Unsupported in let c = cursors.(0) in let row = ref 0 in let col = columns c row (column_uses g.filter (g.group_by @ List.concat_map (fun (a : I.agg) -> a.args) g.aggs)) in let bnd = { col; load = loads c row; cursor = c; params } in let keep = predicate hooks g.filter bnd in let group () = let aggs = Array.of_list (List.map (compile_agg hooks bnd affinity) g.aggs) in { aggs; step = sequence aggs } in let finish grp = Array.map (fun a -> a.finish ()) grp.aggs in (* the source pushes its rows where it can ({!Cursor.iter}) *) let scan each = ignore (Cursor.iter c (fun () -> if keep () then each (); incr row) : int) in match key with | None -> (* no GROUP BY: one group, which answers even when no row is kept *) let grp = group () in fun () -> scan grp.step; [ finish grp ] | Some k -> (* the groups' aggregates are compiled as groups open, during the scan, so one is compiled here first: an aggregate this module does not compile has to send the plan to the VM before a cursor moves *) ignore (group () : group); if adjacent then adjacent_groups (col k) ~group ~finish ~scan else grouped_by (col k) ~group ~finish ~scan let run_grouped ?hooks ?(arrival = false) ?(params = [||]) ?(first = false) ?keep ?(affinity = fun _ -> None) g cursors = (* a scan that stops at its first row folds one row, which the VM folds without staging closures for it *) match if first then raise I.Unsupported else compile ?hooks ~adjacent:arrival ~params ~affinity g cursors with | run -> I.run_output ?hooks ~params g (run ()) | exception I.Unsupported -> I.run_grouped ?hooks ~arrival ~params ~first ?keep g cursors (* ---- Selects ----------------------------------------------------------- *) (* A projected value, as the VM's opcode for it writes it: a column into its output register by the source's own column read, as [Column] loads it, the row's identity as [Rowid] does, a constant as it stands; an expression is its node, whose register is the output. *) type projected = Write of (Register.t -> unit) | Node of node let projector hooks : I.expr -> (Cursor.t -> projected) staged = function | I.Col (0, j) -> fun _ c -> let column = c.column in Write (fun m -> column j m) | I.Rowid 0 -> fun _ c -> let rowid = c.rowid in Write (fun m -> match rowid () with | Some id -> Register.set_int64 m id | None -> Register.set_null m) | I.Lit v -> let k = mem_of v in let w = Write (fun m -> Register.copy ~dst:m ~src:k) in fun _ _ -> w | I.Param i -> fun bnd _ -> let k = mem_of (param bnd.params i) in Write (fun m -> Register.copy ~dst:m ~src:k) | e -> let e = eval hooks e in fun bnd _ -> Node (e bnd) (* The rows of [c] up to the [limit], each handed to [one f], stepped with [rewind] and [next] as the VM steps them, not pushed: a scan its LIMIT or its consumer leaves early has stepped, and counted, the rows before it. *) let step (c : Cursor.t) limit one f = match limit with | Some bound when bound <= 0 -> () | None -> if c.rewind () then begin one f; while c.next () do one f done end | Some bound -> let left = ref bound in let f r = f r; decr left in if c.rewind () then begin one f; while !left > 0 && c.next () do one f done end (* The step of a scan over the row its cursor is on: a row [keep] keeps has its [acts] computed into [regs] and is handed over as [out], and [row] counts every row. A row the OFFSET skips passes the WHERE and is counted, before any result column is computed (select.c, codeOffset); a run with no OFFSET, a recursive CTE's step among them, holds no counter. *) let row_step ~offset keep acts regs out row = let n = Array.length acts in if offset = 0 then (fun f -> if keep () then begin for k = 0 to n - 1 do (Array.unsafe_get acts k) () done; Row_core.with_regs out regs 0 n f end; incr row) else let skip = ref offset in fun f -> if keep () then if !skip > 0 then decr skip else begin for k = 0 to n - 1 do (Array.unsafe_get acts k) () done; Row_core.with_regs out regs 0 n f end; incr row (* The scan of a select of a shape compiled here, as a function of the run's parameters, its one cursor and the row consumer; it raises [I.Unsupported] for any other shape. *) let scan ?hooks (q : I.query) = let s = q.select in (match (s.arities, s.joins, q.order_by, q.distinct) with | [ _ ], [], [], false -> () | _ -> raise I.Unsupported); let uses = column_uses s.filter [] in let keep = predicate hooks s.filter in let proj = Array.of_list (List.map (projector hooks) s.project) in let n = Array.length proj and limit = q.limit and offset = q.offset in fun params (c : Cursor.t) f -> let row = ref 0 in let bnd = { col = columns c row uses; load = loads c row; cursor = c; params } in let keep = keep bnd in let regs = Array.make n (Register.v ()) in let acts = Array.mapi (fun k p -> match p bnd c with | Write w -> let m = Register.v () in regs.(k) <- m; fun () -> w m | Node nd -> regs.(k) <- nd.out; nd.run) proj in let out = Row_core.v () in let one = row_step ~offset keep acts regs out row in step c limit one f; !row (* A scan, which answers how many rows it stepped. *) type scan = Value.t array -> Cursor.t -> (Row_core.row -> unit) -> int (* The path a plan's runs take. Its first run takes the closures the plan staged to learn that its shape compiles. A plan run once, as one compiled for a select whose literal changes with each row of an outer statement, keeps none of its closures after that run: they would cost more held by a cache, until the next collection, than staged again. One run again keeps them from its second run on, unless its first two runs each stepped one row at most, as a recursive CTE's step over the row it was handed does: binding the closures to a run's cursor costs more than the VM's dispatch over a row, and the plan's later runs take the VM. *) type path = Vm | First of scan | Again of int | Staged of scan (* The VM program is coded when a run first takes the VM: a plan whose runs take its closures never reads one, and sqlite3 codes no program it does not run. *) type plan = { query : I.query; program : (I.program * int) Lazy.t; hooks : I.hooks option; mutable path : path; } (* A plan holds the hooks only where its closures call them: they hold the catalog of the statement that made the plan, and a cache of plans would keep every such catalog alive. Its program is coded with the hooks it holds, and where that one is refused its runs keep the closures ({!vm_takes}). *) let plan ?hooks q = match scan q with | first -> { query = q; program = lazy (I.precompile q); hooks = None; path = First first; } | exception I.Unsupported -> ( match scan ?hooks q with | first -> { query = q; program = lazy (I.precompile ?hooks q); hooks; path = First first; } | exception I.Unsupported -> { query = q; program = Lazy.from_val (I.precompile ?hooks q); hooks = None; path = Vm; }) let order p = p.query.select.order let compiled p = match p.path with Vm -> false | First _ | Again _ | Staged _ -> true (* Whether the VM codes [p]'s program. *) let vm_takes p = match Lazy.force p.program with | (_ : I.program * int) -> true | exception I.Unsupported -> false let iter_rows ?(params = [||]) ?regs p cursors ~f = let vm () = let program = Lazy.force p.program in let regs = Option.map (fun r -> r (fst program)) regs in I.iter_rows ~params ?regs p.query program cursors ~f in if Array.length cursors <> 1 then vm () else let c = cursors.(0) in match p.path with | Vm -> vm () | Staged scan -> ignore (scan params c f : int) | First scan -> let rows = scan params c f in p.path <- Again rows | Again first -> let scan = scan ?hooks:p.hooks p.query in let rows = scan params c f in p.path <- (if first <= 1 && rows <= 1 && vm_takes p then Vm else Staged scan) end [@@inline]