(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Spi = Catalog.Spi module V = Catalog.Value (* One window function as this pass runs it: the call, and the position in the projected input row of each expression it reads. *) type bound = | Unbounded_preceding | Preceding of int | Current_row | Following of int | Unbounded_following type frame = { rows : bool; start : bound; end_ : bound } type win = { name : string; star : bool; (* a star [count]: it counts rows and reads no argument *) args : int list; coll : Collation.t option; (* the sequence the fold's own comparison runs under, read only by a fold that compares its arguments *) partition : (int * Collation.t option) list; order : (int * Ast.dir * Collation.t option) list; frame : frame option; filter : int option; (* the FILTER predicate's column: a row it does not hold for is left out of the fold *) } (* The projected input columns, in the order they are registered. An expression appearing twice (the same partition key under two windows, say) is projected once. *) let registry () = let acc = ref [] and n = ref 0 in let slot e = let rec go = function | (e', i) :: _ when Ast.equal_expr e' e -> i | _ :: t -> go t | [] -> let i = !n in acc := !acc @ [ (e, i) ]; incr n; i in go !acc in (slot, fun () -> List.map fst !acc) (* The call under an [OVER]: its name and its arguments. DISTINCT is not one of them -- sqlite3WindowAttach (src/window.c) refuses it as it attaches the window, and the parser refuses it at the same point -- so nothing reaching here folds distinct arguments. *) let call = function | Ast.Func (n, args) -> (n, args) | _ -> failwith "window: not a function call" let bare = Collate.strip (* The sequence a key orders under: its own, or, for one under BINARY, the catalog's [binary] where it has one ({!Lower.query}'s encoding). *) let collation binary e = match (Collate.sequence e, binary) with | (Some Collation.Binary | None), Some _ -> binary | c, _ -> c (* The calls that read no frame: sqlite3 gives each a frame of its own (window.c, sqlite3WindowUpdate), so the one written is dropped, unchecked. *) let reads_frame = function | "row_number" | "rank" | "dense_rank" | "percent_rank" | "cume_dist" | "ntile" | "lag" | "lead" -> false | _ -> true let spec ~binary slot (e : Ast.expr) = let f, w = match e with Ast.Window (f, w) -> (f, w) | _ -> assert false in let f, filter = match f with Ast.Filter (f, p) -> (f, Some p) | f -> (f, None) in let name, args = call f in let key e = slot (bare e) in (* A star [count] counts the rows and has no argument to project; every other call projects each of its arguments. *) let star = name = "count" && match args with [ a ] -> a = Ast.Star | _ -> true in let bound : Ast.frame_bound -> bound = function | Unbounded_preceding -> Unbounded_preceding | Preceding e -> Preceding (key e) | Current_row -> Current_row | Following e -> Following (key e) | Unbounded_following -> Unbounded_following in { name; star; args = (if star then [] else List.map key args); (* A fold that compares its arguments -- [min], [max] -- reads a sequence of its own off the argument list, exactly as the same fold over a GROUP BY group does: one {!Collate.call_sequence} for both. Every other fold orders nothing and carries none. *) coll = (if Collate.fold_compares name then match Collate.call_sequence args with None -> binary | c -> c else None); partition = List.map (fun e -> (key e, collation binary e)) w.partition; order = List.map (fun (e, d) -> (key e, d, collation binary e)) w.Ast.order; frame = (if reads_frame name then Option.map (fun (fr : Ast.frame) -> { rows = fr.rows; start = bound fr.start; end_ = bound fr.end_ }) w.frame else None); filter = Option.map key filter; } (* ---- Running an expression projection on the register VM ---------------- *) let project ~params ?affinity ~membership ~encoding layout (s : Ast.select) rows = let q, subs = Lower.query ~params ?affinity ~membership ~encoding layout s in if Lower.needs_runner subs then raise Ir.Unsupported; let hooks = { Lower.hooks with subquery = Lower.member subs } in let hooks = match encoding with | Encoding.Utf8 -> hooks | e -> Lower.stored_text e hooks in Ir.run ~hooks ~params (Ir.rebase q) [| Spi.list_cursor rows |] (* ---- Partitioning, ordering, framing ------------------------------------ *) (* Two values of the ORDER BY key [(_, _, coll)] compared under its collating sequence. *) let value_cmp (_, _, coll) a b = match coll with | Some seq -> Sqlite3_semantics.collate seq a b | None -> V.compare a b (* The same in the window's order. *) let key_cmp ((_, dir, _) as key) a b = let c = value_cmp key a b in match (dir : Ast.dir) with Asc -> c | Desc -> -c let order_cmp keys (a : V.t array) (b : V.t array) = let rec go = function | [] -> 0 | ((col, _, _) as key) :: rest -> let c = key_cmp key a.(col) b.(col) in if c <> 0 then c else go rest in go keys (* [v] moved by the offset [n], a number: as OP_Add and OP_Subtract compute it, an integer past the int64 range is a real and NULL stays NULL. *) let move ~add v n = let real a b = Value_ops.real (if add then a +. b else a -. b) in let float = Value_ops.float_of_value in match (v, n) with | V.Null, _ -> V.Null | V.Int a, V.Int b -> let r = if add then Int64.add a b else Int64.sub a b in let b_sign = if add then b >= 0L else b < 0L in if a >= 0L = b_sign && r >= 0L <> (a >= 0L) then real (Int64.to_float a) (Int64.to_float b) else V.Int r | _ -> real (float v) (float n) (* [r1 op r2] once [r1] is moved by [n] towards [add], as windowCodeRangeTest (window.c) codes it for one ORDER BY key: a text or blob is not moved, a number already past [r2] in the direction it would move is taken as it is, which keeps an overflowing sum from rounding back, and NULL sorts first and equals NULL. *) let range_test key ~op ~add r1 n r2 = let holds c = match op with `Ge -> c >= 0 | `Le -> c <= 0 | `Gt -> c > 0 | `Lt -> c < 0 in match r1 with | V.Text _ | V.Blob _ -> holds (value_cmp key r1 r2) | _ -> let ahead = match (op, add) with | `Ge, true | `Le, false -> r1 <> V.Null && r2 <> V.Null && holds (V.compare r1 r2) | _ -> false in ahead || holds (value_cmp key (move ~add r1 n) r2) (* windowCodeRangeTest (window.c): whether [r1 + n op r2] holds of two ORDER BY values, with the operator reversed and [n] subtracted under DESC. *) let range_jump ((_, dir, _) as key) op r1 n r2 = match (dir : Ast.dir) with | Asc -> range_test key ~op ~add:true r1 n r2 | Desc -> let op = match op with `Ge -> `Le | `Gt -> `Lt | `Le -> `Ge | `Lt -> `Gt in range_test key ~op ~add:false r1 n r2 (* ---- Walking a partition ------------------------------------------------ *) (* A frame bound as sqlite3WindowCodeStep tells them apart. *) type edge = Unbounded | Current | Preceding_n | Following_n let edge = function | Unbounded_preceding | Unbounded_following -> Unbounded | Current_row -> Current | Preceding _ -> Preceding_n | Following _ -> Following_n (* The test an operation on the rows runs first: none, a ROWS offset counted down a row at a time (OP_IfPos), or a RANGE offset its range test reads. *) type countdown = Always | Rows of int64 ref | Range of V.t (* A cursor over the rows read: the row it is at, or past them for good once a step ran off the last row read -- sqlite3's ephemeral-table cursor is then invalid, and the rows read after do not bring it back (btree.c, btreeNext). An operation on it reads a row of NULLs. *) type cursor = { mutable at : int; mutable eof : bool } (* A partition as sqlite3WindowCodeStep (window.c) walks it: the rows read so far ([n]), the one just read while it is answered ([inserted], -1 once the last is read), three cursors over them -- the next row to take out of the aggregates, the next to answer and the next to fold in -- and how many rows of NULLs a cursor past the rows has folded in and taken out. *) type walker = { range : bool; e_start : edge; e_end : edge; offsets : V.t * V.t; reg_start : int64 ref; reg_end : int64 ref; same : int -> bool; key : int -> V.t; test : [ `Ge | `Gt | `Le | `Lt ] -> V.t -> V.t -> V.t -> bool; step : int option -> unit; inverse : int option -> unit; answer : int -> lo:int -> hi:int -> nulls:int * int -> n:int -> unit; mutable n : int; mutable inserted : int; start : cursor; current : cursor; end_ : cursor; mutable null_steps : int; mutable null_inverses : int; } let countdown t e reg v = match e with | Preceding_n | Following_n -> if t.range then Range v else Rows reg | Unbounded | Current -> Always let cd_start t = countdown t t.e_start t.reg_start (fst t.offsets) let cd_end t = countdown t t.e_end t.reg_end (snd t.offsets) let counts = function Always -> false | Rows _ | Range _ -> true (* OP_IfPos: a ROWS countdown still above zero skips the operation. *) let counted = function | Rows r when !r > 0L -> r := Int64.pred !r; true | Always | Rows _ | Range _ -> false (* The ORDER BY value at a cursor: NULL past the rows. *) let key_at t c = if c.eof then V.Null else t.key c.at (* A range test on the rows at two cursors. *) let range_at t op a v b = t.test op (key_at t a) v (key_at t b) (* The rowid comparison a guard makes, which a cursor past the rows, whose rowid is NULL, never passes (OP_Ge). *) let at_or_past a b = (not a.eof) && (not b.eof) && a.at >= b.at (* Under RANGE, a frame whose two bounds are both PRECEDING or both FOLLOWING keeps its start cursor behind its end cursor, and its end cursor off the row just read. *) let same_edges t = t.range && t.e_start = t.e_end (* windowCodeOp: [f] on the row at cursor [c], and under RANGE on each of its peers, unless [skip ()] holds first; [guard ()] stops it before a row, and a RANGE test runs again after each group. On a cursor past the rows [f] reads a row of NULLs ([None]). `Eof when the cursor is past the rows. *) let rec op t c kind ~skip ~guard f = if skip () then `Done else let rec rows () = if guard () then `Done else if c.eof then ( f None; `Eof) else begin f (Some c.at); c.at <- c.at + 1; if c.at >= t.n then ( c.eof <- true; `Eof) else if t.range && t.same c.at then rows () else match kind with | Range _ -> op t c kind ~skip ~guard f | Always | Rows _ -> `Done end in rows () let agg_step t kind = let skip () = match kind with | Range v -> range_at t `Gt t.end_ v t.current | Always | Rows _ -> counted kind in let guard () = same_edges t && counts kind && t.inserted >= 0 && (not t.end_.eof) && t.end_.at >= t.inserted in op t t.end_ kind ~skip ~guard (fun r -> if r = None then t.null_steps <- t.null_steps + 1; t.step r) let agg_inverse t kind = if t.e_start = Unbounded then `Done else let skip () = match kind with | Range v when t.e_start = Following_n -> range_at t `Le t.current v t.start | Range v -> range_at t `Ge t.start v t.current | Always | Rows _ -> counted kind in let guard () = same_edges t && counts kind && at_or_past t.start t.end_ in op t t.start kind ~skip ~guard (fun r -> if r = None then t.null_inverses <- t.null_inverses + 1; t.inverse r) (* A row answered: no row past the rows read is answered. *) let ret t kind = op t t.current kind ~skip:(fun () -> counted kind) ~guard:(fun () -> false) (function | None -> () | Some pos -> t.answer pos ~lo:t.start.at ~hi:(t.end_.at - 1) ~nulls:(t.null_steps, t.null_inverses) ~n:t.n) (* Whether the end cursor is still within the current row's FOLLOWING offset. *) let end_ahead t = range_at t `Ge t.current (snd t.offsets) t.end_ (* Each row left, answered once the last is read. *) let rec rest t = if ret t Always <> `Eof then rest t (* Answer, then take a row out, until either runs off the rows. *) let rec answer_and_drop t ~ret_kind ~inv_kind = if ret t ret_kind <> `Eof then if agg_inverse t inv_kind = `Eof then rest t else answer_and_drop t ~ret_kind ~inv_kind let flush_following t = ignore (agg_step t Always); if t.range then let rec go () = if agg_inverse t (cd_start t) = `Eof then rest t else if ret t Always <> `Eof then go () in go () else if t.e_end = Unbounded then answer_and_drop t ~ret_kind:(cd_start t) ~inv_kind:Always else begin t.reg_end := Int64.sub !(t.reg_end) !(t.reg_start); t.reg_start := 0L; answer_and_drop t ~ret_kind:(cd_end t) ~inv_kind:(cd_start t) end (* The rows answered once the last is read. *) let flush t = t.inserted <- -1; match (t.e_start, t.e_end) with | _, Preceding_n -> ignore (agg_step t (cd_end t)); if t.e_start = Preceding_n && t.range then ignore (agg_inverse t (cd_start t)); ignore (ret t Always) | Following_n, _ -> flush_following t | _ -> ignore (agg_step t Always); let rec go () = if ret t Always <> `Eof then ( ignore (agg_inverse t (cd_start t)); go ()) in go () let read_following t = ignore (agg_step t Always); if t.e_end <> Unbounded then if t.range then let rec go () = if not (end_ahead t) then begin ignore (agg_inverse t (cd_start t)); ignore (ret t Always); go () end in go () else ( ignore (ret t (cd_end t)); ignore (agg_inverse t (cd_start t))) let read_preceding t = let rps = t.e_start = Preceding_n && t.range in ignore (agg_step t (cd_end t)); if rps then ignore (agg_inverse t (cd_start t)); ignore (ret t Always); if not rps then ignore (agg_inverse t (cd_start t)) let read_current t = ignore (agg_step t Always); if t.e_end <> Unbounded then if t.range then let bounded = t.e_end = Following_n in let rec go () = if not (bounded && end_ahead t) then begin ignore (ret t Always); ignore (agg_inverse t (cd_start t)); if bounded then go () end in go () else if not (counted (cd_end t)) then ( ignore (ret t Always); ignore (agg_inverse t (cd_start t))) (* The rows answered as row [r], the first of its peers under RANGE, is read. *) let read t r = t.inserted <- r; match (t.e_start, t.e_end) with | Following_n, _ -> read_following t | _, Preceding_n -> read_preceding t | _ -> read_current t (* ROWS bounds on one side that end before they start frame nothing. *) let empty t = (not t.range) && t.e_start = t.e_end && (t.e_start = Preceding_n || t.e_start = Following_n) && if t.e_start = Following_n then !(t.reg_end) < !(t.reg_start) else !(t.reg_end) > !(t.reg_start) (* The [k] ordered rows of a partition walked as sqlite3WindowCodeStep (window.c) walks them, reading them one at a time: [step (Some i)] folds row [i] into the aggregates, [inverse (Some i)] takes it back out, and [answer pos ~lo ~hi ~nulls ~n] answers row [pos] over the rows [lo..hi], those stepped and not inverted, and the [nulls] rows of NULLs folded in and taken out, with [n] rows read. A [None] step or inverse is such a row: a cursor that ran off the rows read stays off them, as sqlite3's does, where a RANGE offset rounds a value past the rows read. The calls come in sqlite3's order, which is part of a SUM's answer: a row folded once leaves its mark when the frame drops it, and a row before the first frame is stepped and inverted before that frame is answered. [same i] is whether row [i] is a peer of row [i - 1], [key i] row [i]'s ORDER BY value, and [test op a n b] a range test on two of them. *) let walk ~k ~(frame : frame) ~offsets ~same ~key ~test ~step ~inverse ~answer = let rows_offset = function V.Int i -> i | _ -> 0L in let t = { range = not frame.rows; e_start = edge frame.start; e_end = edge frame.end_; offsets; reg_start = ref (rows_offset (fst offsets)); reg_end = ref (rows_offset (snd offsets)); same; key; test; step; inverse; answer; n = 0; inserted = -1; start = { at = 0; eof = false }; current = { at = 0; eof = false }; end_ = { at = 0; eof = false }; null_steps = 0; null_inverses = 0; } in if empty t then for pos = 0 to k - 1 do answer pos ~lo:pos ~hi:(pos - 1) ~nulls:(0, 0) ~n:k done else if k > 0 then begin if t.e_start = Following_n && (not t.range) && t.e_end = Following_n then t.reg_start := Int64.sub !(t.reg_end) !(t.reg_start); t.n <- 1; for r = 1 to k - 1 do t.n <- r + 1; if not (t.range && same r) then read t r done; flush t end (* An offset is a non-negative integer under ROWS and a non-negative number under RANGE, read under NUMERIC affinity, or the statement fails as it runs (window.c, windowCheckValue). It is read once, and its numeric value is what a RANGE frame moves by. *) let check_offset ~rows ~which v = match Value_ops.apply_affinity `Numeric v with | V.Int n as v when Int64.compare n 0L >= 0 -> v | V.Float f as v when (not rows) && f >= 0. -> v | _ -> Catalog.Error.fail_runtime "frame %s offset must be a non-negative %s" which (if rows then "integer" else "number") (* The frame's two offsets, start then end, checked; [V.Null] where a bound is none. *) let frame_offsets w ~read = match w.frame with | Some f -> let offset which = function | Preceding c | Following c -> check_offset ~rows:f.rows ~which (read c) | Unbounded_preceding | Current_row | Unbounded_following -> V.Null in let start = offset "starting" f.start in (start, offset "ending" f.end_) | None -> (V.Null, V.Null) (* One row's value for a navigation or aggregate window function. [at i c] is input column [c] of the [i]-th ordered row, [cur c] the same at [pos]. *) let lag_lead ~name ~args ~k ~pos ~at ~cur = let off = match List.nth_opt args 1 with | Some c -> Int64.to_int (Value_ops.intify (cur c)) | None -> 1 in let dflt = match List.nth_opt args 2 with Some c -> cur c | None -> V.Null in let t = if name = "lag" then pos - off else pos + off in if t >= 0 && t < k then at t (List.hd args) else dflt let nth_value ~args ~lo ~hi ~at ~cur = let n = Int64.to_int (Value_ops.intify (cur (List.nth args 1))) in let t = lo + (n - 1) in if n >= 1 && t <= hi then at t (List.hd args) else V.Null let ntile ~args ~k ~pos ~cur = let nb = max 1 (Int64.to_int (Value_ops.intify (cur (List.hd args)))) in let base = k / nb and rem = k mod nb in let big = rem * (base + 1) in let b = if pos < big then pos / (base + 1) else rem + ((pos - big) / base) in V.Int (Int64.of_int (b + 1)) (* Whether the FILTER keeps the [r]-th ordered row. *) let kept w ~inputs ~oa r = match w.filter with | None -> true | Some c -> Value_ops.tri_of inputs.(oa.(r)).(c) = Value_ops.T (* Fold an aggregate over the frame's rows the FILTER keeps through the shared {!Sqlite3_semantics.aggregate}, the same fold the register VM's GROUP BY path uses, so one policy decides what an aggregate means wherever it is folded -- the sequence a comparing fold runs under included. No dedup: a window call carries no DISTINCT to fold under ({!call}). [latest] folds the rows last first, so [min] and [max] answer the last of equal values. *) let agg_over ~latest w ~inputs ~oa ~lo ~hi = let rows = if lo > hi then [] else List.filter (kept w ~inputs ~oa) (List.init (hi - lo + 1) (( + ) lo)) in let rows = if latest then List.rev rows else rows in if w.star then ( (* a star [count] reads no argument, so it compares nothing *) let acc = Sqlite3_semantics.aggregate w.name ~nargs:0 ~coll:None in List.iter (fun _ -> acc.step [||] 0) rows; acc.finish ()) else if w.args = [] then Catalog.Error.fail_prepare "wrong number of arguments to function %s()" w.name else let acc = Sqlite3_semantics.aggregate w.name ~nargs:(List.length w.args) ~coll:w.coll in List.iter (fun r -> let row = inputs.(oa.(r)) in acc.step (Array.of_list (List.map (fun c -> row.(c)) w.args)) 0) rows; acc.finish () let percent_rank ~peer_start ~k ~pos = if k > 1 then V.Float (float_of_int peer_start.(pos) /. float_of_int (k - 1)) else V.Float 0. let cume_dist ~peer_end ~k ~pos = V.Float (float_of_int (peer_end.(pos) + 1) /. float_of_int k) let value ~latest w ~inputs ~oa ~peer_start ~peer_end ~k ~dense ~pos ~lo ~hi = let at i c = inputs.(oa.(i)).(c) in let cur c = at pos c in let args = w.args in match w.name with | "row_number" -> V.Int (Int64.of_int (pos + 1)) | "rank" -> V.Int (Int64.of_int (peer_start.(pos) + 1)) | "dense_rank" -> V.Int (Int64.of_int dense) | "percent_rank" -> percent_rank ~peer_start ~k ~pos | "cume_dist" -> cume_dist ~peer_end ~k ~pos | "first_value" -> if lo <= hi then at lo (List.hd args) else V.Null | "last_value" -> if lo <= hi then at hi (List.hd args) else V.Null | "lag" | "lead" -> lag_lead ~name:w.name ~args ~k ~pos ~at ~cur | "nth_value" -> nth_value ~args ~lo ~hi ~at ~cur | "ntile" -> ntile ~args ~k ~pos ~cur | _ -> agg_over ~latest w ~inputs ~oa ~lo ~hi let tie_break ~grouped w = let desc (_, d, _) = d = Ast.Desc in if grouped && w.order <> [] && List.for_all desc w.order then fun i j -> compare j i else fun _ _ -> 0 (* The row indices [idxs] in the order the window sorts them: by its ORDER BY, ties broken as {!tie_break} says. *) let ordered ~grouped w inputs idxs = let tie = tie_break ~grouped w in List.stable_sort (fun i j -> match order_cmp w.order inputs.(i) inputs.(j) with 0 -> tie i j | c -> c) idxs (* A call's value over a frame that also folded rows of NULLs ([nulls], those stepped and those inverted), as sqlite3's own steps of each call read them: a star [count] counts them unless a FILTER drops them, [last_value] is the NULL last stepped, and [first_value] and [nth_value] count them among the rows, reading row [i] of the [n] read so far by its position (window.c, windowReturnOneRow). Every other call skips a NULL, so [plain ()] stands. *) let with_nulls w ~nulls:(steps, inverses) ~lo ~hi ~read ~pos ~n plain = if steps = 0 && inverses = 0 then plain () else let stepped = hi + 1 + steps and taken = lo + inverses in let at i = if i < stepped && i < n then read i (List.hd w.args) else V.Null in match (w.name, plain ()) with | "count", V.Int c when w.star && w.filter = None -> V.Int (Int64.add c (Int64.of_int (steps - inverses))) | "last_value", _ when steps > 0 && stepped > taken -> V.Null | "first_value", _ -> at taken | "nth_value", v -> ( match List.nth_opt w.args 1 with | Some c -> let nth = Int64.to_int (Value_ops.intify (read pos c)) in if nth >= 1 then at (taken + nth - 1) else v | None -> v) | _, v -> v (* The values of a call that reads a frame, each answered as {!walk} reaches its row. SUM, TOTAL, AVG and group_concat fold as the walk steps and inverts, since their answer depends on every row they folded and on the order they came and went in; every other call folds its frame afresh. A frame that does not start at the partition's first row keeps the values of MIN and MAX in an index in which equal values sort by arrival (window.c, windowAggStep), so the last of equal values is the answer, where a frame that does folds them as a GROUP BY does and keeps the first. *) let frame_values w ~inputs ~oa ~peer_start ~k ~read ~value out = let frame = match w.frame with | Some f -> f | None -> { rows = false; start = Unbounded_preceding; end_ = Current_row } in let offsets = if k > 0 then frame_offsets w ~read:(read 0) else (V.Null, V.Null) in let key, test = match w.order with | [ ((c, _, _) as key) ] -> ((fun i -> read i c), range_jump key) | _ -> ((fun _ -> V.Null), fun _ _ _ _ -> false) in (* The calls folded as the walk steps rows in and inverts them out, with the step, the inverse and the answer of the fold. A row of NULLs is folded by none of them. *) let moving = let module Sum = Value_ops.Sum in let module Gc = Value_ops.Group_concat in match (w.name, w.args) with | ("sum" | "total" | "avg"), [ c ] -> let s = Sum.v w.name in let at f i = match read i c with V.Null -> () | v -> f s v in Some (at Sum.add, at Sum.remove, fun () -> Sum.finish s) | ("group_concat" | "string_agg"), c :: seps -> let g = Gc.v () in let sep i = Option.map (read i) (List.nth_opt seps 0) in Some ( (fun i -> Gc.add g ?sep:(sep i) (read i c)), (fun i -> Gc.remove g (read i c)), fun () -> Gc.finish g ) | _ -> None in let latest = (w.name = "min" || w.name = "max") && frame.start <> Unbounded_preceding in let fold pick = function | Some i when kept w ~inputs ~oa i -> ( match moving with Some m -> pick m i | None -> ()) | Some _ | None -> () in walk ~k ~frame ~offsets ~same:(fun i -> peer_start.(i) <> i) ~key ~test ~step:(fold (fun (step, _, _) -> step)) ~inverse:(fold (fun (_, inverse, _) -> inverse)) ~answer:(fun pos ~lo ~hi ~nulls ~n -> out.(oa.(pos)) <- (match moving with | Some (_, _, finish) -> finish () | None -> with_nulls w ~nulls ~lo ~hi ~read ~pos ~n (fun () -> value ~latest ~pos ~dense:0 ~lo ~hi))) (* Compute one partition's values into [out]: order its row indices by the window's ORDER BY, find the peer-group bounds (peers share a rank and a frame), then write each row's value. *) let fill_partition ~grouped w inputs out idxs = let oa = Array.of_list (ordered ~grouped w inputs idxs) in let k = Array.length oa in let peer_start = Array.make k 0 and peer_end = Array.make k 0 in let p = ref 0 in while !p < k do let q = ref !p in while !q + 1 < k && order_cmp w.order inputs.(oa.(!p)) inputs.(oa.(!q + 1)) = 0 do incr q done; for r = !p to !q do peer_start.(r) <- !p; peer_end.(r) <- !q done; p := !q + 1 done; let read i c = inputs.(oa.(i)).(c) in let value ~latest ~pos ~dense ~lo ~hi = value ~latest w ~inputs ~oa ~peer_start ~peer_end ~k ~dense ~pos ~lo ~hi in if reads_frame w.name then frame_values w ~inputs ~oa ~peer_start ~k ~read ~value out else begin let dense = ref 0 and prev_start = ref (-1) in for pos = 0 to k - 1 do if peer_start.(pos) <> !prev_start then begin incr dense; prev_start := peer_start.(pos) end; out.(oa.(pos)) <- value ~latest:false ~pos ~dense:!dense ~lo:0 ~hi:(-1) done end (* Two rows' PARTITION BY keys compared, most significant first, each under its own collating sequence. sqlite3 gives the window's sorter one KeyInfo entry per key with that key's collation (window.c), so a partition's sequence and the window's ORDER BY sequences are independent of one another. *) let partition_cmp w inputs i j = let rec go = function | [] -> 0 | (c, coll) :: rest -> let d = match coll with | Some seq -> Sqlite3_semantics.collate seq inputs.(i).(c) inputs.(j).(c) | None -> V.compare inputs.(i).(c) inputs.(j).(c) in if d <> 0 then d else go rest in go w.partition let partitions w inputs = let cmp = partition_cmp w inputs in let sorted = List.stable_sort cmp (List.init (Array.length inputs) Fun.id) in let rec runs = function | [] -> [] | i :: rest -> let rec take acc = function | j :: t when cmp i j = 0 -> take (j :: acc) t | t -> (List.rev acc, t) in let group, tail = take [ i ] rest in group :: runs tail in runs sorted (* [w]'s value for every input row, aligned to [inputs]: partition by the key tuple, then fill each partition. *) let evaluate ~grouped w inputs = let out = Array.make (Array.length inputs) V.Null in List.iter (fill_partition ~grouped w inputs out) (partitions w inputs); out let row_order ~grouped w inputs = List.concat_map (ordered ~grouped w inputs) (partitions w inputs) (* ---- The pass ----------------------------------------------------------- *) (* The synthetic column a window's value is carried in for the second projection. The NUL byte keeps the name unspellable, so no user column collides with it. *) let win_column i = Fmt.str "\000win%d" i (* [*] and [t.*] listed column by column, over the sources the rows came from. Expanded here rather than by the lowering, whose layout also carries the window columns, which a bare [*] must not reach. *) let expand_star segments (rc : Ast.result_col) : Ast.result_col list = let cols_of (alias, cols) = let qual = if alias = "" then None else Some alias in List.filter_map (fun c : Ast.result_col option -> if String.equal c Resolve.rowid_sentinel then None else Some { expr = Ast.Col (qual, c); alias = None }) cols in match rc.Ast.expr with | Star -> List.concat_map cols_of segments | Qualified_star q -> ( let same (al, _) = String.uppercase_ascii al = String.uppercase_ascii q in match List.find_opt same segments with | Some seg -> cols_of seg | None -> [ rc ]) | _ -> [ rc ] (* Replace each [Window] node by a reference to the column its value was written to. Windows do not nest, so a [Window] is not descended into. *) let rec substitute at (e : Ast.expr) : Ast.expr = match e with | Window _ -> Ast.Col (None, at e) (* A subquery computes its own windows over its own rows, so it is handed back as written; every other part of the expression is projected here and reads the column this pass wrote. *) | e -> Ast.map_expr ~select:Fun.id (substitute at) e (* [rows], each widened by one column per window, in the order the first window sorts them -- as sqlite3 emits them: the sort a window needs is what the caller sees when nothing else orders the result. *) let widen ~grouped specs values inputs rows = let widened = List.mapi (fun i row -> row @ List.map (fun v -> v.(i)) values) rows in match specs with | [] -> widened | w :: _ -> let a = Array.of_list widened in List.map (fun i -> a.(i)) (row_order ~grouped w inputs) (* The select list, ORDER BY, DISTINCT and LIMIT read back over the widened rows, each window replaced by the column [at] names for it. *) let second_projection at cols (s : Ast.select) = { (Lower.post_select (List.map (fun (rc : Ast.result_col) -> { rc with Ast.expr = substitute at rc.expr }) cols)) with Ast.distinct = s.distinct; order_by = List.map (fun (e, d) -> (substitute at e, d)) s.order_by; limit = s.limit; offset = s.offset; } let scan_select (layout : Lower.layout) (s : Ast.select) = (* a table joined from an EXISTS is read by the WHERE alone, which the scan applies, and publishes no column to the pass *) let layout = List.filter (fun (a, _) -> not (Resolve.is_semi_alias a)) layout in let rowid (alias, cols) = if List.mem Resolve.rowid_sentinel cols then let qual = if alias = "" then None else Some alias in Some (alias, { Ast.expr = Col (qual, Resolve.rowid_sentinel); alias = None }) else None in let rowids = List.filter_map rowid layout in let visible = List.map (fun (a, c) -> (a, List.filter (fun n -> n <> Resolve.rowid_sentinel) c)) layout in ( { s with Ast.cols = { Ast.expr = Star; alias = None } :: List.map snd rowids; group_by = []; having = None; order_by = []; limit = None; offset = None; distinct = false; }, visible @ List.map (fun (a, _) -> (a, [ Resolve.rowid_sentinel ])) rowids ) (* A rowid read through the segments {!scan_select} appends is an INTEGER, as it is on the source it came from. *) let rowid_affinity segments affinity (i, j) = match List.nth_opt segments i with | Some (_, cols) when List.nth_opt cols j = Some Resolve.rowid_sentinel -> Some `Integer | _ -> affinity (i, j) let scan ~params ?affinity ?(membership = fun _ -> Query.opaque_membership) ?(grouped = false) ~encoding (segments : Lower.layout) (s : Ast.select) rows = let affinity = Option.map (rowid_affinity segments) affinity in let cols = List.concat_map (expand_star segments) s.Ast.cols in (* the select list and the ORDER BY both name windows this pass computes; expanding a star adds none, so the two agree on which *) let windows = Query.select_windows s in let slot, projected = registry () in let binary = match encoding with Encoding.Utf8 -> None | e -> Some (Collation.binary e) in let specs = List.map (spec ~binary slot) windows in let result_col e : Ast.result_col = { expr = e; alias = None } in let inputs = Array.of_list (List.map Array.of_list (project ~params ?affinity ~membership ~encoding segments (Lower.post_select (List.map result_col (projected ()))) rows)) in let values = List.map (fun w -> evaluate ~grouped w inputs) specs in let names = List.mapi (fun i _ -> win_column i) windows in (* Every window the select names has a column here, the ORDER BY's included, so a node reaching this without one is a window the collection missed rather than a shape to answer differently. *) let at = let table = List.combine windows names in fun e -> match List.find_opt (fun (w, _) -> Ast.equal_expr w e) table with | Some (_, n) -> n | None -> raise Ir.Unsupported in let out = second_projection at cols s in project ~params ?affinity ~membership ~encoding (segments @ [ ("", names) ]) out (widen ~grouped specs values inputs rows)