(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) (* The columns a table's PRIMARY KEY is over, whether it was declared on a column or as a table constraint. *) let primary_key_columns (ct : Ast.create_table) = List.filter_map (fun (c : Ast.column_def) -> if c.primary_key <> None then Some c.name else None) ct.columns @ List.concat_map (function | Ast.Primary_key (cs, _) -> Ast.indexed_column_names cs | _ -> []) ct.table_constraints (* Whether a DEFAULT expression is a constant. SQLite requires defaults to be constant, a column reference making the CREATE TABLE fail, and constant functions allowed. The same rule admits a DEFAULT into a CREATE TABLE and an ADD COLUMN; whether an ADD COLUMN may declare it over existing rows is {!settle}'s narrower question. *) let constant_default e = let rec not_constant : Ast.expr -> bool = function | Ast.Lit _ | Ast.Truth _ | Ast.Numeral _ -> false | Col _ | Schema_col _ | Star | Qualified_star _ | Param _ | Named_param _ | In_select _ | Scalar_select _ | Exists _ -> true | Unop_not e | Is_null e | Is_not_null e | Cast (e, _) | Unary_plus e | Unary_minus e | Collate (e, _) | Affinity (e, _) -> not_constant e | Binary (_, a, b) | Is (a, b) -> not_constant a || not_constant b | In_list (e, l) -> not_constant e || List.exists not_constant l | Func (_, args) -> List.exists not_constant args (* sqlite3 3.54.0 refuses [DEFAULT (RAISE(ABORT,'x'))] with "default value of column [x] is not constant" -- it aborts rather than answering, so it is no more a constant than a column reference is. *) | Raise _ -> true | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ -> true | Case (base, whens, els) -> Option.fold ~none:false ~some:not_constant base || List.exists (fun (c, r) -> not_constant c || not_constant r) whens || Option.fold ~none:false ~some:not_constant els in not (not_constant e) (* The rules sqlite3 decides as it reads each column, in the order it reads them: a name the list already used is refused as the column is added (sqlite3AddColumn), then its DEFAULT and its COLLATE as they are read (sqlite3AddDefaultValue; sqlite3AddCollateType via sqlite3LocateCollSeq) and its REFERENCES ({!check_width}), before any later column or table constraint. Names compare as identifiers, so [x] and [X] are one column. *) (* A column whose name one of [seen] already declares is refused under the name it spells, as the column is added (sqlite3AddColumn). *) let check_name seen (c : Ast.column_def) = if List.exists (Catalog.Ident.equal c.name) seen then Catalog.Error.fail_prepare "duplicate column name: %s" c.name (* sqlite3CreateForeignKey's rule on a key's width, ahead of resolving its child columns (sqlite/src/build.c): a column's REFERENCES names one parent column, and a table's FOREIGN KEY as many as it has child columns. A key naming none is the parent's primary key, whose width is the parent's to match when the key is used. *) let check_width (fk : Ast.foreign_key) = match (fk.clause, fk.cols, fk.parent_cols) with | _, _, [] | Column_constraint _, _, [ _ ] -> () | Column_constraint parent, cols, _ :: _ :: _ -> Catalog.Error.fail_prepare "foreign key on %s should reference only one column of table %s" (String.concat ", " cols) parent | Table_constraint, cols, pcols -> if List.compare_lengths pcols cols <> 0 then Catalog.Error.fail_prepare "number of columns in foreign key does not match the number of \ columns in the referenced table" let check_names (ct : Ast.create_table) = ignore (List.fold_left (fun seen (c : Ast.column_def) -> check_name seen c; c.name :: seen) [] ct.columns : string list) let check_columns (ct : Ast.create_table) = (* each column's REFERENCES, in the order of the columns that declare them, matched as its column is read *) let references = List.filter (fun (fk : Ast.foreign_key) -> match fk.clause with | Column_constraint _ -> true | Table_constraint -> false) ct.foreign_keys in ignore (List.fold_left (fun (seen, references) (c : Ast.column_def) -> check_name seen c; (match Catalog.Ident.assoc_opt c.name ct.defaults with | Some (d : Ast.column_default) when not (constant_default d.expr) -> Catalog.Error.fail_prepare "default value of column [%s] is not constant" c.name | Some _ | None -> ()); Option.iter (fun name -> ignore (Collate.resolve name : Collation.t)) c.collation; let references = match references with | (fk : Ast.foreign_key) :: rest when List.exists (Catalog.Ident.equal c.name) fk.cols -> check_width fk; rest | references -> references in (c.name :: seen, references)) ([], references) ct.columns : string list * Ast.foreign_key list) (* Whether the table computes column [name] rather than storing it. *) let is_generated (ct : Ast.create_table) name = List.exists (fun (g, _) -> Ast.ident_equal g name) ct.generated (* The two rules sqlite3 decides while parsing the column they are declared on (sqlite3AddDefaultValue and sqlite3AddPrimaryKey, sqlite/src/build.c), which is why they are raised ahead of everything below: a generated column is computed from the row it is written with, which leaves it nothing to default to and nothing settled enough to be keyed by. *) let check_generated_column (ct : Ast.create_table) = List.iter (fun (col, _) -> if is_generated ct col then Catalog.Error.fail_prepare "cannot use DEFAULT on a generated column") ct.defaults; List.iter (fun col -> if is_generated ct col then Catalog.Error.fail_prepare "generated columns cannot be part of the PRIMARY KEY") (primary_key_columns ct) (* A table constraint's key columns and a foreign key's width and child columns, resolved against the columns this table declares, all decided before the stored expressions. A table with a defect in each is reported for the constraint, where sqlite3 reports the earlier of the two. *) let check_constraint_columns (ct : Ast.create_table) ~declares = List.iter (fun c -> if not (declares c) then Catalog.Error.fail_prepare "no such column: %s" c) (List.concat_map (function | Ast.Unique (cs, _) | Ast.Primary_key (cs, _) -> Ast.indexed_column_names cs | Ast.Other -> []) ct.table_constraints); List.iter (fun (fk : Ast.foreign_key) -> check_width fk; List.iter (fun c -> if not (declares c) then Catalog.Error.fail_prepare "unknown column %S in foreign key definition" c) fk.cols) ct.foreign_keys (* A generated column is computed from the row it is written with, so a table declaring nothing else has no row to compute one from and is refused. Asked ahead of the stored expressions, which is what a DROP COLUMN leaving only generated columns reads. *) let check_non_generated_column (ct : Ast.create_table) = match ct.generated with | [] -> () | _ :: _ -> if List.for_all (fun (c : Ast.column_def) -> is_generated ct c.name) ct.columns then Catalog.Error.fail_prepare "must have at least one non-generated column" (* A CHECK constraint and a generation expression are both stored and re-evaluated against one row, so each is narrowed to what one row answers ({!Self_ref}). sqlite3 resolves them at the end of the table (sqlite3ResolveSelfReference from sqlite3EndTable), after every rule above. *) let check_stored_exprs (ct : Ast.create_table) ~cols = let table = ct.tbl_name in let rowid = not ct.ct_without_rowid in List.iter (fun (c : Ast.check_constraint) -> Self_ref.check Check_constraint ~rowid ~table ~cols c.expr) ct.checks; List.iter (fun (_, (g : Ast.generated_column)) -> Self_ref.check Generated_column ~rowid ~table ~cols g.expr) ct.generated (* Everything a CREATE TABLE can say that sqlite3 refuses to hold in a schema, in the order it raises them. Asked twice of every table: of the creating statement, and of the text read back out of sqlite_master. The generation cycle is not here; it belongs to CREATE TABLE alone ({!Self_ref.check_generated_loop}). *) let check (ct : Ast.create_table) = let cols = List.map (fun (c : Ast.column_def) -> c.name) ct.columns in let declares c = List.exists (Ast.ident_equal c) cols in check_generated_column ct; check_constraint_columns ct ~declares; check_non_generated_column ct; check_stored_exprs ct ~cols (* The two halves of reading a stored CREATE TABLE as one answer: the text declares this table, or it does not and this is why. The reason comes back rather than the sentence, each caller wording its own refusal. *) let checked sql = match Lexer.parse sql with | Error reason -> Error reason | Ok ct -> ( match check ct with | () -> Ok ct | exception Catalog.Error (Prepare reason | Runtime reason) -> Error reason)