(*--------------------------------------------------------------------------- Copyright (c) 2026 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) module Spi = Catalog.Spi module Ident = Catalog.Ident let fail_prepare = Catalog.Error.fail_prepare let fail_runtime = Catalog.Error.fail_runtime (* sqlite3's own tables, and the names they take (alter.c, isAlterableTable; build.c, sqlite3CheckObjectName). *) let reserved name = String.length name >= 7 && String.equal (String.lowercase_ascii (String.sub name 0 7)) "sqlite_" let check_alterable name = if reserved name then fail_prepare "table %s may not be altered" name let check ~held (op : Ast.alter_op) kind name = match (op, kind) with | Rename_table into, _ -> if held into then fail_prepare "there is already another table or index with this name: %s" into; check_alterable name; if reserved into then fail_prepare "object name reserved for internal use: %s" into; if kind = `View then fail_prepare "view %s may not be altered" name | Add_column _, `View -> fail_prepare "Cannot add a column to a view" | Drop_column _, `View -> fail_prepare "cannot drop column from view \"%s\"" name | Rename_column _, `View -> fail_prepare "cannot rename columns of view \"%s\"" name | (Add_column _ | Drop_column _ | Rename_column _), `Table -> check_alterable name (* {1 The schema re-test} *) (* sqlite3 resolves every view's query and every trigger's program against the schema before an edit and again after it (alter.c, renameTestSchema), and the first that does not resolve refuses the ALTER, named with [stage]: [""] before the edit, [" after drop column"] or [" after rename"] after it. The re-test parses each text as on an open, which qualifies every table a text names with its schema, so a table no relation holds is reported as [main.t]. *) let retest env ~stage defs = let env = { env with Resolve.holds = (fun name -> env.Resolve.holds name || fail_prepare "no such table: main.%s" name); } in let resolve kind name f = match f () with | () -> () | exception Catalog.Error (Prepare reason | Runtime reason) -> fail_runtime "error in %s %s%s: %s" kind name stage reason in List.iter (fun (d : Spi.Definition.t) -> match (d.kind, d.sql) with | `View, Some sql -> Option.iter (fun (cv : Ast.create_view) -> resolve "view" d.name (fun () -> Resolve.check_statement env (Select cv.select))) (View.of_sql sql) | `Trigger, Some sql -> Option.iter (fun tg -> resolve "trigger" d.name (fun () -> Resolve.check_schema_trigger env tg)) (Trigger.of_sql sql) | _ -> ()) defs (* [env] with the columns of [table] as an ALTER leaves them. *) let with_columns env ~table columns = { env with Resolve.columns = (fun name -> if Ident.equal name table then columns else env.Resolve.columns name); } (* {1 ADD COLUMN} *) (* The refusals of an added column that is not generated, over a table with rows, [if_rows] raising only there. A DEFAULT of NULL is no default. *) let check_added_plain_column ~foreign_keys ~if_rows (c : Ast.column_decl) = let default = match c.col_default with | Some { expr = Lit Null; _ } | None -> None | Some d -> Some d.expr in if foreign_keys && Option.is_some c.col_foreign_key && default <> None then if_rows "Cannot add a REFERENCES column with non-NULL default value"; if Option.is_some c.def.not_null && default = None then if_rows "Cannot add a NOT NULL column with default value NULL"; (* The command leaves every existing row short and reading the clause back, so the clause has to settle from its text, as sqlite3AlterFinishAddColumn asks sqlite3ValueFromExpr under BLOB affinity. *) match default with | Some e when Table.settle `Blob e = None -> if_rows "Cannot add a column with non-constant default" | Some _ | None -> () (* What sqlite3AlterFinishAddColumn refuses of the declaration [c] before it touches the schema: a PRIMARY KEY, a UNIQUE or a name the rowid answers to whatever the table holds, and, over a table with rows, what an existing row would break. *) let check_added_column ~has_rowid ~foreign_keys ~has_rows (c : Ast.column_decl) = if Option.is_some c.def.primary_key then fail_prepare "Cannot add a PRIMARY KEY column"; if Option.is_some c.def.unique then fail_prepare "Cannot add a UNIQUE column"; if has_rowid && Ast.is_rowid_name c.def.name then fail_prepare "cannot add rowid alias: %s" c.def.name; let has_rows = lazy (has_rows ()) in let if_rows msg = if Lazy.force has_rows then fail_runtime "%s" msg in match c.col_generated with | None -> check_added_plain_column ~foreign_keys ~if_rows c | Some { kind = Stored; _ } -> if_rows "cannot add a STORED column" | Some { kind = Virtual; _ } -> () (* ADD COLUMN splices the declaration, as written, into the stored CREATE TABLE, which then declares the column as it would have had the table been created with it. *) let add_column ~table ~columns ~has_rowid ~foreign_keys ~has_rows ~sql decl (c : Ast.column_decl) = let name = c.def.name in if List.exists (Ident.equal name) columns then fail_prepare "duplicate column name: %s" name; (* sqlite3AddDefaultValue's rule, about the clause and not the rows: a stored DEFAULT naming a column is a schema sqlite3 declines to open. *) (match c.col_default with | Some d when not (Create_table.constant_default d.expr) -> fail_prepare "default value of column [%s] is not constant" name | Some _ | None -> ()); Option.iter Create_table.check_width c.col_foreign_key; let new_sql = Alter_text.add_column sql decl in let ct = match Lexer.parse new_sql with | Ok ct -> ct | Error reason -> fail_runtime "error in table %s after add column: %s" table reason in Create_table.check_generated_column ct; check_added_column ~has_rowid ~foreign_keys ~has_rows c; (match Create_table.checked new_sql with | Ok _ -> () | Error reason -> fail_runtime "error in table %s after add column: %s" table reason); (new_sql, ct) (* Once the table is read back, sqlite3 asks [PRAGMA quick_check] of it where a constraint could refuse a row the new column leaves as it was: a CHECK, a generated NOT NULL column, or a STRICT type. The first such finding is the refusal, in the words of the RAISE(ABORT) that sqlite3AlterFinishAddColumn runs. *) let check_added_rows (ct : Ast.create_table) (c : Ast.column_decl) report = let needs_check = ct.checks <> [] || (Option.is_some c.def.not_null && Option.is_some c.col_generated) || ct.ct_strict in if needs_check then let starts_with prefix s = String.starts_with ~prefix s in let contains sub s = let n = String.length sub and m = String.length s in let rec at i = i + n <= m && (String.sub s i n = sub || at (i + 1)) in at 0 in let type_mismatch s = starts_with "non-" s && contains " value in" s in match List.find_opt (fun s -> starts_with "CHECK" s || starts_with "NULL" s || type_mismatch s) (report ()) with | None -> () | Some s when starts_with "CHECK" s -> fail_runtime "CHECK constraint failed" | Some s when type_mismatch s -> fail_runtime "type mismatch on DEFAULT" | Some _ -> fail_runtime "NOT NULL constraint failed" (* {1 DROP COLUMN} *) (* The constraint a column declares that no DROP COLUMN may drop it for, or [None]. sqlite3 keeps the two as flags and reports whichever is set, PRIMARY KEY first: PRIMARY KEY however declared, and so the rowid alias with it, but UNIQUE only where the column itself declares it. *) let dropped_column_constraint (ct : Ast.create_table) column = if List.exists (Ident.equal column) (Create_table.primary_key_columns ct) then Some "PRIMARY KEY" else if List.exists (fun (c : Ast.column_def) -> Ident.equal c.name column && c.unique <> None) ct.columns then Some "UNIQUE" else None (* Does the index [ci] read [column]? It keys on it, or an expression it stores names it: sqlite3 resolves each stored expression again against the columns [left] and refuses the ALTER where one no longer resolves. *) let index_reads ~table ~has_rowid ~left column (ci : Ast.create_index) = let unresolvable context e = match Self_ref.check context ~rowid:has_rowid ~table ~cols:left e with | () -> false | exception Catalog.Error (Prepare _ | Runtime _) -> true in List.exists (function | Ast.Column k -> Ident.equal k.column column | Ast.Expression { expr; _ } -> unresolvable Index_expression expr) ci.keys || Option.fold ~none:false ~some:(unresolvable Partial_index) ci.where let drop_column ~table ~has_rowid ~sql ~indexes ~env ~defs (ct : Ast.create_table) column = let names = List.map (fun (c : Ast.column_def) -> c.name) ct.columns in let pos = match List.find_index (Ident.equal column) names with | Some i -> i | None -> fail_prepare "no such column: \"%s\"" column in (* Asked before the count, as sqlite3 asks it: a table whose one column is its PRIMARY KEY is refused for the key, not for having nothing left. *) (match dropped_column_constraint ct column with | Some declared -> fail_prepare "cannot drop %s column: \"%s\"" declared column | None -> ()); if List.length names <= 1 then fail_prepare "cannot drop column \"%s\": no other columns exist" column; (* Past the three questions about the column, the schema re-test: sqlite3 re-parses every row as it is, then rebuilds the schema without the column and re-parses every row again, reporting the first object that no longer resolves. The table's own row comes first, then its indexes. *) retest env ~stage:"" defs; let dropped = Alter_text.drop_column sql ~column in (match Create_table.checked dropped with | Ok _ -> () | Error reason -> fail_runtime "error in table %s after drop column: %s" table reason); let left = List.filteri (fun i _ -> i <> pos) names in (match List.find_opt (fun (_, ci) -> index_reads ~table ~has_rowid ~left column ci) indexes with | Some (name, _) -> fail_runtime "error in index %s after drop column: no such column: %s" name column | None -> ()); retest (with_columns env ~table left) ~stage:" after drop column" defs; (pos, dropped) (* {1 RENAME COLUMN} *) let renamed_table ~table ~sql ~from_ ~to_ = let renamed = Alter_text.rename_column sql ~table ~from_ ~to_ in (* read back as on an open, where a name declared twice is refused too *) let reread = match Create_table.checked renamed with | Error reason -> Error reason | Ok ct -> ( match Create_table.check_names ct with | () -> Ok () | exception Catalog.Error (Prepare reason | Runtime reason) -> Error reason) in match reread with | Ok () -> renamed | Error reason -> fail_runtime "error in table %s after rename: %s" table reason let renamed_views_and_triggers ~table ~from_ ~to_ defs = let renamed (d : Spi.Definition.t) = match (d.kind, d.sql) with | ((`View | `Trigger) as kind), Some sql -> let rename = if kind = `Trigger then Alter_text.rename_column_in_trigger else Alter_text.rename_column_in_view in (d, rename sql ~table ~from_ ~to_) | _ -> (d, Alter_text.Untouched) in let outcomes = List.map renamed defs in List.iter (fun ((d : Spi.Definition.t), outcome) -> if outcome = Alter_text.Unresolved then fail_runtime "error in %s %s after rename: cannot tell which table column %s \ belongs to" (if d.kind = `Trigger then "trigger" else "view") d.name from_) outcomes; List.filter_map (fun ((d : Spi.Definition.t), outcome) -> match outcome with | Alter_text.Rewritten sql -> Some (Spi.Definition.v d.kind ~name:d.name ~table:d.table (Some sql)) | Untouched | Unresolved -> None) outcomes (* [defs] with each of [renamed] in place of the definition it rewrites. *) let replaced defs renamed = List.map (fun (d : Spi.Definition.t) -> Option.value ~default:d (List.find_opt (fun (r : Spi.Definition.t) -> r.kind = d.kind && Ident.equal r.name d.name) renamed)) defs let rename_column ~table ~has_rowid ~sql ~env ~defs (ct : Ast.create_table) ~from_ ~to_ = let names = List.map (fun (c : Ast.column_def) -> c.name) ct.columns in if not (List.exists (Ident.equal from_) names) then fail_prepare "no such column: \"%s\"" from_; if has_rowid && Ast.is_rowid_name to_ then fail_prepare "cannot rename to rowid alias: %s" to_; retest env ~stage:"" defs; let sql = renamed_table ~table ~sql ~from_ ~to_ in let renamed = renamed_views_and_triggers ~table ~from_ ~to_ defs in let columns = List.map (fun n -> if Ident.equal n from_ then to_ else n) names in retest (with_columns env ~table columns) ~stage:" after rename" (replaced defs renamed); (sql, renamed) (* {1 Over a catalog} *) (* The table an ALTER changes, as its store keeps it: its schema, its CREATE TABLE text and the parse of that text. *) type table = { schema : Spi.Schema.t; sql : string; ct : Ast.create_table } let name t = t.schema.table let has_rowid t = not t.schema.without_rowid let text cat kind name = List.find_map (fun (_, (d : Spi.Definition.t)) -> if Spi.Definition.is d kind name then d.sql else None) (Spi.definitions cat) let parse_table name sql = match Lexer.parse sql with | Ok ct -> ct | Error reason -> Catalog.Error.fail (Corrupt_schema { name; reason }) let table cat (schema : Spi.Schema.t) = match text cat `Table schema.table with | Some sql -> { schema; sql; ct = parse_table schema.table sql } | None -> Catalog.Error.fail_unsupported "ALTER TABLE %s: its store keeps no CREATE TABLE text" schema.table (* The relation [name] names: a table of the catalog or a schema table, which sqlite3 finds and then refuses to alter, or a view. *) let locate cat name = if Schema_table.is_name name then `Table (Schema_table.name name) else match Spi.schema cat name with | Some s when List.exists (Ident.equal name) (Spi.tables cat) -> `Schema s | Some _ | None -> ( match View.find cat name with | Some cv -> `View cv.Ast.name | None -> fail_prepare "no such table: %s" name) (* The table's indexes created by a statement, each with its text. *) let created_indexes cat t = List.filter_map (fun (_, (d : Spi.Definition.t)) -> match (d.kind, d.sql) with | `Index, Some sql when Ident.equal d.table (name t) -> Some (d.name, sql) | _ -> None) (Spi.definitions cat) let parse_index name sql = match Lexer.parse_statements sql with | Ok [ Ast.Create_index ci ] -> ci | Ok _ | Error _ -> Catalog.Error.fail (Corrupt_schema { name; reason = "not a CREATE INDEX statement" }) let schema_of ~sql ~indexes ct = Engine.table_schema ~source:sql ~indexes ct let exec_add_column conn t ~source ~start ~stop c = let cat = Connection.catalog conn in let sql, ct = add_column ~table:(name t) ~columns:(Spi.Schema.column_names t.schema) ~has_rowid:(has_rowid t) ~foreign_keys:(Connection.foreign_keys conn) ~has_rows:(fun () -> Spi.rows_rowid cat (name t) <> []) ~sql:t.sql (String.sub source start (stop - start)) c in let schema = schema_of ~sql ~indexes:t.schema.indexes ct in (* What a row older than the column reads: its DEFAULT settled under its affinity, or NULL; a VIRTUAL column, which the store holds as a write computed it, computed from the row. *) let tbl = Table.v schema in let older = match (c.col_generated, c.col_default) with | Some _, _ -> fun r -> let row = Table.generate tbl (r @ [ Catalog.Value.Null ]) in r @ [ List.nth row (List.length r) ] | None, Some d -> let storage = List.nth (Table.storage tbl) (List.length ct.columns - 1) in let v = Option.value ~default:Catalog.Value.Null (Table.settle (Table.affinity storage) d.expr) in fun r -> r @ [ v ] | None, None -> fun r -> r @ [ Catalog.Value.Null ] in Spi.alter_table cat (name t) ~sql ~rows:older schema; check_added_rows ct c (fun () -> Integrity.check cat ~budget:Integrity.error_max (Some (name t))) let definitions cat = List.map snd (Spi.definitions cat) let exec_drop_column conn t column = let cat = Connection.catalog conn in let indexes = List.map (fun (n, sql) -> (n, parse_index n sql)) (created_indexes cat t) in let pos, sql = drop_column ~table:(name t) ~has_rowid:(has_rowid t) ~sql:t.sql ~indexes ~env:(Query.resolve_env (Engine.catalog conn)) ~defs:(definitions cat) t.ct column in Spi.alter_table cat (name t) ~sql ~rows:(List.filteri (fun i _ -> i <> pos)) (schema_of ~sql ~indexes:t.schema.indexes (parse_table (name t) sql)) (* Every table other than [except] whose text [f] changes, with its new text. Another table names one only as the parent of a foreign key. *) let other_tables_retexted defs ~except f = List.filter_map (fun (_, (d : Spi.Definition.t)) -> match (d.kind, d.sql) with | `Table, Some text when not (Ident.equal d.name except) -> let sql = f text in if String.equal sql text then None else Some (d.name, sql) | _ -> None) defs (* Table [name] given the text [sql], its rows and indexes kept. *) let retext_table cat (name, sql) = Option.iter (fun (s : Spi.Schema.t) -> Spi.alter_table cat name ~sql ~rows:Fun.id (schema_of ~sql ~indexes:s.indexes (parse_table name sql))) (Spi.schema cat name) (* Every text that reads the column is renamed before anything is written, so a refusal leaves the schema as it was: the table's own, its indexes', the views and triggers that read it, and the parent list of every other table's foreign key on it (renameColumnFunc). *) let exec_rename_column conn t ~from_ ~to_ = let cat = Connection.catalog conn in let defs = Spi.definitions cat in let sql, others = rename_column ~table:(name t) ~has_rowid:(has_rowid t) ~sql:t.sql ~env:(Query.resolve_env (Engine.catalog conn)) ~defs:(List.map snd defs) t.ct ~from_ ~to_ in let indexes = List.map (fun (n, sql) -> let sql = Alter_text.rename_column_in_index sql ~from_ ~to_ in (n, sql, parse_index n sql)) (created_indexes cat t) in let children = other_tables_retexted defs ~except:(name t) (fun sql -> Alter_text.rename_parent_column sql ~parent:(name t) ~from_ ~to_) in let schema_index (i : Spi.Schema.index) = match List.find_opt (fun (n, _, _) -> Ident.equal n i.name) indexes with | Some (_, _, ci) -> Engine.index_schema ci | None -> i in Spi.alter_table cat (name t) ~sql ~rows:Fun.id (schema_of ~sql ~indexes:(List.map schema_index t.schema.indexes) (parse_table (name t) sql)); List.iter (fun (n, sql, _) -> Spi.redefine cat (Spi.Definition.v `Index ~name:n ~table:(name t) (Some sql))) indexes; List.iter (Spi.redefine cat) others; List.iter (retext_table cat) children (* A table's counter follows its name (alter.c: UPDATE sqlite_sequence SET name = new WHERE name = old). *) let rename_counter cat ~from ~into = if List.exists (Ident.equal Autoinc.table) (Spi.tables cat) then List.iter (fun ((_, row) as r) -> match row with | Catalog.Value.Text n :: rest when String.equal n from -> Spi.update cat Autoinc.table ~row:r (Catalog.Value.Text into :: rest) | _ -> ()) (Spi.rows_rowid cat Autoinc.table) (* Every stored statement that names the table is rewritten, as sqlite3 runs sqlite_rename_table over every row of sqlite_master but the indexes of other tables (sqlite3AlterRenameTable): the table's own text and its indexes', every view and trigger, and every other table whose foreign keys name it as their parent. *) let exec_rename_table cat t into = let from = name t in let renamed sql = Alter_text.rename_table sql ~from_:from ~to_:into in let defs = Spi.definitions cat in let others = other_tables_retexted defs ~except:from renamed in let sql = renamed t.sql in Spi.alter_table cat from ~sql ~rows:Fun.id (schema_of ~sql ~indexes:t.schema.indexes (parse_table into sql)); List.iter (retext_table cat) others; List.iter (fun (_, (d : Spi.Definition.t)) -> match (d.kind, d.sql) with | `Index, Some text when not (Ident.equal d.table from) -> ignore text | (`Index | `View | `Trigger), Some text -> let sql = renamed text in if not (String.equal sql text) then let table = if Ident.equal d.table from then into else d.table in Spi.redefine cat (Spi.Definition.v d.kind ~name:d.name ~table (Some sql)) | _, _ -> ()) defs; rename_counter cat ~from ~into let exec conn ~held ~source (a : Ast.alter_table) = let cat = Connection.catalog conn in let kind, declared = match locate cat a.table with | `Table name -> (`Table, name) | `Schema (s : Spi.Schema.t) -> (`Table, s.table) | `View name -> (`View, name) in check ~held a.op kind declared; let t = match Spi.schema cat declared with | Some s -> table cat s | None -> fail_prepare "no such table: %s" a.table in match a.op with | Add_column { column; start; stop } -> exec_add_column conn t ~source ~start ~stop column | Drop_column column -> exec_drop_column conn t column | Rename_column (from_, to_) -> exec_rename_column conn t ~from_ ~to_ | Rename_table into -> exec_rename_table cat t into