(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* What a CREATE TABLE declares, read back out of it: the columns and their affinities, the DEFAULT expressions, which columns an index keys on and under which sequence and order, and the UNIQUE and CHECK constraints. All of it answers about a schema, so none of it needs a handle or a b-tree. *) open Model module Engine = Sql.Private.Engine module Query = Sql.Private.Query module Lexer = Sql.Private.Lexer (* Text this engine cannot read is not an error here: it is a table whose facts it does not know, kept so the rest of the database stays readable. *) let parse_sql sql = match Sql.Private.Lexer.parse sql with Ok ct -> Some ct | Error _ -> None (* Whether [c] is the rowid under another name. An INTEGER PRIMARY KEY aliases the rowid only where there is one to alias, and a WITHOUT ROWID table has none, so the parser states what the column alone declares and this what the table makes of it. *) let is_rowid_alias (ct : Sql.Ast.create_table) (c : Sql.Ast.column_def) = c.is_rowid_alias && not ct.ct_without_rowid (* Whether column [c] must hold a value, and how a NULL there resolves. A PRIMARY KEY column carries NOT NULL whether or not it declares one in a STRICT table and in a WITHOUT ROWID one, whose key cannot be missing; the rowid alias is outside both. Such an imposed NOT NULL is ABORT without a clause; anywhere else a PRIMARY KEY column accepts NULL. *) let column_not_null (ct : Sql.Ast.create_table) pk (c : Sql.Ast.column_def) = match c.not_null with | Some _ as declared -> declared | None -> if (ct.ct_strict || ct.ct_without_rowid) && (not (is_rowid_alias ct c)) && List.exists (Catalog.Ident.equal c.name) pk then Some Sql.Ast.Unspecified else None let columns_of_parsed = function | None -> [] | Some (ct : Sql.Ast.create_table) -> let pk = Sql.Private.Create_table.primary_key_columns ct in List.map (fun (c : Sql.Ast.column_def) -> { name = c.name; affinity = c.affinity; type_affinity = (if ct.ct_strict && Sql.Private.Strict.of_type_name c.affinity = Some Sql.Private.Strict.Any then `Blob else Sql.Value_ops.affinity_of_type c.affinity); is_rowid_alias = is_rowid_alias ct c; not_null = column_not_null ct pk c; primary_key = c.primary_key; collation = c.collation; generated = Option.map (fun (g : Sql.Ast.generated_column) -> g.kind) (Catalog.Ident.assoc_opt c.name ct.generated); }) ct.columns let parse_create_table sql = columns_of_parsed (parse_sql sql) let column_names columns = List.map (fun (c : column) -> c.name) columns (* Which columns a read widens an integer to a real in: one byte per declared column, set where the column's type gives it REAL affinity, and [None] where none has. A REAL column stores an integer-valued one as an integer and widens it back on the way out, so this is asked of every row a read spreads back. Deferred and kept, since a mask is a byte per column. *) let real_columns ~columns = lazy (let mask = Bytes.make (List.length columns) '\000' in List.iteri (fun i (c : column) -> if c.type_affinity = `Real then Bytes.set mask i '\001') columns; if Bytes.exists (fun b -> b <> '\000') mask then Some mask else None) (* A partial index's predicate as the index carries it: what the CREATE INDEX text spells, sequences made explicit. [None] for an index that is not partial. The index carries it because more than one reader decides by it, and an entry only one would have written is a file the other reads as damaged. *) let index_predicate (schema : schema) where = Option.map (Sql.Private.Table.collate (Lazy.force schema.table)) where (* Find the index of the rowid alias column, if any *) let rowid_alias_index columns = let rec find i = function | [] -> None | c :: _ when c.is_rowid_alias -> Some i | _ :: rest -> find (i + 1) rest in find 0 columns (* The rowid alias's position in [schema], read once per schema. *) let rowid_alias (schema : schema) = Lazy.force schema.rowid_alias (* What a record that ends before each column reads for it, positionally: the column's DEFAULT settled under its affinity, and NULL where it declares none or one that does not settle (sqlite3ColumnDefault, src/expr.c). A REAL column's integer is widened by the read, as any stored one is. The affinity is the one the column compares under, which a STRICT type's is too. *) let record_defaults ~parsed ~columns = lazy (let defs = match parsed with None -> [] | Some ct -> ct.Sql.Ast.defaults in Array.of_list (List.map (fun (c : column) -> match Catalog.Ident.assoc_opt c.name defs with | Some (d : Sql.Ast.column_default) -> Option.value ~default:Sql.Ast.Null (Sql.Private.Table.settle c.type_affinity d.expr) | None -> Sql.Ast.Null) columns)) (* The index [idx] as its CREATE INDEX statement declares it, where it has one: a constraint's index is the constraint's, which the table's schema carries. *) let storage_index (idx : index) = match (idx.origin, idx.sql) with | Created, Some sql -> ( match Lexer.parse_statements sql with | Ok [ Sql.Ast.Create_index ci ] -> Some (Engine.index_schema ci) | Ok _ | Error _ -> None) | (Created | Unique_constraint | Primary_key), _ -> None (* The table [tbl_name] declares as the store holds it, from its parse where it has one, else from its columns alone. *) let spi_schema ~indexes ~without_rowid ~tbl_name ~sql ~parsed ~columns = let indexes = List.filter_map storage_index indexes in match parsed with | Some ct -> let t = Engine.table_schema ~source:sql ct in (* a STRICT table's key columns are NOT NULL as the store holds them *) let columns = List.map2 (fun (sc : Catalog.Spi.Schema.column) (c : column) -> if c.not_null <> None && not sc.not_null then { sc with not_null = true } else sc) t.columns columns in Catalog.Spi.Schema.v ?primary_key: (Option.map (fun (p : Catalog.Spi.Schema.primary_key) -> p.keys) t.primary_key) ?on_primary_key: (Option.bind t.primary_key (fun (p : Catalog.Spi.Schema.primary_key) -> p.on_conflict)) ?primary_key_on_column: (Option.map (fun (p : Catalog.Spi.Schema.primary_key) -> p.on_column) t.primary_key) ~uniques:t.uniques ~checks:t.checks ~foreign_keys:t.foreign_keys ~autoincrement:t.autoincrement ~without_rowid ~strict:t.strict ~indexes t.table columns | None -> Catalog.Spi.Schema.v ~primary_key_on_column:false ~without_rowid ~indexes tbl_name (List.map (fun (c : column) -> Catalog.Spi.Schema.column ~decl_type:c.affinity ~not_null:(c.not_null <> None) ?collation:c.collation c.name) columns) let storage_schema ?(indexes = []) ~without_rowid (s : schema) = spi_schema ~indexes ~without_rowid ~tbl_name:s.tbl_name ~sql:s.sql ~parsed:s.parsed ~columns:s.columns (* The one place a schema record is built. Its derived fields are functions of the columns and the parse beside them, so building them anywhere else is how a schema ends up carrying a lazy computed from the columns it replaced -- the ALTER paths derive a new column list from the old one, and go back through here for the rest. The write rules are the engine's, read from the table as the store holds it. *) let schema ~encoding ~tbl_name ~sql ~parsed ~columns = let without_rowid = match parsed with | Some (ct : Sql.Ast.create_table) -> ct.ct_without_rowid | None -> false in let table = lazy (Sql.Private.Table.v ~encoding (spi_schema ~indexes:[] ~without_rowid ~tbl_name ~sql ~parsed ~columns)) in { tbl_name; columns; sql; parsed; table; record_defaults = record_defaults ~parsed ~columns; names = lazy (column_names columns); real_cols = real_columns ~columns; rowid_alias = lazy (rowid_alias_index columns); } (* A schema whose columns the CREATE TABLE text alone decides, for a caller that has already parsed it: the one parse serves both the schema and whatever the caller does with the statement. *) let schema_of_ast ~encoding ~tbl_name ~sql ct = let parsed = Some ct in schema ~encoding ~tbl_name ~sql ~parsed ~columns:(columns_of_parsed parsed) (* A schema whose columns the CREATE TABLE text alone decides. *) let schema_of_sql ~encoding ~tbl_name sql = let parsed = parse_sql sql in schema ~encoding ~tbl_name ~sql ~parsed ~columns:(columns_of_parsed parsed) (* A schema whose columns the caller already holds: the kv tables, which declare theirs, and the ALTER paths, which derive the new column list from the old one rather than from the text they rewrite. *) let schema_of_columns ~encoding ~tbl_name ~columns ~sql = schema ~encoding ~tbl_name ~sql ~parsed:(parse_sql sql) ~columns (* A table's PRIMARY KEY column names, in key order. Either spelling reaches it: a [PRIMARY KEY] on a column, or a table-level [PRIMARY KEY (a, b)]. *) let pk_column_names (schema : schema) = match schema.parsed with | None -> [] | Some ct -> Sql.Private.Create_table.primary_key_columns ct let column_index names name = Catalog.Ident.index name names (* The collating sequence key column [pos] of an index is ordered by: the one the index definition names, else the column's declared COLLATE, else BINARY. This door takes the resolver's refusal as a value rather than a raise, since an application may register its own sequences and a file can name one this engine has never heard of, costing its indexes and not the database. *) let resolve_collation name = match Sql.Private.Collate.resolve name with | c -> Ok c | exception Catalog.Error (Prepare e) -> Error e (* The sentence a key column the table does not declare is refused with: the resolver's, since every index key reaches sqlite3ResolveSelfReference one at a time, so all three key shapes are refused the same way. *) let err_no_column col = Fmt.kstr (fun e -> Error e) "no such column: %s" col (* The name BINARY, which a key naming no sequence is ordered by and which the pragmas print for it. *) let default_collation_name = Sql.Collation.to_string Sql.Collation.default (* The collating sequence key column [pos] names, as the schema spells it: the index definition's own COLLATE, else the column's declared one, else BINARY. sqlite3 keeps the spelling on the index (Index.azColl) and prints it back unchanged, folding case only to resolve it. *) let key_collation_name (columns : column list) ~named pos = let declared = Option.bind (List.nth_opt columns pos) (fun c -> c.collation) in match if Option.is_some named then named else declared with | Some name -> name | None -> default_collation_name let key_collation_result (columns : column list) ~named pos = let declared = Option.bind (List.nth_opt columns pos) (fun c -> c.collation) in let name = if Option.is_some named then named else declared in match name with | None -> Ok Sql.Collation.default | Some name -> resolve_collation name (* The same, where the caller is a statement being prepared rather than a schema being loaded: there is nothing to degrade, so an unknown name fails it. *) let key_collation columns ~named pos = match key_collation_result columns ~named pos with | Ok c -> c | Error e -> Catalog.Error.fail (Prepare e) (* The order key column [pos] of an index is compared in: the sequence above, and the direction the definition's ASC/DESC names. Every index resolves its orders here -- a UNIQUE/PRIMARY KEY autoindex and an explicit CREATE INDEX, built fresh or reconnected from the stored schema text -- so a reopened database orders its keys exactly as the handle that wrote them did. *) let key_order_result columns (c : Sql.Ast.indexed_column) pos = Result.map (fun coll -> ( Sql.Order.v ~desc:c.desc coll, key_collation_name columns ~named:c.collation pos )) (key_collation_result columns ~named:c.collation pos) (* The order an expression key is compared in: the sequence written on the key itself, its outermost node where that is a postfix COLLATE, else BINARY. The key computes under the depth-first sequence inside it and is filed under this one, sqlite3's read at CREATE INDEX; reading the inner one instead orders the entries by a sequence no other SQLite would use. *) let expression_key_order ~desc e = match e with | Sql.Ast.Collate (_, name) -> Result.map (fun c -> (Sql.Order.v ~desc c, name)) (resolve_collation name) | _ -> Ok (Sql.Order.v ~desc Sql.Collation.default, default_collation_name) (* [e] with every top-level COLLATE peeled off (sqlite/src/expr.c, sqlite3ExprSkipCollate). *) let rec skip_collate = function | Sql.Ast.Collate (e, _) -> skip_collate e | e -> e (* An index key read as CREATE INDEX reads it. sqlite3 peels every top-level COLLATE off a key before deciding what the key is, so a COLLATE over a bare column is that column, ordered by the outermost sequence. A qualified name is no column key however wrapped, since sqlite3 refuses the "." while resolving it. *) let index_key_read (k : Sql.Ast.indexed_key) = match k with | Sql.Ast.Column _ -> k | Sql.Ast.Expression { expr; desc } -> ( match (expr, skip_collate expr) with | Sql.Ast.Collate (_, collation), Sql.Ast.Col (None, column) -> Sql.Ast.Column { column; collation = Some collation; desc } | _ -> k) (* The sequence a bare reference to column [pos] compares under, which is the column's declared COLLATE (else BINARY) -- no index definition in sight. [None] where the column declares a sequence this engine does not have, since then nothing is known about the order such a reference wants. *) let declared_collation columns pos = Result.to_option (key_collation_result columns ~named:None pos) (* Resolve the key columns of a UNIQUE/PRIMARY KEY constraint or a CREATE INDEX against the table they read: the position of each, the order each is compared in, what put the index in the schema, and how a duplicate key resolves. The failure text is what the index is unusable for. *) let resolve_index_keys (schema : schema) ~origin ?(on_conflict = Sql.Ast.Unspecified) (keys : Sql.Ast.indexed_key list) : (index_key, string) result = let columns = schema.columns in let names = column_names columns in let column_key (c : Sql.Ast.indexed_column) = match column_index names c.column with | None -> err_no_column c.column | Some pos -> Result.map (fun (order, coll) -> (Column pos, order, coll)) (key_order_result columns c pos) in let rec resolve acc = function | [] -> Ok (List.rev acc) | (k : Sql.Ast.indexed_key) :: rest -> ( let resolved = match index_key_read k with | Sql.Ast.Column c -> column_key c (* The order is read off the expression as written and the key stores it collated: the sequence a comparison inside it reads is the one its column operand declares, while the sequence the key itself is ordered by is the one the expression assigns -- and the rewrite assigns sequences the expression did not. *) | Sql.Ast.Expression e -> Result.map (fun (order, coll) -> ( Expression (Sql.Private.Table.collate (Lazy.force schema.table) e.expr), order, coll )) (expression_key_order ~desc:e.desc e.expr) in match resolved with | Error _ as e -> e | Ok r -> resolve (r :: acc) rest) in Result.map (fun resolved -> { keys = List.map (fun (k, _, _) -> k) resolved; orders = List.map (fun (_, o, _) -> o) resolved; colls = List.map (fun (_, _, c) -> c) resolved; origin; on_conflict; }) (resolve [] keys) let resolve_index_columns schema ~origin ?on_conflict (cols : Sql.Ast.indexed_column list) = resolve_index_keys schema ~origin ?on_conflict (List.map (fun c -> Sql.Ast.Column c) cols) (* A table-level UNIQUE / PRIMARY KEY builds the same kind of index a column-level one does, and its [ON CONFLICT] rides along the same way: that clause is the index's own resolution, sqlite3's pIdx->onError. *) let table_unique_constraint schema = function | Sql.Ast.Unique (cols, on_conflict) -> Some (resolve_index_columns schema ~origin:Unique_constraint ~on_conflict cols) | Sql.Ast.Primary_key (cols, on_conflict) -> Some (resolve_index_columns schema ~origin:Primary_key ~on_conflict cols) | _ -> None (* [~without_rowid] decides whether an [INTEGER PRIMARY KEY] column is a key of its own: where the rows are keyed by a rowid it is an alias for that rowid and needs no index, where there is no rowid it is an ordinary key column. *) let column_unique_constraint ~without_rowid schema (c : Sql.Ast.column_def) = let keyed = match c.primary_key with | Some res when without_rowid || not c.is_rowid_alias -> Some (Primary_key, res) | _ -> Option.map (fun res -> (Unique_constraint, res)) c.unique in (* A column-level UNIQUE names no sequence of its own, so its index takes the column's declared COLLATE. Its [ON CONFLICT] rides along: that clause is the index's own resolution, sqlite3's pIdx->onError. A column-level PRIMARY KEY may name a direction, and that direction is the index's, so it is carried over; a UNIQUE cannot, and reads as ascending. *) Option.map (fun (origin, on_conflict) -> let desc = origin = Primary_key && c.pk_desc in resolve_index_columns schema ~origin ~on_conflict [ { column = c.name; collation = None; desc } ]) keyed (* Whether [k] builds the index [earlier] already is: the same columns in the same order under the same collating sequences, whatever the directions. *) let same_index (earlier : index_key) (k : index_key) = List.equal ( = ) earlier.keys k.keys && List.equal (fun a b -> String.equal (String.lowercase_ascii a) (String.lowercase_ascii b)) earlier.colls k.colls (* [k] folded into the earlier constraint [into] that builds the same index (build.c, sqlite3CreateIndex): a PRIMARY KEY makes it the primary key, and an ON CONFLICT moves onto it where it names none. Two that name different ones refuse the table. *) let fold_into (into : index_key) (k : index_key) = let on_conflict = match (into.on_conflict, k.on_conflict) with | Sql.Ast.Unspecified, c -> Ok c | c, Sql.Ast.Unspecified -> Ok c | a, b when a = b -> Ok a | _ -> Error "conflicting ON CONFLICT clauses specified" in Result.map (fun on_conflict -> { into with origin = (if k.origin = Primary_key then Primary_key else into.origin); on_conflict; }) on_conflict (* [constraints] less each one that builds an index an earlier one builds, folded into that one. Such a constraint takes no autoindex and so no number in the sqlite_autoindex_* names. *) let without_repeats constraints = List.fold_left (fun kept c -> match c with | Error _ -> kept @ [ c ] | Ok k -> ( let repeated = function Ok e -> same_index e k | Error _ -> false in match List.find_index repeated kept with | Some i -> List.mapi (fun j e -> if j = i then Result.bind e (fun e -> fold_into e k) else e) kept | None -> kept @ [ c ])) [] constraints (* One entry per UNIQUE/PRIMARY KEY constraint that builds an index, in the order sqlite3 numbers the autoindexes: the order the CREATE TABLE text declares them, every column-level constraint before every table-level one, less each that repeats an earlier one's index. A constraint that does not resolve keeps its place as an [Error], since dropping it would renumber the sqlite_autoindex_* names after it. *) let unique_constraints ~without_rowid (schema : schema) = match schema.parsed with | None -> [] | Some ct -> let column_level = List.filter_map (column_unique_constraint ~without_rowid schema) ct.columns in let table_level = List.filter_map (table_unique_constraint schema) ct.table_constraints in without_repeats (column_level @ table_level) (* The autoindexes of a table this engine stores with a rowid, which is every table it writes. *) let parse_unique_constraints schema = unique_constraints ~without_rowid:false schema (* The CHECK constraints of a table, as the table the engine writes through holds them ({!Sql.Private.Table.checks}). *) let table_checks (schema : schema) = Sql.Private.Table.checks (Lazy.force schema.table) (* The DEFAULT expressions of a table, keyed by column: the source form, which a statement that has to evaluate one reads. A column with no DEFAULT is absent rather than [Null], one defaults to nothing and the other to the null value. Its evaluated counterpart is {!evaluated_defaults}. *) let table_defaults (schema : schema) = match schema.parsed with | None -> [] | Some ct -> List.map (fun (c, (d : Sql.Ast.column_default)) -> (c, d.expr)) ct.Sql.Ast.defaults (* Does [schema] declare AUTOINCREMENT? Only such a table promises a rowid is never handed out twice; a plain one recomputes max + 1. A schema whose text this engine cannot parse answers [false], the ordinary rule. *) let has_autoincrement (schema : schema) = match schema.parsed with | None -> false | Some (ct : Sql.Ast.create_table) -> List.exists (fun (c : Sql.Ast.column_def) -> c.autoincrement) ct.columns (* A name written where a column name goes -- an INSERT's column list, an UPDATE's SET -- that reaches the rowid rather than a column: one of the rowid spellings, no column declaring it, on a table keyed by a rowid. The INTEGER PRIMARY KEY is not this: it answers by its own name. *) let written_rowid columns ~has_rowid name = has_rowid && Sql.Ast.is_rowid_name name && not (List.exists (fun (c : column) -> Catalog.Ident.equal c.name name) columns)