Something went wrong. Try again.
SQLite file format and SQL engine in pure OCaml
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
open Modelopen Declopen Sql.Ast
(* Whether [e] is built of literals and parameters alone, through the operators and CASTs: its value is the same for every row, so a seek can be bounded by it. A function call is left out, since some ([random()]) are not. *)let rec constant (e : Sql.Ast.expr) = match e with | Lit _ | Numeral _ | Param _ -> true | Unary_minus a | Unary_plus a | Cast (a, _) | Affinity (a, _) -> constant a | Binary (_, a, b) -> constant a && constant b | _ -> false
(* The value of a constant operand: a literal, a parameter, or an expression of them ({!constant}), folded once as sqlite3 folds it before a seek: [c BETWEEN 'x' AND ('x' || '~')] is bounded on both sides. A parameter left unbound is NULL, as sqlite3 binds it (vdbeapi.c) and {!Sql.Private.Engine} reads it. *)let rec const_value params = function | (Sql.Ast.Lit _ | Sql.Ast.Numeral _) as e -> Sql.Ast.literal e | Sql.Ast.Param i -> Some (if i >= 0 && i < Array.length params then params.(i) else Null) (* a COLLATE or a stated affinity leaves the value as it is: the comparison under it is the caller's to have checked *) | Sql.Ast.Collate (e, _) | Sql.Ast.Affinity (e, _) -> const_value params e | e when constant e -> ( match Sql.Private.Engine.eval_const (* a rowid bound, folded to the number it names *) (Sql.Private.Query.closed ~encoding:Sql.Encoding.Utf8 "a constant operand") params e with | v -> Some v | exception Catalog.Error (Prepare _ | Runtime _) -> None) | _ -> None
(* [arg] denotes the rowid of the table declaring [columns] (queried as [name], alias [alias]): a rowid keyword not shadowed by a real column, or the INTEGER PRIMARY KEY alias. *)let names_rowid columns name alias arg = match arg with | Sql.Ast.Col (qual, c) -> let same = Catalog.Ident.equal in let qual_ok = match qual with | None -> true | Some q -> same q name || Option.fold ~none:false ~some:(same q) alias in let declared = List.exists (fun (col : column) -> same col.name c) columns in let is_alias = match rowid_alias_index columns with | Some i -> same (List.nth columns i).name c | None -> false in qual_ok && ((Sql.Ast.is_rowid_name c && not declared) || is_alias) | _ -> false
(* SELECT <cols> FROM t [ORDER BY rowid [DESC]] LIMIT n [OFFSET m] over one plain rowid table emits the n rows in rowid order with a bounded scan, instead of materialising, sorting and slicing the whole table. The bounded rows are fed through the normal engine over a restricted catalog, so the projection, ORDER BY and column handling stay the engine's. *)
(* The integer value of a constant LIMIT/OFFSET ([Lit] or a bound [Param]). *)let const_int params = function | Sql.Ast.Lit (Int n) -> Some (Int64.to_int n) | Sql.Ast.Param i when i >= 0 && i < Array.length params -> ( match params.(i) with Int n -> Some (Int64.to_int n) | _ -> None) | _ -> None
(* An expression a LIMIT scan may keep: it folds no aggregate's siblings into the answer the way a subquery, window, or (caught elsewhere) aggregate does -- those would compute over the bounded set, not the whole table. *)let rec pushdown_safe (e : Sql.Ast.expr) = match e with | In_select _ | Scalar_select _ | Exists _ | Window _ -> false | Func (_, args) | In_list (_, args) -> List.for_all pushdown_safe args | Binary (_, a, b) | Is (a, b) -> pushdown_safe a && pushdown_safe b | Unop_not a | Is_null a | Is_not_null a | Cast (a, _) | Unary_plus a | Unary_minus a | Collate (a, _) | Affinity (a, _) | Distinct_agg (_, a) | Filter (a, _) | Ordered_agg (a, _) -> pushdown_safe a | Case (base, brs, els) -> Option.fold ~none:true ~some:pushdown_safe base && List.for_all (fun (c, r) -> pushdown_safe c && pushdown_safe r) brs && Option.fold ~none:true ~some:pushdown_safe els (* RAISE is not an expression a scan may be bounded around: it aborts the statement rather than answering, so a bound that skipped it would skip the abort. *) | Raise _ -> false | Lit _ | Truth _ | Numeral _ | Param _ | Named_param _ | Col _ | Star | Qualified_star _ -> true (* Resolves nowhere, so the statement is refused before a scan is bounded. *) | Schema_col _ -> false
(* The inclusive rowid range a WHERE confines the scan to, or [None] when it is not a pure conjunction of rowid comparisons (a non-rowid predicate may reject rows, needing more than [limit] read). [None] WHERE is the whole range. Each top-level conjunct must be [rowid OP const], or its mirror. *)let flip_cmp = function | Sql.Ast.Gt -> Sql.Ast.Lt | Sql.Ast.Lt -> Sql.Ast.Gt | Sql.Ast.Ge -> Sql.Ast.Le | Sql.Ast.Le -> Sql.Ast.Ge | op -> op
let narrow_range (lo, hi) op c = (* [empty] when a strict bound would overflow past the int64 edge. *) let empty = (Int64.max_int, Int64.min_int) in match op with | Sql.Ast.Gt -> if c = Int64.max_int then empty else (max lo (Int64.add c 1L), hi) | Sql.Ast.Ge -> (max lo c, hi) | Sql.Ast.Lt -> if c = Int64.min_int then empty else (lo, min hi (Int64.sub c 1L)) | Sql.Ast.Le -> (lo, min hi c) | Sql.Ast.Eq -> (max lo c, min hi c) | _ -> (lo, hi)
(* [range] narrowed by [rowid op v], [v] read as sqlite3's seek reads it (vdbe.c, OP_SeekGT and its siblings): under numeric affinity, so a text spelling a number is that number; a real bounds at the integer next past it on its side; NULL keeps no row; and a text spelling no number, or a blob, sorts after every integer. The rowid holds integers only, so the span is the rows the comparison keeps, no more. *)let narrow_value range op (v : Sql.Ast.value) = let empty = (Int64.max_int, Int64.min_int) in let real = match v with | Float f -> Some f | Text s -> ( match Sql.Value_ops.whole_number s with | Some (Float f) -> Some f | _ -> None) | Int _ | Null | Blob _ -> None in match (v, Rowid.of_value v, real) with | Null, _, _ -> empty | _, Some c, _ -> narrow_range range op c | _, None, Some f when Float.is_nan f -> empty | _, None, Some f when f >= -0x1p63 && f < 0x1p63 -> ( match op with | Sql.Ast.Gt | Sql.Ast.Ge -> narrow_range range Sql.Ast.Ge (Int64.of_float (Float.ceil f)) | Sql.Ast.Lt | Sql.Ast.Le -> narrow_range range Sql.Ast.Le (Int64.of_float (Float.floor f)) | _ -> empty) | _, None, Some f when f < 0. -> ( match op with Sql.Ast.Gt | Sql.Ast.Ge -> range | _ -> empty) | _, None, _ -> ( match op with Sql.Ast.Lt | Sql.Ast.Le -> range | _ -> empty)
let rec of_expr columns name alias params acc (e : Sql.Ast.expr) = match (acc, e) with | None, _ -> None | Some range, Binary (And, a, b) -> of_expr columns name alias params (of_expr columns name alias params (Some range) a) b | Some range, Binary (((Gt | Ge | Lt | Le | Eq) as op), x, y) -> ( let bound col v op = if names_rowid columns name alias col then Option.map (narrow_value range op) (const_value params v) else None in match bound x y op with | Some r -> Some r | None -> ( match bound y x (flip_cmp op) with Some r -> Some r | None -> None)) | Some _, _ -> None
(* The rowid range for a select's WHERE: the whole range when there is none. *)let of_where columns name alias params = function | None -> Some (Int64.min_int, Int64.max_int) | Some e -> of_expr columns name alias params (Some (Int64.min_int, Int64.max_int)) e
(* The rowid inequalities among the top-level conjuncts of [e], folded into the inclusive span they leave and whether each edge was bounded. A conjunct that bounds nothing here stays in the WHERE the engine applies to the span, so ignoring it only widens the span. *)let rec edges columns name alias params ((range, low, high) as acc) (e : Sql.Ast.expr) = match e with | Binary (And, a, b) -> edges columns name alias params (edges columns name alias params acc a) b | Binary (((Gt | Ge | Lt | Le) as op), x, y) -> ( let bound col v op = if names_rowid columns name alias col then Option.map (fun v -> (op, v)) (const_value params v) else None in let found = match bound x y op with | Some b -> Some b | None -> bound y x (flip_cmp op) in match found with | Some (((Gt | Ge) as op), v) -> (narrow_value range op v, true, high) | Some (op, v) -> (narrow_value range op v, low, true) | None -> acc) | _ -> acc
let bounds columns name alias params where = match edges columns name alias params ((Int64.min_int, Int64.max_int), false, false) where with | _, false, false -> None | (lo, hi), low, high -> Some (lo, hi, low, high)
(* [s] carries nothing but its select list, FROM and WHERE. What the select list holds, and whether the WHERE reads as a rowid range, are the caller's own checks. *)let bare (s : Sql.Ast.select) = List.for_all Fun.id [ s.joins = []; s.group_by = []; s.having = None; s.compound = []; s.ctes = []; not s.distinct; s.order_by = []; s.limit = None; s.offset = None; ]
(* [SELECT MIN(rowid) / MAX(rowid) FROM t [WHERE <rowid range>]]: seek the b-tree edge of the range. A non-rowid WHERE yields no range and falls through to the aggregate path. *)