(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* Schema types *) type column = { name : string; affinity : string; type_affinity : Sql.Value_ops.affinity; is_rowid_alias : bool; not_null : Sql.Ast.insert_conflict option; primary_key : Sql.Ast.insert_conflict option; collation : string option; generated : Sql.Ast.generated_kind option; } type schema = { tbl_name : string; columns : column list; sql : string; parsed : Sql.Ast.create_table option; table : Sql.Private.Table.t Lazy.t; record_defaults : Sql.Ast.value array Lazy.t; names : string list Lazy.t; real_cols : Bytes.t option Lazy.t; rowid_alias : int option Lazy.t; } let is_virtual (c : column) = match c.generated with Some Sql.Ast.Virtual -> true | Some _ | None -> false module Kv_cache = struct type ready = { keys : (string, int64) Hashtbl.t; mutable dup : bool } type t = { mutable ready : ready option } type lookup = Unloaded | Missing | Rowid of int64 let unloaded () = { ready = None } let empty () = { ready = Some { keys = Hashtbl.create 64; dup = false } } let lookup t key = match t.ready with | None -> Unloaded | Some r -> ( match Hashtbl.find_opt r.keys key with | None -> Missing | Some rowid -> Rowid rowid) let stored t ~key ~rowid = match t.ready with | None -> () | Some r -> ( match Hashtbl.find_opt r.keys key with | Some held when held <> rowid -> r.dup <- true; if rowid > held then Hashtbl.replace r.keys key rowid | _ -> Hashtbl.replace r.keys key rowid) let invalidate t = t.ready <- None let dropped t ~key = match t.ready with | None -> () | Some r -> if r.dup then invalidate t else Hashtbl.remove r.keys key end type kv_table = { btree : Btree.Table.t; mutable cache : Kv_cache.t } type Eio.Exn.err += Is_a_directory let () = Eio.Exn.register_pp (fun ppf -> function | Is_a_directory -> Fmt.string ppf "Is_a_directory"; true | _ -> false) let fail_is_a_directory path = raise (Eio.Exn.add_context (Eio.Exn.create Is_a_directory) "opening %a" Eio.Path.pp path) let fail_busy fmt = Fmt.kstr (fun s -> Catalog.Error.fail (Busy s)) fmt let fail_readonly () = Catalog.Error.fail (Readonly "attempt to write a readonly database") let fail_readonly_rollback fmt = Fmt.kstr (fun s -> Catalog.Error.fail (Readonly_rollback s)) fmt let fail_readonly_dbmoved fmt = Fmt.kstr (fun s -> Catalog.Error.fail (Readonly_dbmoved s)) fmt type index_origin = | Created (** an explicit CREATE INDEX: "c" *) | Unique_constraint (** a UNIQUE constraint's autoindex: "u" *) | Primary_key (** a PRIMARY KEY's autoindex: "pk" *) let origin_name = function | Created -> "c" | Unique_constraint -> "u" | Primary_key -> "pk" type index_column = { cid : int; order : Sql.Order.t; coll : string } let xn_rowid = -1 let xn_expr = -2 type index_key_source = Column of int | Expression of Sql.Ast.expr let key_column_position = function Column i -> Some i | Expression _ -> None let key_cid = function Column i -> i | Expression _ -> xn_expr type index_decl = { name : string; unique : bool; origin : index_origin; partial : bool; key_columns : index_column list option; (** the key columns in key order, or [None] where a key names a collating sequence this build cannot resolve: the index is still the schema's, and still listed, but nothing true can be said about the order its entries sit in *) trailing_columns : index_column list option; (** what the record carries past its key, or [None] where unknown *) } type index_key = { keys : index_key_source list; orders : Sql.Order.t list; colls : string list; (** each key's collating sequence as the schema spells it, for the pragmas that print it *) origin : index_origin; on_conflict : Sql.Ast.insert_conflict; } type stat = { rows : int; per_prefix : int list } let string_of_stat s = String.concat " " (List.map string_of_int (s.rows :: s.per_prefix)) let stat_of_string str = let rec ints acc = function | [] -> List.rev acc | w :: rest -> ( match int_of_string_opt w with | Some n -> ints (n :: acc) rest | None -> List.rev acc) in match ints [] (String.split_on_char ' ' (String.trim str)) with | [] -> None | rows :: per_prefix -> Some { rows; per_prefix } let stat_per_prefix ~rows ~distinct = let distinct = max 1 distinct in let v = (rows + distinct - 1) / distinct in (* a ratio only just above one is one, not two *) if v = 2 && rows * 10 <= distinct * 11 then 1 else v type trailing = | Rowid_ref (** the rowid of the row in the table b-tree *) | Pk_ref of index_column list (** the PRIMARY KEY columns of a table whose rows are index-b-tree keys *) let entry_orders ~orders = function | Rowid_ref -> orders @ [ Sql.Order.default ] | Pk_ref cols -> orders @ List.map (fun (c : index_column) -> c.order) cols type index = { keys : index_key_source list; (* what each key position reads, in key order *) orders : Sql.Order.t list; (* one per key, positionally *) trailing : trailing; (* what its entries carry past the key to name the row. Part of the record the tree compares, so [entry_orders] reads it to build the order the tree is created with and reopened under. *) name : string; (* sqlite_master name, e.g. "sqlite_autoindex_t_1" *) tbl_name : string; (* owning table name *) unique : bool; (* enforce distinct keys *) origin : index_origin; (* what put it in the schema *) on_conflict : Sql.Ast.insert_conflict; (* the ON CONFLICT the constraint that built it declared, sqlite3's pIdx->onError; Unspecified for an explicit CREATE INDEX, which has no such clause, and for a constraint naming no action *) sql : string option; (* explicit CREATE INDEX text; None for autoindexes *) where : Sql.Ast.expr option; (* CREATE INDEX ... WHERE p: the rows it holds *) btree : Btree.Index.t; (* persistent B-tree index *) master_rowid : int64; (* the rowid of its row in sqlite_master *) mutable stat : stat option; (* what the last ANALYZE measured; None until something has. Mutable because it is not part of the schema: no statement declares it, and the rows it describes go on moving underneath it. *) } type pk_rows = { index : Btree.Index.t; layout : int array; key : (index_column list * int) option; place : int; on_conflict : Sql.Ast.insert_conflict; } type row_store = Rowid_rows of Btree.Table.t | Pk_index_rows of pk_rows type unusable_index = { name : string; master_rowid : int64; (* its sqlite_master row; none where root_page is 0 *) root_page : int; sql : Sql.Ast.value; (* stored CREATE INDEX text; Null for an autoindex *) reason : string; } type generic_table = { store : row_store; schema : schema; master_rowid : int64; (* the rowid of the table's row in sqlite_master *) indexes : index list; unusable : unusable_index list; explicit : string list; (** the names of the CREATE INDEX indexes, in the order the schema declares them. Reconnected and kept ones are otherwise in two lists, and PRAGMA index_list numbers them by that one order. *) } type raw_master_entry = { rowid : int64; type_ : string; name : string; tbl_name : string; root_page : int; sql : Sql.Ast.value; } let rows_root = function | Rowid_rows b -> Btree.Table.root_page b | Pk_index_rows p -> Btree.Index.root_page p.index let rows_encoding = function | Rowid_rows b -> Btree.Table.encoding b | Pk_index_rows p -> Btree.Index.encoding p.index let row_count store ~upto = match store with | Rowid_rows b -> Btree.Table.row_count b ~upto | Pk_index_rows p -> Btree.Index.fold_from p.index (Btree.Record.encode (Btree.Index.encoding p.index) []) ~init:0 ~f:(fun n _ -> let n = n + 1 in if n >= upto then `Stop n else `Continue n) (* The rows a rowid table holds, estimated off the paths from its root to its first and its last leaf. The first leaf's cells and the fan-out of each page above it give the rows of a full subtree at every level, a table its rows were appended to being as full everywhere off its last path as it is on its first. The last path then counts, level by level, the full subtrees left of it, and ends on the last leaf's own cells, so the answer is exact for such a table. Taking the last subtree to be half full instead is a third of the table off on a root of two children. A scan of the table reads the first path's pages first, out of the cache, and the last path's last. Each page of the last path is read twice, as a page the cache is to keep is: one read once is dropped while a scan streams past it and fetched again at the end, and one read again is kept, so a scan that follows the plan reads every page the estimate did out of the cache. [None] for a table whose root is a leaf, which a count reads in one page, for one whose two paths disagree on its depth, and for a store that is not a rowid b-tree. *) let estimate_rows pager store ~upto = match store with | Pk_index_rows _ -> None | Rowid_rows b -> ( let hdr p = if p = 1 then 100 else 0 in let read p = let buf = Btree.Pager.checked pager p ~hdr:(hdr p) in (buf, hdr p, Btree.Page.Unchecked.header buf (hdr p)) in let times a b = if a = 0 || b <= upto / a then min upto (a * b) else upto in let plus a b = min upto (a + b) in let root = Btree.Table.root_page b in (* the fan-outs down the first path, the deepest first, at most twenty levels as a sound file has, and the first leaf's cells *) let rec first depth p fanouts = let buf, off, h = read p in match h.Btree.Page.kind with | Btree.Page.Leaf_table when depth > 0 -> Some (fanouts, h.Btree.Page.cell_count) | Btree.Page.Interior_table when depth <= 20 && h.cell_count > 0 -> let child = Btree.Page.u32_be buf (Btree.Page.cell_pointer buf off h 0) land 0xffff_ffff in first (depth + 1) child ((h.cell_count + 1) :: fanouts) | _ -> None in match first 0 root [] with | None -> None | Some (fanouts, per_leaf) -> let depth = List.length fanouts in (* [full.(d)]: the rows of a full subtree whose root is [d] levels down *) let full = Array.make (depth + 1) (max 1 per_leaf) in List.iteri (fun i f -> let d = depth - 1 - i in if d >= 1 then full.(d) <- times f full.(d + 1)) fanouts; (* [rows] counted left of the last path, down to page [p], [d] levels down *) let rec last d p rows = if rows >= upto then Some upto else begin ignore (read p); let _, _, h = read p in match (h.Btree.Page.kind, h.right_child) with | Btree.Page.Leaf_table, _ when d = depth -> Some (plus rows h.cell_count) | Btree.Page.Interior_table, Some right when d < depth -> last (d + 1) right (plus rows (times h.cell_count full.(d + 1))) | _ -> None end in last 0 root 0) let unsupported_storage gt what = Catalog.Error.fail_unsupported "%s %S: it is a WITHOUT ROWID table, whose rows are the keys of an index \ b-tree" what gt.schema.tbl_name let rowid_stored gt = match gt.store with Rowid_rows _ -> true | Pk_index_rows _ -> false let rowid_btree gt = match gt.store with | Rowid_rows b -> b | Pk_index_rows _ -> unsupported_storage gt "cannot address by rowid a row of" let maintainable gt = match gt.unusable with | [] -> gt | (u : unusable_index) :: _ -> Catalog.Error.fail_unsupported "cannot write %S: cannot maintain index %s: %s" gt.schema.tbl_name u.name u.reason let pk_key gt (p : pk_rows) = match p.key with | Some k -> k | None -> Catalog.Error.fail_unsupported "cannot modify %S: its PRIMARY KEY orders the rows by a collating \ sequence this build does not have" gt.schema.tbl_name