(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (** How a join reads its inner relation, and how much of one a hash may hold, over a dialect's text keys and numeric reading. A nested loop rewinds the inner side once per outer row. An index seek answers each rewind with a b-tree descent and holds nothing; a hash answers it with a bucket lookup after one pass that holds the whole relation. Which is cheaper is a question about how many times the loop rewinds, not about which indexes happen to exist, so the choice is made from an estimate of that number ({!choose}) and bounded by what the hash would cost in memory ({!val-budget}). Every engine over a {!Catalog.Spi.t} makes the same choice, so it is made once here. *) (** The type for what a hash join keys a value by. *) module type SEMANTICS = sig type collation (** The type for the collating sequences text is compared under. *) val key : collation -> string -> string (** [key c s] is the bytes [c] compares the text [s] by: two texts collate equal exactly when their keys are byte-equal. *) val numeric : string -> float option (** [numeric s] is the number a comparison's numeric affinity reads the text or blob [s] as, or [None] when it leaves [s] as it is. *) end (** The type for join algorithms and cursors. *) module type S = sig type collation (** The type for collating sequences, the semantics'. *) (** The algorithm a join reads its inner relation with. *) type t = | Seek (** an index descent per outer row *) | Hash (** one pass over the inner relation, then a bucket per outer row *) | Scan (** the whole inner relation per outer row: the plain nested loop *) val pp : Format.formatter -> t -> unit (** [pp ppf t] writes [t] as ["seek"], ["hash"] or ["scan"]. *) val equal : t -> t -> bool (** [equal a b] is [true] iff [a] and [b] are the same algorithm. *) val max_rewinds : int (** [max_rewinds] is the ceiling of a rewind estimate. Past it no choice here changes, so a caller multiplying estimates down a chain of sources saturates at this value instead of overflowing. Saturation under-states the rewinds, and so errs towards the seek. *) val index_equality_rows : int (** [index_equality_rows] is the number of rows an equality on a non-unique index is assumed to select when nothing has counted them, sqlite3's default without ANALYZE data. A backend that can count a bucket cheaply gives the count instead. *) val choose : rewinds:int -> inner_rows:int -> seek_yield:int -> covering:bool -> seek:bool -> hash:bool -> t (** [choose ~rewinds ~inner_rows ~seek_yield ~covering ~seek ~hash] is the algorithm for an inner relation of [inner_rows] rows whose cursor the loop rewinds about [rewinds] times, where [seek] says an index covers the join key, [seek_yield] how many rows one of its keys selects, [covering] that the seek answers the query out of that index rather than looking each row up again in the relation, and [hash] that the relation can be hashed on the key and fits {!val-budget}. A seek pays a b-tree descent per rewind and re-reads the rows its key selects; a hash pays one pass over the inner relation, holds it for the whole loop, and answers each rewind from a bucket. So the seek is cheaper while the descents and re-reads it costs stay under what holding the relation costs, which is a question about both numbers and not about [rewinds] alone: hashing a three-row relation to save a few hundred rewinds spends memory to save nothing. [covering] is the widest factor in that comparison. A path that is not covering pays a second descent for every row it hands back, so a bucket of ten rows costs a seek eleven lookups where a covering one costs it one -- which is why an index that happens to hold the answer changes the algorithm and not merely the constant. Then a hash, then a seek the estimate would have declined (better than rescanning), and {!Scan} when neither is available -- an inner join with no equality to hash on, or a relation too large to hold. *) val count_bound : rewinds:int -> next:bool -> int (** [count_bound ~rewinds ~next] is how far an inner relation has to be counted before {!choose} cannot change its mind about it. [next] is [true] when another source follows this one in the loop, whose rewinds this relation's size then estimates. Counting is not free -- a table's rows are counted from its leaf pages -- and past this bound no further row can move either the choice or that estimate, so a huge relation is read a handful of pages deep rather than walked. The last source of a loop sizes nothing after it, and is counted only as far as the choice needs. *) (** {1:budget Build-side budget} *) type budget = { cells : int; (** boxed values the build side may hold *) bytes : int; (** text and blob payload it may hold *) } (** How large a relation a hash build may hold, as two independent limits. Rows measure neither: the same row count costs a hundred times more in a wide table than in a narrow one, and a row of two large blobs is two cells. A build stops at whichever limit it reaches first. *) val budget : budget (** [budget] is the default budget: two million cells or 192 MB of payload, about 190 MB of heap either way. *) val over : budget -> cells:int -> bytes:int -> bool (** [over b ~cells ~bytes] is whether a build side holding that much has passed [b] on either limit. Meant to be called as the build grows, so a relation too large to hold is abandoned rather than completed and dropped. *) val row_bytes : Catalog.Value.t list -> int (** [row_bytes row] is the text and blob payload [row] holds -- the part of a build side's memory that its column count does not predict. *) (** {1:cursors Hash and seek cursors} The inner cursors a nested loop reads its inner relation through, once {!choose} has picked a hash or a seek. Each offers candidates: the rows the join's equality can accept, and some it cannot, so the caller's join predicate still runs on every row offered. *) type key = { outer : Catalog.Cursor.t; (** The cursor the key's value is read from. *) outer_key : int; (** The column of {!field-outer} holding that value. *) inner_key : int; (** The inner column it is equated with. *) collation : collation option; (** The sequence the comparison orders text under, its bytes if [None]. *) nulls : bool; (** [true] for an IS, whose NULL matches the rows keyed NULL. *) } (** The type for one further equality of a multi-key {!probe}. *) val probe : ?collation:collation -> ?nulls:bool -> ?rest:key list -> outer:Catalog.Cursor.t -> outer_key:int -> inner:Catalog.Value.t list list -> inner_key:int -> unit -> Catalog.Cursor.t (** [probe ~outer ~outer_key ~inner ~inner_key ()] is an inner cursor that rewinds onto just the rows whose key matches where [outer] currently stands, read through [outer]'s own column accessor. The VM rewinds it once per outer row, so the loop costs the sum of the two relations rather than their product, and only the inner side is materialised -- the outer rows stream from wherever the caller reads them. The optional argument is the sequence the join's comparison orders text under (its bytes if omitted), so a [NOCASE] key buckets ["ABC"] with ["abc"]. The key is otherwise as loose as SQL equality: integers and reals share a bucket by value, and a text that spells a number shares one with that number ({!SEMANTICS.numeric}), matching the affinity coercion a numeric column applies. With [nulls] (false by default) the key is an IS, and a NULL finds the rows whose key is NULL. [rest] (empty by default) holds the join's further equalities, each read from its own outer cursor. A rewind then offers only the rows that match on every key, each key under its own collating sequence and the same loose equality, and a NULL on any key but an IS offers nothing. The hash on each further key is built over the rows the keys before it selected, the first time an outer value reaches it, and kept for the next outer row that carries that value. So a join whose first key has a single value still costs the sum of the two relations when the further keys tell the rows apart. Rows are offered in the order of [inner]. So the cursor offers every row the join's equality can accept, and some it cannot: it offers candidates, it does not decide them. The caller's join predicate still runs on every row offered, and throws back what does not actually match. *) val ordered : ?collation:collation -> key:int option -> by:int list -> Catalog.Value.t list list -> Catalog.Value.t list list (** [ordered ?collation ~key ~by rows] is [rows] reordered so that every bucket a {!probe} of them on the column [key] under [collation] offers comes in the order of the columns [by] under BINARY, then in the order of [rows]: the order sqlite3's automatic index holds a key's entries in (where.c, constructAutomaticIndex). With [key] [None] the bucket is every row. Where no key spells a number, the buckets are disjoint and each is sorted alone, which costs a comparison per row and per halving of its bucket rather than of [rows]. *) (** The type for the value one key of a {!seek} binds its column to. *) type seek_key = | Bound of Catalog.Value.t (** A value fixed before the loop, such as a constant. *) | Column of Catalog.Cursor.t * int (** Column [j] of the row the cursor stands on when the seek rewinds. *) val seek : lookup:((string * Catalog.Value.t) list -> Catalog.Value.t list list option) -> scan:Catalog.Value.t list list Lazy.t -> (string * seek_key) list -> Catalog.Cursor.t (** [seek ~lookup ~scan keys] is an inner cursor that rewinds onto the rows [lookup] answers for [keys], each column bound to its key's value where the outer cursors stand. It is the inner side of an index nested-loop join: the VM rewinds it once per outer row, so [lookup] is asked once per outer row, the way sqlite3 asks a virtual table's [xFilter], and the inner relation is never read whole. [lookup] answers as {!Catalog.Spi.index_scan} does. A NULL in any key offers no row and asks [lookup] nothing, since an equality holds of no NULL. A [lookup] that answers [None] declines the path for those values, which is not the same as matching nothing: the rewind then offers the rows of [scan], forced the first time a lookup declines and kept for the next. As {!probe}, the cursor offers candidates and the join's predicate still runs on every row offered. Its rows carry no identity. *) end (** [Make (Sem)] is the joins whose keys compare under [Sem]. *) module Make (Sem : SEMANTICS) : S with type collation = Sem.collation