(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* The cursors a query reads its sources through, and the counting that makes the access path visible: a nested-loop join rewinds each source once per outer row, so a scan, a seek and a probe are charged for exactly the pass each makes. What a cursor may ask of a database is S: six reads and nothing else. *) open Model open Decl open Rowid_range module Register = Catalog.Register module Ident = Catalog.Ident module Lower = Sql.Private.Lower module Plan = Sql.Private.Plan type source = string * string list * (unit -> Catalog.Cursor.t) (* OP_RealAffinity over register [m]: an integer becomes the real it spells, and every other kind is left where it is. A column whose declared type gives it REAL affinity does not hold a real. sqlite3 stores an integer-valued one as an integer -- serial type 8 for 0.0, 9 for 1.0, 1 for 5.0 (fileformat.html sec.2.1) -- and widens it back on the way out, emitting this after every OP_Column over such a column (sqlite/src/select.c, sqlite3ColumnDefault). Text and a blob are what numeric affinity declined on the way in, so converting them here would answer 0.0 for 'abc'; NULL is left where every affinity leaves it (datatype3.html sec.3). In place and idempotent, so a source publishing through two widened layers -- a seek that falls back to the scan behind it -- answers the same. *) let realify (m : Register.t) = match m.kind with | Int -> Register.set_real m (float_of_int m.i) | Bigint -> Register.set_real m (Int64.to_float m.big) | Null | Real | Text | Blob -> () type policy = Materialised | Synthetic | Literal type set_walk = { compared : Sql.Value_ops.affinity list; order : Sql.Order.t; rank : int; } (* The values of an IN set as sqlite3 writes them into its ephemeral index and walks it (expr.c, sqlite3CodeRhsOfIN; wherecode.c, codeINTerm): each converted as its comparison with the column converts it, then once each under the column's sequence, ascending, or descending for a DESC column. *) let in_set_order w vs = let vs = List.sort_uniq (Sql.Value_ops.compare_values_coll w.order.collation) (List.map (Sql.Value_ops.key_value w.compared) vs) in if w.order.desc then List.rev vs else vs module type S = sig type t val counter : t -> Catalog.Cursor.counter val table : t -> string -> Model.generic_table val columns : t -> string -> string list val encoding : t -> Sql.Encoding.t val affinity : t -> string -> string -> Sql.Value_ops.affinity option val seek_plan : t -> ?where:Sql.Ast.expr -> ?index:string -> ?affinity:(string -> Sql.Value_ops.affinity list) -> ?nulls:(string -> bool) -> string -> string list -> read:int list -> (string * (reverse:bool -> Seek.rows)) option val covering_plan : t -> ?where:Sql.Ast.expr -> ?index:string -> ?affinity:(string -> Sql.Value_ops.affinity list) -> ?nulls:(string -> bool) -> string -> string list -> read:int list -> (Model.index * (reverse:bool -> Seek.entries)) option val primary_plan : t -> ?where:Sql.Ast.expr -> ?affinity:(string -> Sql.Value_ops.affinity list) -> string -> string list -> read:int list -> (Model.pk_rows * (Sql.Ast.value array -> string list)) option val budget : t -> Sql.Join.budget end module Make (S : S) = struct (* The tally every source of a query steps its rows into. The mechanism is {!Sql.Vdbe}'s, shared with every other backend; what this layer decides is which cursors are wrapped. *) let counted t (c : Catalog.Cursor.t) : Catalog.Cursor.t = Catalog.Cursor.counted (S.counter t) c (* [OP_RealAffinity] over every column a source publishes out of a REAL column. A REAL column stores an integer-valued one as an integer and widens it back on the way out, an opcode emitted after every OP_Column over such a column, so the widening belongs to the read and not to one access path. A table with no REAL column is handed back untouched, and the wrapper is idempotent. *) let realified (schema : schema) (c : Catalog.Cursor.t) : Catalog.Cursor.t = match Row.real_affinity schema with | None -> c | Some real -> let column j m = c.Catalog.Cursor.column j m; if real j then realify m in (* a REAL column reads through the widening; the others keep the source's own reader *) let reader j = if real j then Catalog.Cursor.column_reader column j else c.Catalog.Cursor.reader j in { c with Catalog.Cursor.column; reader } (* A cursor maker over materialised value-list [rows]; an absent column reads as NULL. [count] wraps each cursor it makes, so a relation read as a source is counted while the statement's own constants are not. *) let rows_cursor count rows = let arr = Array.of_list rows in fun () -> let idx = ref (-1) in let rewind () = idx := 0; !idx < Array.length arr in let next () = incr idx; !idx < Array.length arr in let column j m = Register.set_value m (match List.nth_opt arr.(!idx) j with Some v -> v | None -> Null) in count { Catalog.Cursor.rewind; next; column; rowid = (fun () -> None); reader = Catalog.Cursor.column_reader column; push = None; } (* A cursor over rows already in memory, charged for the pass a scan makes by its [policy]. [Materialised] was counted when it was built (a FROM-subquery, a CTE), [Synthetic] is charged at the scan as a full pass (the schema table, a table-valued function), and [Literal] is the statement's own constants, uncounted because they are not a relation. *) let of_rows t policy rows = let count = match policy with Synthetic -> counted t | _ -> Fun.id in rows_cursor count rows (* The reads a cursor makes of pages and records, each under the guard ({!Integrity.read}), so a page the b-tree or the record codec refuses answers as a damaged database. Nothing else a cursor does is guarded: a generated column ({!Sql.Private.Table.column}), a DEFAULT or a seek key can fail over a sound file, and each answers as itself. *) module Table_cursor = struct module C = Btree.Table.Cursor let v t = Integrity.read C.v t let rewind c = Integrity.read C.rewind c let next c = Integrity.read C.next c let rowid c = Integrity.read C.rowid c let payload_buf c = Integrity.read C.payload_buf c let payload_off c = Integrity.read C.payload_off c let payload_len c = Integrity.read C.payload_len c let seek c rid = match C.seek c rid with | found -> found | exception e when Integrity.is_damage e -> Integrity.malformed () end module Index_cursor = struct module C = Btree.Index.Cursor let v ?reverse t = Integrity.read (C.v ?reverse) t let rewind c = Integrity.read C.rewind c let next c = Integrity.read C.next c let decode e c = Btree.Record.decode_sub e (C.payload_buf c) ~off:(C.payload_off c) ~len:(C.payload_len c) let record e c = Integrity.read (decode e) c end (* A WITHOUT ROWID table's scan info: its rows are the keys of an index b-tree, so stepping that tree in order is the scan, in the order sqlite3 keeps the table in. The row is decoded once per entry rather than per column read, since a record's slots are in PRIMARY KEY order, and the entry is taken as a span so the decode reads the cached page. *) let own_cursor ?reverse t gt (p : pk_rows) = let schema = gt.schema in let width = List.length schema.columns in let c = Index_cursor.v ?reverse p.index in let row = Sql.Private.Table.row (Row.table schema) in let loaded = ref false in let rewind () = loaded := false; Index_cursor.rewind c in let next () = loaded := false; Index_cursor.next c in let column j m = if not !loaded then begin Row.on_key schema row p.layout (Index_cursor.record (Btree.Index.encoding p.index) c); loaded := true end; Register.set_value m (if j < width then Sql.Private.Table.column row j else Sql.Ast.Null) in counted t { Catalog.Cursor.rewind; next; column; rowid = (fun () -> None); reader = Catalog.Cursor.column_reader column; push = None; } let without_rowid_info t (tr : Sql.Ast.table_ref) name gt (p : pk_rows) = let cols = S.columns t name in let alias = match tr.alias with Some a -> a | None -> name in (alias, cols, fun () -> own_cursor t gt p) (* A walk of a WITHOUT ROWID table's own b-tree, backwards if [reverse]. *) let own_walk t ~table p ~reverse = own_cursor ~reverse t (S.table t table) p (* Decode column [j] of the row the table cursor [c] stands on into register [m]: the hidden slot and the INTEGER PRIMARY KEY alias read the cell's key, and a column the record does not reach reads its declared default. The key is decoded only for those two slots, so a scan reading other columns decodes no rowid. A VIRTUAL generated column shifts the slots, so such a table reads through a {!Sql.Private.Table.row}, its record decoded under the guard and its columns computed outside it; a table with none keeps the allocation-free slot decode, guarded whole. The text encoding is the file's, matched once a scan: [slot_read] is inlined with the encoding a constant, so a UTF-8 scan reads a text as its bytes with no test. *) let row_reader t name gt c = let vis = S.columns t name in let nvis = List.length vis in let schema = gt.schema in let rowid_col = match rowid_alias schema with Some i -> i | None -> -1 in let defaults = Row.record_defaults schema in if not (Row.has_virtual schema) then begin let cur = Vdbe_record.cursor () in Table_cursor.C.watch c cur; let[@inline] slot_read enc j m = if j = nvis || j = rowid_col then Register.set_int64 m (Table_cursor.rowid c) else (* the span and the column are read under one guard *) match Vdbe_record.column_of_row enc cur c j m with | true -> () | false -> Register.set_value m defaults.(j) | exception e when Integrity.is_damage e -> Integrity.malformed () in ( (fun () -> ()), match Btree.Table.encoding (rowid_btree gt) with | Sql.Encoding.Utf8 -> fun j m -> slot_read Sql.Encoding.Utf8 j m | enc -> fun j m -> slot_read enc j m ) end else begin let row = Sql.Private.Table.row (Row.table schema) in let loaded = ref false in ( (fun () -> loaded := false), fun j m -> if j = nvis || j = rowid_col then Register.set_int64 m (Table_cursor.rowid c) else begin if not !loaded then begin let buf = Table_cursor.payload_buf c in let off = Table_cursor.payload_off c in let len = Table_cursor.payload_len c in Row.on_record schema row ~rowid:(Table_cursor.rowid c) (match Btree.Record.decode_sub (Btree.Table.encoding (rowid_btree gt)) buf ~off ~len with | stored -> Row.record stored | exception e when Integrity.is_damage e -> Integrity.malformed ()); loaded := true end; Register.set_value m (if j < nvis then Sql.Private.Table.column row j else Null) end ) end (* A stored column of a table without VIRTUAL columns, read where the page holds it: [read] walks the record header to the column and decodes its serial type, and an integer of up to seven bytes or a real is decoded into the reader's cell, so a compiled plan reads it with no register and no allocation. With [real], the column has REAL affinity and such an integer is the real it widens to, as OP_RealAffinity widens it (realify). A blob, and a text of a [utf8] file, is left in the reader's cell where the page holds it, so a comparison reads its bytes with no copy. A column the record does not reach (its DEFAULT), a text of another encoding and an eight-byte integer are loaded by [column], the scan's own column read, into a register [load] answers from, and the value is copied to its cell. *) let page_reader c ~utf8 ~real column j : Catalog.Cursor.reader = let cur = Vdbe_record.cursor () in Table_cursor.C.watch c cur; let from_mem = ref false in let ic = { Catalog.Cursor.int_value = 0 } and rc = { Catalog.Cursor.real_value = 0. } in let sc = { Catalog.Cursor.bytes = ""; first = 0; length = 0 } in let m = Register.v () in let via_mem () = from_mem := true; column j m; (match m.Register.kind with | Int -> ic.int_value <- m.i | Real -> rc.real_value <- m.r | Text | Blob -> sc.bytes <- m.s; sc.first <- 0; sc.length <- String.length m.s | Null | Bigint -> ()); m.kind in (* the kind the cell holds, [Null] when the row's value is not there *) let in_cell = ref (Register.Null : Register.kind) in let in_place buf boff n : Register.kind = (* the rows of a page share its bytes, and a pointer store costs a write barrier *) if sc.bytes != buf then sc.bytes <- buf; sc.first <- boff; sc.length <- Btree.Record.serial_size n; let k : Register.kind = if n land 1 = 0 then Register.Blob else Register.Text in in_cell := k; k in let int i : Register.kind = if real then begin rc.real_value <- float_of_int i; Register.Real end else begin ic.int_value <- i; Register.Int end in (* The record is read on its leaf page; of a row that spilled, a header or a column the page does not hold is [column]'s, which copies that column alone. *) let decode () = let buf = Table_cursor.C.local_buf c in let off = Table_cursor.C.local_off c in let len = Table_cursor.C.payload_len c in let local = Table_cursor.C.local_len c in let header = Char.code (String.unsafe_get buf off) in let off_page = local < len && (header >= 0x80 || header > local) in let at = if off_page then -1 else Btree.Record.locate_small buf ~off ~len j in let n = if at >= 0 then at land 0x7f else if off_page then -1 else Btree.Record.seek_sub cur buf ~off ~len j in let boff = if n < 0 then 0 else if at >= 0 then at lsr 7 else Btree.Record.body_offset cur in if n < 0 || boff + Btree.Record.serial_size n > off + local then via_mem () else begin from_mem := false; if n = 0 then Register.Null else if n <= 5 then int (Btree.Record.decode_int_native buf boff (Btree.Record.serial_size n)) else if n = 7 then begin rc.real_value <- Btree.Record.decode_real buf boff; Register.Real end else if n = 8 then int 0 else if n = 9 then int 1 else if n >= 12 && (utf8 || n land 1 = 0) then in_place buf boff n else via_mem () end in let read () = in_cell := (Register.Null : Register.kind); match decode () with | k -> k | exception e when Integrity.is_damage e -> Integrity.malformed () in { Catalog.Cursor.read; int = ic; real = rc; str = (fun () -> sc); load = (fun dst -> if !from_mem then Register.copy ~dst ~src:m else match !in_cell with | Text -> Register.set_text dst (String.sub sc.bytes sc.first sc.length) | Blob -> Register.set_blob dst (String.sub sc.bytes sc.first sc.length) | Null | Int | Bigint | Real -> column j dst); } let rowid_table_info t (tr : Sql.Ast.table_ref) name gt = let cols = S.columns t name @ [ Sql.Private.Resolve.rowid_sentinel ] in let alias = match tr.alias with Some a -> a | None -> name in (* The scan steps the b-tree a row at a time, so a cursor nothing steps reads no page and a source the plan seeks costs nothing. *) let nvis = List.length (S.columns t name) in let rowid_col = match rowid_alias gt.schema with Some i -> i | None -> -1 in let make_cursor () = let c = Table_cursor.v (rowid_btree gt) in let moved, read = row_reader t name gt c in let rewind () = moved (); Table_cursor.rewind c in let next () = moved (); Table_cursor.next c in let utf8 = match Btree.Table.encoding (rowid_btree gt) with | Sql.Encoding.Utf8 -> true | _ -> false in (* a REAL column widens what it reads, as {!realified} widens another source's, and its page reader widens it on the page *) let real = match Row.real_affinity gt.schema with | Some real -> real | None -> fun _ -> false in let column j m = read j m; if real j then realify m in let rowid () = Some (Table_cursor.rowid c) in (* the rowid slots and a table computing VIRTUAL columns read through [column]; every other column where the page holds it *) let reader j = if Row.has_virtual gt.schema || j = nvis || j = rowid_col || j < 0 || j > nvis then Catalog.Cursor.column_reader column j else page_reader c ~utf8 ~real:(real j) column j in (* a table without VIRTUAL columns pushes its rows from the b-tree; the guard covers the walk, and what [f] raises passes through it as itself, a FAILURE of the plan's own being no damage to the file *) let push = if Row.has_virtual gt.schema then None else Some (fun f -> (* set while [f] runs, so the guard leaves what it raises *) let in_body = ref false in match Table_cursor.C.iter c (fun _ _ _ -> in_body := true; f (); in_body := false) with | n -> n | exception e when (not !in_body) && Integrity.is_damage e -> Integrity.malformed ()) in counted t { Catalog.Cursor.rewind; next; column; rowid; reader; push } in (alias, cols, make_cursor) (* The cursor data for one VM-scanned table: its alias, its column names and a thunk building a fresh cursor over its rows. The store decides the scan; a secondary index does not divert a bare [SELECT]. *) let table_info t (tr : Sql.Ast.table_ref) gt = let name = tr.Sql.Ast.name in match gt.store with | Pk_index_rows p -> without_rowid_info t tr name gt p | Rowid_rows _ -> rowid_table_info t tr name gt (* What [lookup] answers for every key of [keys], each answer once and in the order first answered. The values of an IN list are distinct, but two of them can still select one row, as [1] and ['1'] do on a column of numeric affinity. *) let each_key lookup = function | [ key ] -> lookup key | keys -> let seen = Hashtbl.create 16 in let fresh acc a = if Hashtbl.mem seen a then acc else begin Hashtbl.add seen a (); a :: acc end in let rec go acc = function | [] -> List.rev acc | key :: rest -> go (List.fold_left fresh acc (lookup key)) rest in go [] keys (* A cursor over the row of [table] a rowid key names, as sqlite3's OP_SeekRowid finds it (vdbe.c): a rewind reads the key's column [slot], converts it as [affinity] says ({!Seek.key_rowid}) and seeks the table once, standing on the row or on none. A native integer the outer row holds is the rowid as it is, read where that row lies, so the rewind boxes no key and keeps no copy of it: the rowid is the table cursor's. An IN list's keys name their rows each once, gathered first, last first for a [reverse] walk. Where the values name no key the cursor reads [scan] instead. *) let rowid_cursor t ~table ~slot ~affinity ~reverse ~values ~scan = let gt = S.table t table in let rows = Table_cursor.v (rowid_btree gt) in let moved, row = row_reader t table gt rows in let native = not (List.mem `Text affinity) in let by_rowid = Seek.Rowid_key { slot; affinity } in let rest = ref [] and fallback = ref None in let seek_to = function | Some rid -> Table_cursor.seek rows rid | None -> false in (* the key is the outer row's or a constant's, computed outside the guard the table's seek takes *) let seek_key (key : Seek.key_value array) = match key.(slot) with | Seek.Column c when native -> ( match c.Catalog.Cursor.read () with | Int -> Table_cursor.seek rows (Int64.of_int c.int.int_value) | Null -> false | Bigint | Real | Text | Blob -> seek_to (Seek.key_rowid affinity (Column c))) | k -> seek_to (Seek.key_rowid affinity k) in let rec settle_listed () = match !rest with | [] -> false | rid :: tl -> rest := tl; Table_cursor.seek rows rid || settle_listed () in let column j m = match !fallback with | Some c -> c.Catalog.Cursor.column j m | None -> row j m in { Catalog.Cursor.rewind = (fun () -> if Option.is_some !fallback then fallback := None; moved (); match values () with | Some [ key ] -> (match !rest with [] -> () | _ :: _ -> rest := []); seek_key key | Some keys -> let keys = if reverse then List.rev keys else keys in rest := each_key (Seek.rowids by_rowid) keys; settle_listed () | None -> let c = scan () in fallback := Some c; c.Catalog.Cursor.rewind ()); next = (fun () -> moved (); match !fallback with | Some c -> c.Catalog.Cursor.next () | None -> settle_listed ()); column; rowid = (fun () -> match !fallback with | Some c -> c.Catalog.Cursor.rowid () | None -> Some (Table_cursor.rowid rows)); (* the path is chosen at each rewind, so a column reads through it *) reader = Catalog.Cursor.column_reader column; push = None; } (* A cursor over the rows [table]'s index holds for the current seek keys. [values] resolves the keys on every rewind, since an [Outer] one moves with the outer row. Where the values name no path the cursor reads [scan] instead; declining is not matching nothing. Rows are stepped, not fetched: one key's entries one at a time, as the index's pages hold them, and the rowids of an IN list's keys, each once, gathered first. *) let index_seek_cursor t ~table ~sought ~reverse ~values ~scan = let gt = S.table t table in let rows = Table_cursor.v (rowid_btree gt) in let moved, row = row_reader t table gt rows in let rest = ref [] and listed = ref false and held = ref 0L in let fallback = ref None in let stand rid = Table_cursor.seek rows rid && begin held := rid; true end in (* Stand on the row of the entry the seek is on, or of the next entry whose row the table still holds. *) let rec settle_on (s : Seek.steps) on = on && (stand (s.rowid ()) || settle_on s (Integrity.read s.next ())) in (* The same over the rowids an IN list's keys gathered. *) let rec settle_listed () = match !rest with | [] -> false | rid :: tl -> rest := tl; stand rid || settle_listed () in let settle () = if !listed then settle_listed () else match sought with | Some s -> settle_on s (Integrity.read s.next ()) | None -> false in (* The key is the outer row's or a constant's, so it is computed outside the guard; the index lookup it keys is a page read. [None] declines. A reverse walk takes an IN list's keys last first, each key's rows last first. *) let seek () = match (sought, values ()) with | None, _ | _, None -> None | Some s, Some [ key ] -> listed := false; Some (settle_on s (Integrity.read s.first key)) | Some s, Some keys -> listed := true; let keys = if reverse then List.rev keys else keys in rest := each_key (Integrity.read (Seek.rowids (Steps s))) keys; Some (settle_listed ()) in let column j m = match !fallback with | Some c -> c.Catalog.Cursor.column j m | None -> row j m in { Catalog.Cursor.rewind = (fun () -> fallback := None; moved (); match seek () with | Some on -> on | None -> let c = scan () in fallback := Some c; c.Catalog.Cursor.rewind ()); next = (fun () -> moved (); match !fallback with | Some c -> c.Catalog.Cursor.next () | None -> settle ()); column; rowid = (fun () -> match !fallback with | Some c -> c.Catalog.Cursor.rowid () | None -> Some !held); (* the path is chosen at each rewind, so a column reads through it *) reader = Catalog.Cursor.column_reader column; push = None; } (* The rowid an index entry trails, decoded under the guard. *) let entry_rowid cur idx entry = match Index.entry_rowid cur idx entry with | rid -> rid | exception e when Integrity.is_damage e -> Integrity.malformed () (* A cursor over the rows [idx]'s entries answer outright: [column] reads the entry at the slot the index holds that column in and [rowid] the value every entry trails, so a row costs no second descent. A column the index does not hold is a read the planner did not predict, fetched the slow way; never wrong, only slower. [read s m] decodes slot [s] of the entry stood on and [entry_rowid ()] reads its rowid. *) let covering_entry_reader rows row slot ~read ~entry_rowid j m = match slot j with | Some s -> ( match read s m with | true -> () | false -> Register.set_value m Null | exception e when Integrity.is_damage e -> Integrity.malformed ()) | None -> ( match entry_rowid () with | Some rid -> if Table_cursor.seek rows rid then row j m else Register.set_value m Null | None -> Register.set_value m Null | exception e when Integrity.is_damage e -> Integrity.malformed ()) (* One key's entries are stepped where the index's pages hold them, as sqlite3 steps an index cursor, so a loop that stops at its first row -- a min() or max(), a LIMIT -- reads one descent and not the bucket. An IN list's keys gather their entries first, each once. *) let covering_index_cursor t ~table ~idx ~entries ~reverse ~values ~scan = let gt = S.table t table in let rows = Table_cursor.v (rowid_btree gt) in let moved, row = row_reader t table gt rows in (* which entry column answers each of the source's columns, resolved once: it is a walk of the index's keys, and a rewind reads a column per row *) let entry_slot = Seek.entry_slot gt idx in let ncols = List.length gt.schema.columns in let slots = Array.init (ncols + 1) entry_slot in let slot j = if j >= 0 && j <= ncols then slots.(j) else entry_slot j in let sought : Seek.entries = entries ~reverse in let cur = Vdbe_record.cursor () in let enc = Btree.Index.encoding idx.btree in let bucket = ref [||] and bidx = ref (-1) and listed = ref false in let fallback = ref None in let seek () = match values () with | None -> None | Some [ key ] -> listed := false; Some (Integrity.read sought.seek key) | Some keys -> listed := true; let keys = if reverse then List.rev keys else keys in bucket := Array.of_list (each_key (Integrity.read (Seek.entries sought)) keys); bidx := 0; Some (Array.length !bucket > 0) in let here () = !bucket.(!bidx) in let read_listed = covering_entry_reader rows row slot ~read:(fun s m -> Vdbe_record.column_into_opt enc cur (here ()) s m) ~entry_rowid:(fun () -> Index.entry_rowid cur idx (here ())) in let read_sought = covering_entry_reader rows row slot ~read:sought.column ~entry_rowid:sought.entry_rowid in let column j m = match !fallback with | Some c -> c.Catalog.Cursor.column j m | None -> if !listed then read_listed j m else read_sought j m in { Catalog.Cursor.rewind = (fun () -> fallback := None; moved (); match seek () with | Some on -> on | None -> let c = scan () in fallback := Some c; c.Catalog.Cursor.rewind ()); next = (fun () -> moved (); match !fallback with | Some c -> c.Catalog.Cursor.next () | None -> if !listed then begin incr bidx; !bidx < Array.length !bucket end else Integrity.read sought.step ()); column; rowid = (fun () -> match !fallback with | Some c -> c.Catalog.Cursor.rowid () | None -> if !listed then entry_rowid cur idx (here ()) else Integrity.read sought.entry_rowid ()); reader = Catalog.Cursor.column_reader column; push = None; } (* A cursor over the rows of the WITHOUT ROWID table [table] the current seek keys select down its PRIMARY KEY: each is a row as stored, decoded as a scan of the table decodes it ({!without_rowid_info}). Where the values name no path the cursor reads [scan] instead. *) let primary_key_cursor t ~table ~(p : pk_rows) ~rows ~reverse ~values ~scan = let gt = S.table t table in let width = List.length gt.schema.columns in let row = Sql.Private.Table.row (Row.table gt.schema) in let bucket = ref [||] and bidx = ref (-1) and loaded = ref false in let fallback = ref None and into = ref [||] in let read key = if Array.length !into <> Array.length key then into := Array.make (Array.length key) Sql.Ast.Null; Integrity.read rows (Seek.values ~into:!into key) in let seek () = match Option.map (each_key read) (values ()) with | None -> false | Some rs -> bucket := Array.of_list (if reverse then List.rev rs else rs); true in let read_here j m = if not !loaded then begin Row.on_key gt.schema row p.layout (Btree.Record.decode (Btree.Index.encoding p.index) !bucket.(!bidx)); loaded := true end; Register.set_value m (if j < width then Sql.Private.Table.column row j else Sql.Ast.Null) in let column j m = match !fallback with | Some c -> c.Catalog.Cursor.column j m | None -> read_here j m in counted t { Catalog.Cursor.rewind = (fun () -> fallback := None; loaded := false; if seek () then begin bidx := 0; !bidx < Array.length !bucket end else let c = scan () in fallback := Some c; c.Catalog.Cursor.rewind ()); next = (fun () -> loaded := false; match !fallback with | Some c -> c.Catalog.Cursor.next () | None -> incr bidx; !bidx < Array.length !bucket); column; rowid = (fun () -> None); reader = Catalog.Cursor.column_reader column; push = None; } (* A walk of every entry of [index], from the largest key down if [reverse], each a row of [table]: read out of the entry where the index holds every column read ([covering]), else out of the row its rowid names, fetched once per entry and only once a column is read. Counted as a full scan, which it is, in the index's order rather than the table's. *) (* The row an entry of [index] names, as [(moved, rowid, fetch, read)]: [fetch ()] stands on it and [read j m] reads its column [j]. A rowid table's row is found by the rowid the entry trails, a WITHOUT ROWID table's by the PRIMARY KEY columns it holds, down the table's own b-tree. *) let entry_row t ~table gt (index : index) ~field ~slot = let scratch = Register.v () in match gt.store with | Rowid_rows _ -> let rows = Table_cursor.v (rowid_btree gt) in let moved, read = row_reader t table gt rows in let rowid () = if field (List.length index.keys) scratch then match scratch.Register.kind with | Register.Int -> Some (Int64.of_int scratch.Register.i) | Register.Bigint -> Some scratch.Register.big | Register.Null | Register.Real | Register.Text | Register.Blob -> Integrity.malformed () else None in let fetch () = match rowid () with | Some rid when Table_cursor.seek rows rid -> moved () | Some _ | None -> Integrity.malformed () in (moved, rowid, fetch, read) | Pk_index_rows p -> let key, len = pk_key gt p in let names = Lazy.force gt.schema.names in let pk = List.filteri (fun i _ -> i < len) key in let pk_names = List.map (fun (c : index_column) -> List.nth names c.cid) pk in let lookup = Option.bind (Seek.index gt pk_names ~read:[]) (fun path -> Option.map snd (Seek.primary_plan pk_names path)) in let width = List.length gt.schema.columns in let row = Sql.Private.Table.row (Row.table gt.schema) in let values = Array.make len Sql.Ast.Null in let fetch () = List.iteri (fun i (c : index_column) -> match slot c.cid with | Some s when field s scratch -> values.(i) <- Register.to_value scratch | Some _ | None -> Integrity.malformed ()) pk; match Option.map (fun f -> Integrity.read f values) lookup with | Some (record :: _) -> Row.on_key gt.schema row p.layout (Btree.Record.decode (Btree.Index.encoding p.index) record) | Some [] | None -> Integrity.malformed () in let read j m = Register.set_value m (if j < width then Sql.Private.Table.column row j else Sql.Ast.Null) in ((fun () -> ()), (fun () -> None), fetch, read) let index_scan t ~table ~(index : index) ~reverse ~covering = let gt = S.table t table in let entry_slot = Seek.entry_slot gt index in let ncols = List.length gt.schema.columns in let slots = Array.init (ncols + 1) entry_slot in let slot j = if j >= 0 && j <= ncols then slots.(j) else entry_slot j in let cur = Vdbe_record.cursor () in let encoding = Btree.Index.encoding index.btree in let c = Index_cursor.v ~reverse index.btree in (* the entry is read where the page holds it, column by column *) let field s m = match Vdbe_record.column_at_opt encoding cur (Index_cursor.C.payload_buf c) ~off:(Index_cursor.C.payload_off c) ~len:(Index_cursor.C.payload_len c) s m with | found -> found | exception e when Integrity.is_damage e -> Integrity.malformed () in let moved, rowid, fetch, read = entry_row t ~table gt index ~field ~slot in let fetched = ref false in let step more = moved (); Btree.Record.reset cur; fetched := false; more in let column j m = match slot j with | Some s when covering -> if not (field s m) then Register.set_value m Null | Some _ | None -> if not !fetched then begin fetch (); fetched := true end; read j m in counted t (realified gt.schema { Catalog.Cursor.rewind = (fun () -> step (Index_cursor.rewind c)); next = (fun () -> step (Index_cursor.next c)); column; rowid; reader = Catalog.Cursor.column_reader column; push = None; }) (* How a planned seek reads: out of the index where the plan says the index holds the answer, else the row the entry names. Asking the store rather than carrying the index on the plan keeps {!Sql.Private.Plan} free of this store's b-trees; the two answers agree because both come from the same choice of index. Each is a walk of the schema, made once per plan: a rewind costs a b-tree descent and nothing more. *) type seek_path = | Span of { lo : bool option; hi : bool option } | Primary of Model.pk_rows * (Sql.Ast.value array -> string list) | Covering of Model.index * (reverse:bool -> Seek.entries) | Rows of (string * (reverse:bool -> Seek.rows)) option let seek_path ?index t ~where ~table ~(keys : Plan.key list) ~read ~covering = let cols = List.map (fun (k : Plan.key) -> k.column) keys in let key c = List.find_opt (fun (k : Plan.key) -> Ident.equal k.column c) keys in let affinity c = match key c with Some k -> k.affinity | None -> [] in let nulls c = match key c with Some k -> k.nulls | None -> false in match S.primary_plan t ?where ~affinity table cols ~read with | Some (p, rows) -> Primary (p, rows) | None -> ( match if covering then S.covering_plan t ?where ?index ~affinity ~nulls table cols ~read else None with | Some (idx, entries) -> Covering (idx, entries) | None -> Rows (S.seek_plan t ?where ?index ~affinity ~nulls table cols ~read) ) (* The entries of the index named [index] of [table] whose first [bound] columns equal the values of the [keys] that name them and whose next column is within the bounds the values after [keys] give, [lo] and [hi] the bounds that are there, stepped one at a time from one seek: read for themselves where the plan says the index [covering] answers the query, else for the rows they name. Each key's value is converted as the key says ({!Sql.Private.Plan.key.affinity}), each bound's as the bound says ({!Sql.Private.Plan.bound.affinity}), and a NULL selects nothing, as no comparison with NULL is true. [keys] name their columns in any order and may equate columns the index does not lead with, which the loop tests: each of the [bound] index columns takes the value of the key that names it. *) let range_path t ~table ~index ~bound ~(keys : Plan.key list) ~lo ~hi ~covering = let after = List.length keys in let conv = Array.of_list (List.map (fun (k : Plan.key) -> k.affinity) keys) in let gt = S.table t table in let idx = List.find (fun (i : index) -> Ident.equal i.name index) gt.indexes in let names = Lazy.force gt.schema.names in let slots = Seek.key_slots (List.map (fun (k : Plan.key) -> k.column) keys) (List.filteri (fun i _ -> i < bound) idx.keys |> List.map (function | Column c -> List.nth names c | Expression _ -> Fmt.invalid_arg "Cursor.range_path: %s equates an expression" index)) in let nulls = Array.of_list (List.map (fun (k : Plan.key) -> k.nulls) keys) in let hi_at = if lo = None then after else after + 1 in (* a NULL selects nothing: a bound's, and a bound key's but an IS key's, which seeks the entries holding NULL; a key the index does not bind is the loop's to test *) let selects_none (values : Sql.Ast.value array) = let null at = values.(at) = Sql.Ast.Null in Array.exists (fun at -> null at && not nulls.(at)) slots || (lo <> None && null after) || (hi <> None && null hi_at) in let limit values at = Option.map (fun (b : Plan.bound) -> (Sql.Value_ops.key_value b.affinity values.(at), b.inclusive)) in (* One walk per cursor, sought again at each rewind and stepped in place: the key's values are read into [into], converted into [prefix]. *) let walk ~reverse = let r = Index.range ~reverse idx bound in let into = ref [||] and prefix = Array.make bound Sql.Ast.Null in let seek key = if Array.length !into <> Array.length key then into := Array.make (Array.length key) Sql.Ast.Null; let values = Seek.values ~into:!into key in (not (selects_none values)) && begin for k = 0 to bound - 1 do let at = slots.(k) in prefix.(k) <- Sql.Value_ops.key_value conv.(at) values.(at) done; Index.seek_range r prefix ~lo:(limit values after lo) ~hi:(limit values hi_at hi) end in (r, seek) in if covering then Covering ( idx, fun ~reverse -> let r, seek = walk ~reverse in let s = Index.range_seeker r in { Seek.seek; step = (fun () -> Index.next_in_range r); column = Index.column s; entry_rowid = (fun () -> Index.rowid s); entry = (fun () -> Index.entry s); } ) else Rows (Some ( index, fun ~reverse -> let r, seek = walk ~reverse in let s = Index.range_seeker r in let at = ref 0L in (* an entry naming no rowid names no row of this table *) let rec settle on = on && match Index.rowid s with | Some rid -> at := rid; true | None -> settle (Index.next_in_range r) in Seek.Steps { first = (fun key -> settle (seek key)); next = (fun () -> settle (Index.next_in_range r)); rowid = (fun () -> !at); } )) let inclusive = Option.map (fun (b : Plan.bound) -> b.inclusive) let seek_paths t ?where accesses ~reads = (* a probe's spill is a seek too, once its build gives up *) let rec path_of = function | Plan.Seek { path = { index = None; _ }; range = Some r; _ } -> Some (Span { lo = inclusive r.lo; hi = inclusive r.hi }) | Plan.Seek { table; path; keys; range = Some r; _ } -> Some (range_path t ~table ~index:(Option.get path.Plan.index) ~bound:path.Plan.bound ~keys ~lo:r.lo ~hi:r.hi ~covering:path.Plan.covering) | Plan.Seek { table; path; keys; _ } -> Some (seek_path ?index:path.Plan.index t ~where ~table ~keys ~read:(reads table) ~covering:path.Plan.covering) | Plan.Probe { spill = Some a; _ } -> path_of a | Plan.Scan | Plan.Ordered _ | Plan.Probe _ -> None in Array.of_list (List.map path_of accesses) (* The first and the last rowid a bound [v] admits from below and from above, as the rowid's comparison with it reads it: a number, a text that spells one, and above every number any other text or a blob. [None] where it admits none. *) let rowid_floor v incl = match Sql.Value_ops.compared `Integer v with | Sql.Ast.Int n -> if incl then Some n else if n = Int64.max_int then None else Some (Int64.succ n) | Float f -> let c = Float.ceil f in if c > 0x1p63 then None else if c < -0x1p63 then Some Int64.min_int else let n = Int64.of_float c in if (not incl) && Float.equal c f then if n = Int64.max_int then None else Some (Int64.succ n) else Some n | Null | Text _ | Blob _ -> None let rowid_ceiling v incl = match Sql.Value_ops.compared `Integer v with | Sql.Ast.Int n -> if incl then Some n else if n = Int64.min_int then None else Some (Int64.pred n) | Float f -> let c = Float.floor f in if c < -0x1p63 then None else if c >= 0x1p63 then Some Int64.max_int else let n = Int64.of_float c in if (not incl) && Float.equal c f then if n = Int64.min_int then None else Some (Int64.pred n) else Some n | Text _ | Blob _ -> Some Int64.max_int | Null -> None (* A cursor over the rows of [table] whose rowid is within the bounds the values give, [lo] and [hi] saying whether each is there and inclusive, in rowid order: one descent to the first, then a step per row. A bound with no value ({!key_values}) declines the seek at that rewind, and the rows are [scan]'s, which the loop's WHERE then tests, as an index seek's are. *) let span_cursor t ~table ~lo ~hi ~values ~scan = let gt = S.table t table in let rows = Table_cursor.v (rowid_btree gt) in let moved, row = row_reader t table gt rows in let last = ref Int64.max_int and on = ref false and into = ref [||] in let fallback = ref None in let check () = on := !on && Int64.compare (Table_cursor.rowid rows) !last <= 0; !on in let seek key = if Array.length !into <> Array.length key then into := Array.make (Array.length key) Sql.Ast.Null; let vs = Seek.values ~into:!into key in let at = ref 0 in let take f = Option.map (fun incl -> let v = vs.(!at) in incr at; f v incl) in let first = take rowid_floor lo in let final = take rowid_ceiling hi in (match (first, final) with | Some None, _ | _, Some None -> on := false | first, final -> last := Option.value (Option.join final) ~default:Int64.max_int; on := Integrity.read (fun () -> Btree.Table.Cursor.seek_from rows (Option.value (Option.join first) ~default:Int64.min_int)) ()); check () in let column j m = match !fallback with | Some c -> c.Catalog.Cursor.column j m | None -> row j m in { Catalog.Cursor.rewind = (fun () -> fallback := None; moved (); match values () with | Some [ key ] -> seek key | Some _ -> on := false; false | None -> let c = scan () in fallback := Some c; c.Catalog.Cursor.rewind ()); next = (fun () -> moved (); match !fallback with | Some c -> c.Catalog.Cursor.next () | None -> on := !on && Table_cursor.next rows; check ()); column; rowid = (fun () -> match !fallback with | Some c -> c.Catalog.Cursor.rowid () | None -> Some (Table_cursor.rowid rows)); (* the path is chosen at each rewind, so a column reads through it *) reader = Catalog.Cursor.column_reader column; push = None; } let seek t ~table ~path ~reverse ~values ~scan = let cur = match path with | Span { lo; hi } -> span_cursor t ~table ~lo ~hi ~values ~scan | Primary (p, rows) -> primary_key_cursor t ~table ~p ~rows ~reverse ~values ~scan | Covering (idx, entries) -> covering_index_cursor t ~table ~idx ~entries ~reverse ~values ~scan | Rows None -> index_seek_cursor t ~table ~sought:None ~reverse ~values ~scan | Rows (Some (_, make)) -> ( match make ~reverse with | Seek.Rowid_key { slot; affinity } -> rowid_cursor t ~table ~slot ~affinity ~reverse ~values ~scan | Steps s -> index_seek_cursor t ~table ~sought:(Some s) ~reverse ~values ~scan ) in realified (S.table t table).schema cur (* The columns [cols] of every row [mk] scans, in that order, or [None] once holding them would pass [budget]. Counted as it is read, so a relation too large to hold is abandoned partway and falls back to its access path. *) let drain ~budget ~cols mk = let cur : Catalog.Cursor.t = mk () in let m = Register.v () in let ncols = List.length cols in let row () = List.map (fun j -> cur.Catalog.Cursor.column j m; Register.to_value m) cols in let out = ref [] and cells = ref 0 and bytes = ref 0 and over = ref false in let more = ref (cur.Catalog.Cursor.rewind ()) in while !more && not !over do let r = row () in (* a source with no columns still costs a row: never a zero-cost loop *) cells := !cells + max 1 ncols; bytes := !bytes + Sql.Join.row_bytes r; if Sql.Join.over budget ~cells:!cells ~bytes:!bytes then over := true else begin out := r :: !out; more := cur.Catalog.Cursor.next () end done; if !over then None else Some (List.rev !out) exception Over_budget (* What a hash holds of a source: the columns the query reads from it and the columns it is keyed on, in ascending order, and the place in a held row of each column of the source, [-1] for one it does not hold. A wide table read for three columns is held as three, and its budget counted on them. *) type held = { cols : int list; slot : int array } let held ~width ~read keys = let cols = List.sort_uniq Int.compare (keys @ read) in let slot = Array.make width (-1) in List.iteri (fun k j -> slot.(j) <- k) cols; { cols; slot } (* The cursor [make ()] makes, made at the first call on it. *) let deferred make : Catalog.Cursor.t = let c = lazy (make ()) in { Catalog.Cursor.rewind = (fun () -> (Lazy.force c).Catalog.Cursor.rewind ()); next = (fun () -> (Lazy.force c).Catalog.Cursor.next ()); column = (fun j m -> (Lazy.force c).Catalog.Cursor.column j m); rowid = (fun () -> (Lazy.force c).Catalog.Cursor.rowid ()); reader = (fun j -> (Lazy.force c).Catalog.Cursor.reader j); push = Some (fun f -> Catalog.Cursor.iter (Lazy.force c) f); } (* [c], a cursor over held rows, read by the source's own column numbers. A column the hash does not hold reads as NULL. The query names none of them: the one read that reaches one is the whole row a correlated subquery takes as its scope, and the subquery reads only the columns it names, which {!Sql.Private.Plan.read_columns} counts as read. *) let widened h (c : Catalog.Cursor.t) : Catalog.Cursor.t = let width = Array.length h.slot in let held j = j >= 0 && j < width && h.slot.(j) >= 0 in let column j m = if held j then c.Catalog.Cursor.column h.slot.(j) m else Register.set_value m Null in let reader j = if held j then c.Catalog.Cursor.reader h.slot.(j) else Catalog.Cursor.column_reader column j in { c with Catalog.Cursor.column; reader } (* The affinity of each column the relation [table] publishes: a table's declared type, a view column's expression (sqlite3SubqueryColumnTypes); the hidden rowid slot is an INTEGER. *) let source_affinity t table cols = let of_column = S.affinity t table in fun (_, j) -> match List.nth_opt cols j with | Some c when String.equal c Sql.Private.Resolve.rowid_sentinel -> Some `Integer | Some c -> of_column c | None -> None (* {!drain} of the rows [cond] keeps, [cond] being the predicates of the WHERE that read this source's columns alone: a row it drops is one the joined row's WHERE would drop, so the hash holds the rows the join can use rather than its table. [None] where [cond] does not lower on its own, and the caller drains the whole source; [Some None] once the kept rows pass [budget]. *) let drain_kept t params ~budget ~held (alias, cols, mk) (table, cond) = let qual = if alias = "" then None else Some alias in let s = { (Lower.post_select (List.map (fun j -> { Sql.Ast.expr = Col (qual, List.nth cols j); alias = None }) held)) with Sql.Ast.where = Some cond; } in let encoding = S.encoding t in match Lower.query ~params ~affinity:(source_affinity t table cols) ~encoding [ (alias, cols) ] s with | exception Sql.Ir.Unsupported -> None | _, _ :: _ -> None | q, [] -> ( let hooks = match encoding with | Sql.Encoding.Utf8 -> Lower.hooks | e -> Lower.stored_text e Lower.hooks in let prog = Sql.Ir.precompile ~hooks q in let ncols = List.length held in let out = ref [] and cells = ref 0 and bytes = ref 0 in let keep r = cells := !cells + max 1 ncols; bytes := !bytes + Sql.Join.row_bytes r; if Sql.Join.over budget ~cells:!cells ~bytes:!bytes then raise Over_budget; out := r :: !out in match Sql.Ir.iter ~params q prog [| mk () |] ~f:keep with | () -> Some (Some (List.rev !out)) | exception Over_budget -> Some None) (* The walk of an IN set on the column [col] of [table], sought through the index named [index] or the table's own b-tree: the affinities its values take ({!Sql.Private.Plan.key.affinity}), and its order and place in that b-tree. The rowid, and a column the b-tree does not hold, is walked as BINARY ascending, after the columns it holds. *) let set_walk t ~table ~index (k : Plan.key) = let col = k.column and compared = k.affinity in let gt = S.table t table in let columns = gt.schema.columns in let pos = List.find_index (fun (c : column) -> Ident.equal c.name col) columns in let rowid = { compared; order = Sql.Order.default; rank = 0 } in let ranked held = match Option.bind pos (fun p -> List.find_index (fun (c, _) -> c = p) held) with | Some r -> { compared; order = snd (List.nth held r); rank = r } | None -> { rowid with rank = List.length held } in match index with | Some name -> ( match List.find_opt (fun (idx : index) -> Ident.equal idx.name name) gt.indexes with | Some idx -> ranked (List.filter_map (fun (k, o) -> match k with | Column c -> Some (c, o) | Expression _ -> Some (-1, o)) (List.combine idx.keys idx.orders)) | None -> rowid) | None -> ( match gt.store with | Pk_index_rows { key = Some (key, _); _ } -> ranked (List.map (fun (c : index_column) -> (c.cid, c.order)) key) | Pk_index_rows { key = None; _ } | Rowid_rows _ -> rowid) (* The keys a seek rewinds onto, resolved afresh on every rewind since an [Outer] key moves with the outer row. [None] when a key has no value, and the cursor reads its plain scan instead. A key is one value per column, in the order [keys] names the columns; an IN list or an IN subquery gives one key per distinct value, and several give every combination, nested in the order of their columns in the b-tree. A subquery's values are its rows [set] answers, ordered once, at the first rewind, as sqlite3 fills its ephemeral index once. Without a set, the single key lands in [into] at the first rewind and stays there: a constant is the statement's, and an [Outer] column is the outer cursor's reader of it, which the seek reads where the outer row lies, so a rewind allocates and copies nothing. *) let key_values params ~cursor ~scratch ~into ~walk ~set keys = let column ci cj = (cursor ci).Catalog.Cursor.column cj scratch; Register.to_value scratch in let single = List.fold_right (fun (k : Plan.key) acc -> let k = k.value in match (k, acc) with | Plan.Const e, Some ks -> Some (`Const e :: ks) | Plan.Outer (ci, cj), Some ks -> Some (`Outer (ci, cj) :: ks) | (Plan.In_list _ | Plan.In_select _), _ | _, None -> None) keys (Some []) in match single with | Some single -> ( let fill () = let rec go i = function | [] -> Some [ into ] | `Const e :: rest -> ( match const_value params e with | None -> None | Some v -> into.(i) <- Seek.Value v; go (i + 1) rest) | `Outer (ci, cj) :: rest -> into.(i) <- Seek.Column ((cursor ci).Catalog.Cursor.reader cj); go (i + 1) rest in go 0 single in (* filled at the first rewind and kept *) let filled = ref None in fun () -> match !filled with | Some keys -> keys | None -> let keys = fill () in filled := Some keys; keys) | None -> let n = List.length keys in let list w es () = List.fold_right (fun e acc -> match (acc, const_value params e) with | Some vs, Some v -> Some (v :: vs) | _ -> None) es (Some []) |> Option.map (in_set_order w) in (* each key with its place in [keys] and its values, the sets in their columns' order in the b-tree, which is the order their combinations are sought in *) let nested = List.mapi (fun i (key : Plan.key) -> let k = key.value in match k with | Plan.In_list es -> let w = walk key in (i, w.rank, list w es) | Plan.In_select sub -> let w = walk key in let values = lazy (Option.map (in_set_order w) (set sub)) in (i, w.rank, fun () -> Lazy.force values) | Plan.Const e -> ( i, -1, fun () -> Option.map (fun v -> [ v ]) (const_value params e) ) | Plan.Outer (ci, cj) -> (i, -1, fun () -> Some [ column ci cj ])) keys |> List.stable_sort (fun (_, a, _) (_, b, _) -> Int.compare a b) in fun () -> List.fold_right (fun (i, _, values) acc -> match (values (), acc) with | Some vs, Some tails -> Some (List.concat_map (fun v -> List.map (fun t -> (i, v) :: t) tails) vs) | _ -> None) nested (Some [ [] ]) |> Option.map (List.map (fun combo -> let a = Array.make n (Seek.Value Sql.Ast.Null) in List.iter (fun (i, v) -> a.(i) <- Seek.Value v) combo; a)) (* The cursors [accesses] describes, built in [order] -- the order the loop enters them -- so a seek or a probe reads its key through a cursor already in the array. A FULL join's two sides are built together: the pair is one object, and each half is the inner of a different pass. *) (* [e] with its column references unqualified. A probe's filter reads its own source alone ({!Sql.Private.Plan.local_filter}), so its qualifiers name nothing but the alias, and two filters over one table that differ only by it are the same predicate. *) let rec unqualified (e : Sql.Ast.expr) = match e with | Col (_, c) -> Sql.Ast.Col (None, c) | e -> Sql.Ast.map_expr ~select:Fun.id unqualified e (* The build side of a probe of [table] under [filter]: the table, and the predicates its build keeps. Two probes with one side drain one hash. *) let build_side table filter = (table, Option.map (fun (_, cond) -> unqualified cond) filter) let same_side (t, f) (t', f') = Ident.equal t t' && Option.equal Sql.Ast.equal_expr f f' let probe_keys key rest = key :: List.map (fun (k, _, _, _) -> k) rest (* The places in a row held as [h] holds it of the columns sqlite3's automatic index orders a key's entries by (where.c, constructAutomaticIndex): after its key [keys], each other column [covers], the columns the source reads, in the table's order under BINARY, then the rowid, which the scan the rows came in already orders. A hash a table joined twice shares holds the columns of both, and the index of each covers its own alone. The column [rowid], an INTEGER PRIMARY KEY, is that rowid and no column of the index. *) let auto_index_columns h ~covers ~keys ~rowid = List.filter (fun c -> c <> rowid && List.mem c covers && not (List.mem c keys)) h.cols |> List.map (fun c -> h.slot.(c)) (* [c] reading NULL for every column and every reader, and no rowid, once a rewind or a step has left it on no row, as sqlite3's OP_NullRow marks a padded cursor: a LEFT JOIN pads its row with the cursor past its last row, and a seek or a hash keyed on that row then reads NULL, which nothing equals, rather than the cursor's last row or a page it no longer stands on. *) let on_row (c : Catalog.Cursor.t) = let standing = ref false in let moved r = standing := r; r in let reader j = let r = c.reader j in { r with Catalog.Cursor.read = (fun () -> if !standing then r.read () else Register.Null); load = (fun m -> if !standing then r.load m else Register.set_value m Sql.Ast.Null); } in { Catalog.Cursor.rewind = (fun () -> moved (c.rewind ())); next = (fun () -> moved (c.next ())); column = (fun j m -> if !standing then c.column j m else Register.set_value m Sql.Ast.Null); rowid = (fun () -> if !standing then c.rowid () else None); reader; push = None; } (* The sources of a join a seek or a hash reads its key off. *) let keyed_sources acc = let keyed = Array.make (Array.length acc) false in let outer = function Plan.Outer (k, _) -> keyed.(k) <- true | _ -> () in Array.iter (function | Plan.Seek { keys; range; _ } -> List.iter (fun (k : Plan.key) -> outer k.value) keys; Option.iter (fun (r : Plan.range) -> Option.iter (fun (b : Plan.bound) -> outer b.value) r.lo; Option.iter (fun (b : Plan.bound) -> outer b.value) r.hi) range | Plan.Probe { outer; rest; _ } -> Option.iter (fun (src, _) -> keyed.(src) <- true) outer; List.iter (fun (_, s, _, _) -> keyed.(s) <- true) rest | Plan.Scan | Plan.Ordered _ -> ()) acc; keyed (* The cursor of a table a RIGHT or FULL join keeps, [main], and the one the loop over its unmatched rows reads, [sub], as one cursor of that table: the one the levels after it read their keys off stands on [sub]'s row once [sub] is rewound, and on [main]'s once [main] is, as sqlite3 reads both loops through the table's one cursor (where.c, sqlite3WhereRightJoinLoop). *) let switching (main : Catalog.Cursor.t) (sub : Catalog.Cursor.t) = let active = ref main in let column j m = !active.column j m in ( { sub with rewind = (fun () -> active := sub; sub.rewind ()); push = None; }, { Catalog.Cursor.rewind = (fun () -> active := main; main.rewind ()); next = (fun () -> !active.next ()); column; rowid = (fun () -> !active.rowid ()); reader = Catalog.Cursor.column_reader column; push = None; } ) let accesses t params infos accesses ~paths ~unmatched ~held:read ~relation ~set ~order = let scratch = Register.v () in let arr = Array.of_list infos and acc = Array.of_list accesses in let cursors = Array.make (Array.length arr) None in let cursor i = Option.get cursors.(i) in let scan_of i = let _, _, mk = arr.(i) in mk () in let drained ?filter ~read ~keys i = let _, cols, mk = arr.(i) in let h = held ~width:(List.length cols) ~read keys in let budget = S.budget t in let whole () = drain ~budget ~cols:h.cols mk in let rows = match filter with | None -> whole () | Some f -> ( match drain_kept t params ~budget ~held:h.cols arr.(i) f with | Some kept -> kept | None -> whole ()) in Option.map (fun rows -> (rows, h)) rows in (* The side each probe of a table builds, and every column the probes of that side read or are keyed on: the hash of a relation joined twice holds what either end reads, and is drained once. *) let sides = Array.mapi (fun i a -> match (a, relation i) with | Plan.Probe { filter; _ }, Some table -> Some (build_side table filter) | _ -> None) acc in let side_reads s = List.concat (List.mapi (fun j a -> match (a, sides.(j)) with | Plan.Probe { key; rest; _ }, Some s' when same_side s s' -> read j @ probe_keys key rest | _ -> []) (Array.to_list acc)) in let built = ref [] in let probed ?filter ~keys i = match sides.(i) with | None -> drained ?filter ~read:(read i) ~keys i | Some s -> ( match List.find_opt (fun (s', _) -> same_side s s') !built with | Some (_, rows) -> rows | None -> let rows = drained ?filter ~read:(side_reads s) ~keys:[] i in built := (s, rows) :: !built; rows) in (* the INTEGER PRIMARY KEY of the table the source at [i] reads, [-1] for none *) let rowid_column i = match relation i with | Some table -> Option.value ~default:(-1) (rowid_alias (S.table t table).schema) | None -> -1 in (* The cursor of the source at [i] reading through [a], whose seek reads through [sought]; [unmatched] for the loop over the rows a RIGHT or FULL join kept unmatched, which the loop tests whatever it answers. *) let rec cursor_for ~unmatched ~sought i a = match a with | Plan.Scan -> scan_of i | Plan.Probe { key; outer; coll; nulls; rest; spill; filter; auto; _ } -> (* Built at its first rewind, when the loop stands on an outer row: the outer cursor has read the pages planning read to estimate it, and holds them, before the build reads a relation's worth more. *) deferred (fun () -> match probed ?filter ~keys:(probe_keys key rest) i with (* Too large to hold. An index over the join key still answers a rewind, so a declined seek is what this falls back to; only with none is the scan the answer, and then the join costs the product. *) | None -> let a = Option.value spill ~default:Plan.Scan in if not unmatched then acc.(i) <- a; cursor_for ~unmatched ~sought i a | Some (rows, h) -> let rows = match auto with | None -> rows | Some _ -> Sql.Join.ordered ?collation:coll ~key:(Option.map (fun _ -> h.slot.(key)) outer) ~by: (auto_index_columns h ~covers:(read i) ~keys:(probe_keys key rest) ~rowid:(rowid_column i)) rows in (* Uncounted: a probe is a lookup, not a full scan. The pass that drained the inner relation was counted as it read. A constant's one bucket is every row held. *) widened h (match outer with | None -> rows_cursor Fun.id rows () | Some (src, pos) -> Sql.Join.probe ?collation:coll ~nulls ~rest: (List.map (fun (inner_key, src, outer_key, collation) -> { Sql.Join.outer = cursor src; outer_key; inner_key = h.slot.(inner_key); collation; nulls = false; }) rest) ~outer:(cursor src) ~outer_key:pos ~inner:rows ~inner_key:h.slot.(key) ())) | Plan.Ordered { table; index = None; reverse; _ } -> ( match (S.table t table).store with | Pk_index_rows p -> own_walk t ~table p ~reverse | Rowid_rows _ -> scan_of i) | Plan.Ordered { table; index = Some index; covering; reverse } -> ( match List.find_opt (fun (idx : index) -> Ident.equal idx.name index) (S.table t table).indexes with | Some index -> index_scan t ~table ~index ~reverse ~covering | None -> scan_of i) | Plan.Seek { table; path; keys; range; reverse } -> (* a range's bounds are read as keys after the equated ones *) let keys = match range with | None -> keys | Some r -> keys @ List.filter_map (Option.map (fun (b : Plan.bound) -> { Plan.column = ""; value = b.value; affinity = []; nulls = false; answers = None; })) [ r.lo; r.hi ] in let into = Array.make (List.length keys) (Seek.Value Sql.Ast.Null) in seek t ~table ~reverse ~path:(Option.get sought) ~values: (key_values params ~cursor ~scratch ~into ~set ~walk:(set_walk t ~table ~index:path.Plan.index) keys) ~scan: (* the loop no longer tests what such a seek answers, so its rows are the seek's or none *) (if (not unmatched) && Plan.answered a <> [] then fun () -> Fmt.invalid_arg "Cursor.accesses: the seek of %s answers a conjunct but \ reads no path for its key" table else fun () -> scan_of i) in let keyed = if Array.length acc < 2 then [||] else keyed_sources acc in let keyed_on i c = if Array.length keyed > 0 && keyed.(i) then on_row c else c in let subs = Hashtbl.create 1 in let build i = let c = keyed_on i (cursor_for ~unmatched:false ~sought:paths.(i) i acc.(i)) in cursors.(i) <- Some (match List.find_opt (fun (k, _, _) -> k = i) unmatched with | None -> c | Some (_, a, sought) -> let sub, proxy = switching c (keyed_on i (cursor_for ~unmatched:true ~sought i a)) in Hashtbl.replace subs i sub; proxy) in List.iter build order; Array.append (Array.map Option.get cursors) (Array.of_list (List.map (fun (i, _, _) -> Hashtbl.find subs i) unmatched)) end