Skip to main content

spg_engine/
ddl.rs

1//! DDL execution — every CREATE / DROP / ALTER for schema objects:
2//! tables and indexes, plus users, functions, triggers, sequences,
3//! views, types, domains, schemas, and materialized views. Lifted out
4//! of `lib.rs` (v7.32 engine modularisation). These `impl Engine`
5//! methods are dispatched from `Engine::execute` (hence pub(crate)) and
6//! drive the catalog / storage schema mutations.
7
8use alloc::string::{String, ToString};
9use alloc::vec::Vec;
10
11use spg_sql::ast::{
12    ColumnDef, CreateIndexStatement, CreateTableStatement, CreateUserStatement, Expr, IndexMethod,
13    Literal, PartitionKindAst, PartitionOfBoundsAst, Statement, VecEncoding as SqlVecEncoding,
14};
15use spg_storage::{
16    ColumnSchema, DataType, ExclusionConstraint, PartitionKind, PartitionRole, RangeKind,
17    StorageError, TableSchema, Value, VecEncoding,
18};
19
20/// v7.39 (round 215) — the column an EXCLUDE constraint's range-overlap index
21/// should key on: the `&&` element sitting on an integer-keyable range column
22/// (int4/int8/date/ts/tstz range — the kinds `range_excl_index_key` reduces to
23/// an `i128`). `None` when no element qualifies (numrange, or a non-`&&`
24/// operator only), in which case the constraint keeps the O(n) enforcement.
25fn excl_index_column(schema: &TableSchema, ex: &ExclusionConstraint) -> Option<usize> {
26    for (pos, op) in &ex.elements {
27        if op == "&&"
28            && let Some(col) = schema.columns.get(*pos)
29            && matches!(
30                col.ty,
31                DataType::Range(
32                    RangeKind::Int4
33                        | RangeKind::Int8
34                        | RangeKind::Date
35                        | RangeKind::Ts
36                        | RangeKind::TsTz
37                )
38            )
39        {
40            return Some(*pos);
41        }
42    }
43    None
44}
45
46/// v7.39 (round 215) — rebuild the range-exclusion indexes for every table in
47/// a freshly-deserialized catalog. The indexes aren't persisted (like BRIN,
48/// they re-derive), so a catalog load must re-emit them from the persisted
49/// exclusion constraints + rows before the first EXCLUDE enforcement runs.
50pub(crate) fn rebuild_all_excl_indexes(cat: &mut spg_storage::Catalog) {
51    for name in cat.table_names() {
52        let Some(table) = cat.get_mut(&name) else {
53            continue;
54        };
55        let cols: Vec<usize> = table
56            .schema()
57            .exclusion_constraints
58            .iter()
59            .filter_map(|ex| excl_index_column(table.schema(), ex))
60            .collect();
61        for c in cols {
62            table.ensure_excl_range_index(c);
63        }
64    }
65}
66
67use crate::{
68    CancelToken, ClockFn, Engine, EngineError, QueryResult, check_existing_unique_violation,
69    coerce_value, column_type_to_data_type, enforce_fk_inserts, eval, infer_column_types,
70    literal_expr_to_value, resolve_foreign_key, rewrite_column_in_source, users,
71};
72
73/// v7.39 (round 475) — the column a `to_tsvector(…)` index key reads.
74///
75/// PG's full-text idiom is `CREATE INDEX … USING gin (to_tsvector('simple',
76/// body))`, and it is the reason a PG schema reaches the expression path at
77/// all. SPG already builds a fulltext GIN over a column for MySQL's
78/// `FULLTEXT KEY`; this recognises the shape so the PG spelling lands on the
79/// same index instead of being refused.
80///
81/// `None` for anything else, including `to_tsvector` over an expression
82/// rather than a bare column — indexing a derived value is a different
83/// build, and guessing at it would be worse than refusing.
84fn tsvector_source_column(e: &spg_sql::ast::Expr) -> Option<String> {
85    let spg_sql::ast::Expr::FunctionCall { name, args } = e else {
86        return None;
87    };
88    if !name.eq_ignore_ascii_case("to_tsvector") {
89        return None;
90    }
91    // `to_tsvector(col)` or `to_tsvector(config, col)` — either way the
92    // column is the last argument.
93    match args.last() {
94        Some(spg_sql::ast::Expr::Column(c)) => Some(c.name.clone()),
95        _ => None,
96    }
97}
98
99/// The first name that appears twice, or `None`.
100///
101/// v7.39.2 — whether case matters is the DIALECT's answer, and the
102/// first version of this got it wrong in a way no refusal pin could
103/// see. Measured:
104///
105/// * PostgreSQL 18.6 accepts `CREATE TABLE t ("a" int, "A" int)` —
106///   quoting preserves case there, so those are two columns. Unquoted
107///   `(a int, A int)` is still one name twice, because the LEXER folded
108///   it long before this sees it. So the comparison here is exact, and
109///   folding it a second time refuses a table PostgreSQL creates.
110/// * MySQL 9.7.2 refuses ``(`a` int, `A` int)`` with
111///   `Duplicate column name 'A'`: its column names never distinguish
112///   case, quoted or not.
113///
114/// The over-rejection was found by an ablation that did NOT bite —
115/// making the comparison case-sensitive left every pin green, which
116/// said the pin named for case was passing for another reason.
117fn first_duplicate<'a>(
118    names: impl Iterator<Item = &'a str>,
119    fold_case: bool,
120) -> Option<alloc::string::String> {
121    let mut seen: alloc::collections::BTreeSet<alloc::string::String> =
122        alloc::collections::BTreeSet::new();
123    for n in names {
124        let key = if fold_case {
125            n.to_ascii_lowercase()
126        } else {
127            alloc::string::String::from(n)
128        };
129        if !seen.insert(key) {
130            // The spelling as WRITTEN, which is what both engines quote
131            // back — MySQL 9.7.2 says `Duplicate column name 'A'` for
132            // the second one.
133            return Some(alloc::string::String::from(n));
134        }
135    }
136    None
137}
138
139/// Each engine's own words for it.
140fn duplicate_column_message(name: &str, mysql: bool) -> alloc::string::String {
141    if mysql {
142        alloc::format!("Duplicate column name '{name}'")
143    } else {
144        alloc::format!("column \"{name}\" specified more than once")
145    }
146}
147
148impl Engine {
149    /// v6.7.2 — `ALTER TABLE t SET hot_tier_bytes = X`. Dispatch
150    /// arm. Currently the only setting is `hot_tier_bytes`; later
151    /// v6.7.x can extend `AlterTableTarget` without touching this
152    /// arm structure.
153    pub(crate) fn exec_alter_table(
154        &mut self,
155        s: spg_sql::ast::AlterTableStatement,
156    ) -> Result<QueryResult, EngineError> {
157        // v7.13.2 — mailrs round-6 S1: apply each subaction in order.
158        // On first error the statement aborts; subactions already
159        // applied stay (no transactional rollback in v7.13 — wrap in
160        // BEGIN/COMMIT if atomicity matters).
161        let table_name = s.name.clone();
162        // v7.39 (round 735, S14/B3) — any table-shape change invalidates
163        // a dependent materialized view's refresh watermark.
164        self.bump_table_change(&table_name);
165        for target in s.targets {
166            self.exec_alter_table_subaction(&table_name, target)?;
167        }
168        // v7.39 (round 215) — (re)build range-exclusion indexes after any
169        // ALTER: ADD EXCLUDE installs a new one; DROP COLUMN cleared them (it
170        // shifts positions), so this restores them from the constraints'
171        // updated column positions. Idempotent for the untouched case.
172        self.install_excl_range_indexes(&table_name);
173        Ok(QueryResult::CommandOk {
174            affected: 0,
175            modified_catalog: self.catalog_change_is_committed(),
176        })
177    }
178
179    pub(crate) fn exec_alter_table_subaction(
180        &mut self,
181        table_name_outer: &str,
182        target: spg_sql::ast::AlterTableTarget,
183    ) -> Result<(), EngineError> {
184        use spg_sql::ast::AlterTableTarget as T;
185        let tbl = table_name_outer;
186        match target {
187            // v7.39 (round 647) — attach or detach an inheritance child.
188            // Accepted-and-ignored since v7.37.18, whose reasoning ("SPG
189            // doesn't support PG-style inheritance") round 645 made
190            // false. `NO INHERIT` reporting success while the child
191            // stayed attached is the worst shape a statement can have.
192            T::Inherit { parent, detach } => self.alter_inherit(tbl, &parent, detach),
193            T::SetHotTierBytes(n) => self.alter_set_hot_tier_bytes(tbl, n),
194            T::AddForeignKey(fk) => self.alter_add_foreign_key(tbl, fk),
195            T::DropForeignKey { name, if_exists } => {
196                self.alter_drop_foreign_key(tbl, name, if_exists)
197            }
198            // v7.39 (round 431) — `ALTER TABLE t DROP {INDEX|KEY} name`
199            // shares the standalone DROP INDEX path, so the two spellings
200            // cannot diverge on the not-found / IF EXISTS behaviour.
201            // v7.39.7 — and the table is the one ALTER named, so this
202            // spelling scopes the same way MySQL's own `DROP INDEX i ON
203            // t` does.
204            T::DropIndex { name, if_exists } => self
205                .exec_drop_index(name, if_exists, Some(tbl.to_string()))
206                .map(|_| ()),
207            T::AddColumn {
208                column,
209                if_not_exists,
210                position,
211            } => self.alter_add_column(tbl, column, if_not_exists, position),
212            // v7.39.9 — MySQL's own ALTER TABLE vocabulary.
213            T::ModifyColumn {
214                column,
215                rename_to,
216                definition,
217                position,
218            } => self.alter_modify_column(tbl, column, rename_to, definition, position),
219            T::RenameIndex { old, new } => self.alter_rename_index(tbl, &old, &new),
220            T::SetTableAutoIncrement(n) => self.alter_set_table_auto_increment(tbl, n),
221            T::SetEngine(name) => Self::alter_set_engine(&name),
222            T::ConvertToCharacterSet { charset, collate } => {
223                Self::alter_convert_charset(&charset, collate.as_deref())
224            }
225            T::AlterColumnType {
226                column,
227                new_type,
228                using,
229                collation,
230            } => self.alter_column_type(tbl, column, new_type, using, collation),
231            T::AddTableConstraint(tc) => self.alter_add_table_constraint(tbl, tc),
232            T::ValidateConstraint { name } => self.alter_validate_constraint(tbl, &name),
233            // v7.39 (round 652) — SPG is single-owner and has no
234            // clustered storage, so both of these remain no-ops once the
235            // name checks out. What was missing was the check.
236            T::OwnerTo { role } => {
237                if self.role_exists(&role) {
238                    Ok(())
239                } else {
240                    Err(EngineError::Unsupported(alloc::format!(
241                        "role \"{role}\" does not exist"
242                    )))
243                }
244            }
245            // v7.39 (round 710) — same shape as OwnerTo/ClusterOn above:
246            // the ACTION no-ops, the NAME check is what was missing.
247            T::OfType { type_name } => {
248                let cat = self.active_catalog();
249                if cat.enum_types().contains_key(&type_name)
250                    || cat.domain_types().contains_key(&type_name)
251                    || cat.composite_types().contains_key(&type_name)
252                {
253                    Ok(())
254                } else {
255                    Err(EngineError::Unsupported(alloc::format!(
256                        "type \"{type_name}\" does not exist"
257                    )))
258                }
259            }
260            T::ReplicaIdentityUsingIndex { index } => {
261                let table = self.active_catalog().get(tbl).ok_or_else(|| {
262                    EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
263                })?;
264                if table
265                    .indices()
266                    .iter()
267                    .any(|i| i.name.eq_ignore_ascii_case(&index))
268                {
269                    Ok(())
270                } else {
271                    Err(EngineError::Unsupported(alloc::format!(
272                        "index \"{index}\" for table \"{tbl}\" does not exist"
273                    )))
274                }
275            }
276            T::ClusterOn { index } => {
277                let Some(index) = index else { return Ok(()) };
278                let table = self.active_catalog().get(tbl).ok_or_else(|| {
279                    EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
280                })?;
281                if table
282                    .indices()
283                    .iter()
284                    .any(|i| i.name.eq_ignore_ascii_case(&index))
285                {
286                    Ok(())
287                } else {
288                    Err(EngineError::Unsupported(alloc::format!(
289                        "index \"{index}\" for table \"{tbl}\" does not exist"
290                    )))
291                }
292            }
293            T::DropColumn {
294                column,
295                if_exists,
296                cascade,
297            } => self.alter_drop_column(tbl, column, if_exists, cascade),
298            T::SetTriggerEnabled { which, enabled } => {
299                self.alter_set_trigger_enabled(tbl, which, enabled)
300            }
301            T::SetColumnAutoIncrement { column, seq_name } => {
302                self.alter_set_column_auto_increment(tbl, column, seq_name)
303            }
304            T::RenameTable { new } => self.alter_rename_table(tbl, new),
305            T::RenameColumn { old, new } => self.alter_rename_column(tbl, old, new),
306            T::RenameConstraint { old, new } => self.alter_rename_constraint(tbl, &old, new),
307            T::AttachPartition { child, bounds } => self.alter_attach_partition(tbl, child, bounds),
308            T::DetachPartition {
309                child,
310                concurrently,
311                finalize,
312            } => self.alter_detach_partition(tbl, child, concurrently, finalize),
313            T::AlterColumnSetDefault {
314                column,
315                default_expr,
316            } => self.alter_column_set_default(tbl, column, default_expr),
317            T::AlterColumnDropDefault { column } => self.alter_column_drop_default(tbl, column),
318            T::AlterColumnSetNotNull { column } => self.alter_column_set_not_null(tbl, column),
319            T::AlterColumnDropNotNull { column } => self.alter_column_drop_not_null(tbl, column),
320            // v7.39 (round 220) — RESTART [WITH n]: record the next-value
321            // floor on the identity column (max+1 alloc takes the max).
322            T::AlterColumnRestart { column, with } => {
323                let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
324                    EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
325                })?;
326                let Some(col) = table
327                    .schema_mut()
328                    .columns
329                    .iter_mut()
330                    .find(|c| c.name.eq_ignore_ascii_case(&column))
331                else {
332                    return Err(EngineError::Unsupported(alloc::format!(
333                        "column \"{column}\" of relation \"{tbl}\" does not exist"
334                    )));
335                };
336                col.auto_restart = Some(with.unwrap_or(1));
337                Ok(())
338            }
339            T::AlterColumnDropExpression { column, if_exists } => {
340                self.alter_column_drop_expression(tbl, column, if_exists)
341            }
342            T::AlterColumnDropIdentity { column, if_exists } => {
343                self.alter_column_drop_identity(tbl, column, if_exists)
344            }
345            T::AlterColumnSetExpression { column, expr } => {
346                self.alter_column_set_expression(tbl, column, expr)
347            }
348            T::SetRowSecurity { enabled, force } => {
349                self.alter_set_row_security(tbl, enabled, force)
350            }
351        }
352    }
353
354    /// v7.39 (RLS) — `ALTER TABLE t { ENABLE|DISABLE|FORCE|NO FORCE } ROW LEVEL
355    /// SECURITY`. Sets the schema flags (`relrowsecurity` / `relforcerowsecurity`
356    /// mirrors). Enforcement is gated on the session role (Phase 1); Phase 0
357    /// only records the flags for catalog / pg_dump fidelity.
358    fn alter_set_row_security(
359        &mut self,
360        tbl: &str,
361        enabled: Option<bool>,
362        force: Option<bool>,
363    ) -> Result<(), EngineError> {
364        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
365            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
366        })?;
367        if let Some(e) = enabled {
368            table.schema_mut().row_security = e;
369        }
370        if let Some(fo) = force {
371            table.schema_mut().force_row_security = fo;
372        }
373        Ok(())
374    }
375
376    /// v7.38 (read01 U12) — `ALTER COLUMN col SET EXPRESSION AS (expr)`
377    /// (PG 17): swap a stored generated column's expression and recompute
378    /// every existing row against the new expression.
379    fn alter_column_set_expression(
380        &mut self,
381        tbl: &str,
382        column: String,
383        expr: spg_sql::ast::Expr,
384    ) -> Result<(), EngineError> {
385        let expr_str = alloc::format!("{expr}");
386        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
387            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
388        })?;
389        let pos = table
390            .schema()
391            .columns
392            .iter()
393            .position(|c| c.name.eq_ignore_ascii_case(&column))
394            .ok_or_else(|| {
395                EngineError::Unsupported(alloc::format!(
396                    "ALTER COLUMN SET EXPRESSION: column {column:?} not in table {tbl:?}"
397                ))
398            })?;
399        if table.schema().columns[pos].generated_stored_expr.is_none() {
400            return Err(EngineError::Unsupported(alloc::format!(
401                "ALTER COLUMN SET EXPRESSION: column {column:?} is not a stored generated column"
402            )));
403        }
404        table.schema_mut().columns[pos].generated_stored_expr = Some(expr_str);
405        // Recompute existing rows against the new expression.
406        let schema_cols = table.schema().columns.clone();
407        let col_ty = schema_cols[pos].ty;
408        let ctx = crate::eval::EvalContext::new(&schema_cols, None);
409        let mut new_values: Vec<Value<'static>> = Vec::with_capacity(table.rows().len());
410        for row in table.rows().iter() {
411            let v = eval::eval_expr(&expr, row, &ctx).map_err(|e| {
412                EngineError::Unsupported(alloc::format!(
413                    "ALTER COLUMN SET EXPRESSION: recompute failed: {e:?}"
414                ))
415            })?;
416            new_values.push(coerce_value(v, col_ty, &column, pos)?);
417        }
418        for (i, v) in new_values.into_iter().enumerate() {
419            let mut row_values = table
420                .rows()
421                .get(i)
422                .expect("bounds-checked by the loop above")
423                .values
424                .clone();
425            row_values[pos] = v;
426            table.update_row(i, row_values)?;
427        }
428        Ok(())
429    }
430
431    /// v7.38 (read01 U10) — `ALTER COLUMN col DROP EXPRESSION` converts a
432    /// stored generated column to a plain column: clear the generation
433    /// expression so future INSERT/UPDATE accept a supplied value instead
434    /// of recomputing it. Existing stored values are left as-is.
435    fn alter_column_drop_expression(
436        &mut self,
437        tbl: &str,
438        column: String,
439        if_exists: bool,
440    ) -> Result<(), EngineError> {
441        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
442            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
443        })?;
444        let pos = table
445            .schema()
446            .columns
447            .iter()
448            .position(|c| c.name.eq_ignore_ascii_case(&column))
449            .ok_or_else(|| {
450                EngineError::Unsupported(alloc::format!(
451                    "ALTER COLUMN DROP EXPRESSION: column {column:?} not in table {tbl:?}"
452                ))
453            })?;
454        if table.schema().columns[pos].generated_stored_expr.is_none() {
455            // v7.39 (round 187, U10) — PG's wordings, live-verified
456            // 2026-07-18: plain form errors, IF EXISTS raises a NOTICE
457            // and skips (`ALTER TABLE` still succeeds — pg_dump
458            // restore scripts rely on that).
459            if if_exists {
460                self.notice(alloc::format!(
461                    "column \"{column}\" of relation \"{tbl}\" is not a generated column, skipping"
462                ));
463                return Ok(());
464            }
465            return Err(EngineError::Unsupported(alloc::format!(
466                "column \"{column}\" of relation \"{tbl}\" is not a generated column"
467            )));
468        }
469        table.schema_mut().columns[pos].generated_stored_expr = None;
470        Ok(())
471    }
472
473    /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
474    /// de-generate an identity column into a plain column. Errors when the
475    /// column is not an identity column, unless `IF EXISTS` was given.
476    fn alter_column_drop_identity(
477        &mut self,
478        tbl: &str,
479        column: String,
480        if_exists: bool,
481    ) -> Result<(), EngineError> {
482        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
483            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
484        })?;
485        let pos = table
486            .schema()
487            .columns
488            .iter()
489            .position(|c| c.name.eq_ignore_ascii_case(&column))
490            .ok_or_else(|| {
491                EngineError::Unsupported(alloc::format!(
492                    "ALTER COLUMN DROP IDENTITY: column {column:?} not in table {tbl:?}"
493                ))
494            })?;
495        if !table.schema().columns[pos].auto_increment {
496            if if_exists {
497                return Ok(());
498            }
499            // PG18.4: `column "a" of relation "t3" is not an identity column`.
500            return Err(EngineError::Unsupported(alloc::format!(
501                "column {column:?} of relation {tbl:?} is not an identity column"
502            )));
503        }
504        table.schema_mut().columns[pos].auto_increment = false;
505        // v7.38 (read01) — a dropped identity is a plain column: clear the
506        // ALWAYS marker too so explicit INSERT values are accepted again.
507        table.schema_mut().columns[pos].identity_always = false;
508        Ok(())
509    }
510
511    /// v7.37.18 (18.1) — set / drop column default.
512    fn alter_column_set_default(
513        &mut self,
514        tbl: &str,
515        column: String,
516        default_expr: spg_sql::ast::Expr,
517    ) -> Result<(), EngineError> {
518        // Volatile defaults (now(), nextval(), …) go through the
519        // runtime_default path; literal defaults freeze into `default`.
520        let display = alloc::format!("{}", default_expr);
521        let is_runtime = matches!(default_expr, spg_sql::ast::Expr::FunctionCall { .. });
522        let literal_value = if is_runtime {
523            None
524        } else {
525            crate::conversions::literal_expr_to_value(default_expr.clone()).ok()
526        };
527        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
528            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
529        })?;
530        let pos = table
531            .schema()
532            .columns
533            .iter()
534            .position(|c| c.name.eq_ignore_ascii_case(&column))
535            .ok_or_else(|| {
536                EngineError::Unsupported(alloc::format!(
537                    "column {column:?} of relation {tbl:?} does not exist"
538                ))
539            })?;
540        // v7.39.9 — the source text follows the default, which it did
541        // not.
542        //
543        // `default_text` is what `information_schema.columns`,
544        // `pg_attrdef` and the DUMP all read, and it was written once at
545        // CREATE TABLE and never again. So after `ALTER TABLE t ALTER
546        // COLUMN b DROP DEFAULT` — PostgreSQL's own spelling — the
547        // catalog held no default and `dump_sql` still wrote
548        // `DEFAULT 5`: restoring that dump brought the default back, and
549        // the schema you got was not the schema you dumped. `SET
550        // DEFAULT 9` had the mirror problem, reporting and dumping the
551        // value it replaced.
552        let ty = table.schema().columns[pos].ty;
553        let text = deparse_default(&default_expr, ty);
554        let col = &mut table.schema_mut().columns[pos];
555        col.default_text = Some(text);
556        if is_runtime {
557            col.runtime_default = Some(display);
558            col.default = None;
559        } else if let Some(v) = literal_value {
560            col.default = Some(v);
561            col.runtime_default = None;
562        } else {
563            // Could not evaluate; fall back to runtime path.
564            col.runtime_default = Some(display);
565            col.default = None;
566        }
567        Ok(())
568    }
569
570    fn alter_column_drop_default(&mut self, tbl: &str, column: String) -> Result<(), EngineError> {
571        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
572            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
573        })?;
574        let pos = table
575            .schema()
576            .columns
577            .iter()
578            .position(|c| c.name.eq_ignore_ascii_case(&column))
579            .ok_or_else(|| {
580                EngineError::Unsupported(alloc::format!(
581                    "ALTER COLUMN DROP DEFAULT: column {column:?} not in table {tbl:?}"
582                ))
583            })?;
584        let col = &mut table.schema_mut().columns[pos];
585        col.default = None;
586        col.runtime_default = None;
587        // v7.39.9 — and the source text the views and the dump read.
588        col.default_text = None;
589        Ok(())
590    }
591
592    /// v7.37.18 (18.2) — set / drop column NOT NULL flag.
593    fn alter_column_set_not_null(&mut self, tbl: &str, column: String) -> Result<(), EngineError> {
594        // Validate no existing row holds NULL in this column
595        // before flipping the flag. PG raises on first NULL hit.
596        // v7.39 (read01 round 49) — scan VISIBLE rows, not physical ones.
597        // Under in-place MVCC a DELETE leaves a tombstoned physical row
598        // behind; counting it made `DELETE FROM t; ALTER TABLE t ALTER c SET
599        // NOT NULL` fail on a table PG sees as empty (the flip-regression
600        // family: same shape as the ATTACH PARTITION empty-check and the
601        // ALTER TYPE rewrite bug).
602        let snap = self.current_snapshot();
603        let table = self.active_catalog().get(tbl).ok_or_else(|| {
604            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
605        })?;
606        let pos = table
607            .schema()
608            .columns
609            .iter()
610            .position(|c| c.name.eq_ignore_ascii_case(&column))
611            .ok_or_else(|| {
612                EngineError::Unsupported(alloc::format!(
613                    "column {column:?} of relation {tbl:?} does not exist"
614                ))
615            })?;
616        for (_, row) in table.scan_visible(&snap) {
617            if matches!(row.values.get(pos), Some(spg_storage::Value::Null)) {
618                // v7.39 (read01 round 49) — PG wording (23502 at the wire).
619                return Err(EngineError::Unsupported(alloc::format!(
620                    "column {column:?} of relation {tbl:?} contains null values"
621                )));
622            }
623        }
624        let table = self
625            .active_catalog_mut()
626            .get_mut(tbl)
627            .expect("checked above");
628        table.schema_mut().columns[pos].nullable = false;
629        Ok(())
630    }
631
632    fn alter_column_drop_not_null(&mut self, tbl: &str, column: String) -> Result<(), EngineError> {
633        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
634            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
635        })?;
636        let pos = table
637            .schema()
638            .columns
639            .iter()
640            .position(|c| c.name.eq_ignore_ascii_case(&column))
641            .ok_or_else(|| {
642                EngineError::Unsupported(alloc::format!(
643                    "ALTER COLUMN DROP NOT NULL: column {column:?} not in table {tbl:?}"
644                ))
645            })?;
646        table.schema_mut().columns[pos].nullable = true;
647        Ok(())
648    }
649
650    /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child <bounds>`.
651    ///
652    /// Promotes an existing standalone table `child` into a partition
653    /// of `parent`. Enforces:
654    ///   1. `parent` is a partition parent (`PartitionRole::Parent`).
655    ///   2. `child` is currently standalone (`partition_role == None`).
656    ///   3. `child`'s column list is layout-compatible with `parent`
657    ///      (same column names, types and ordering — PG also requires
658    ///      this and uses it to delegate the actual storage).
659    ///   4. `bounds` shape matches `parent.kind` (Range/List/Hash).
660    ///   5. New range / list / hash bounds don't overlap any existing
661    ///      sibling — same gates as the CREATE TABLE … PARTITION OF
662    ///      path.
663    ///   6. Every existing row in `child` satisfies the bound predicate
664    ///      (PG's "partition constraint" check). Mis-fits raise; no
665    ///      silent re-routing.
666    fn alter_attach_partition(
667        &mut self,
668        parent_name: &str,
669        child_name: String,
670        bounds: spg_sql::ast::PartitionOfBoundsAst,
671    ) -> Result<(), EngineError> {
672        use spg_sql::ast::PartitionOfBoundsAst;
673        use spg_storage::{PartitionKind, PartitionRole};
674        // Parent gate.
675        let (parent_kind, parent_columns) = {
676            let parent = self.active_catalog().get(parent_name).ok_or_else(|| {
677                EngineError::Storage(StorageError::TableNotFound {
678                    name: parent_name.into(),
679                })
680            })?;
681            match &parent.schema().partition_role {
682                Some(PartitionRole::Parent { kind, .. }) => {
683                    (*kind, parent.schema().columns.clone())
684                }
685                _ => {
686                    return Err(EngineError::Unsupported(alloc::format!(
687                        "ALTER TABLE … ATTACH PARTITION: {parent_name:?} is not a partition parent"
688                    )));
689                }
690            }
691        };
692        // Child gate: must exist + be standalone + share parent's
693        // column layout.
694        {
695            let child = self.active_catalog().get(&child_name).ok_or_else(|| {
696                EngineError::Storage(StorageError::TableNotFound {
697                    name: child_name.clone(),
698                })
699            })?;
700            if child.schema().partition_role.is_some() {
701                return Err(EngineError::Unsupported(alloc::format!(
702                    "ALTER TABLE … ATTACH PARTITION: {child_name:?} is already a partition; \
703                     DETACH it first"
704                )));
705            }
706            let child_cols = &child.schema().columns;
707            if child_cols.len() != parent_columns.len() {
708                return Err(EngineError::Unsupported(alloc::format!(
709                    "ALTER TABLE … ATTACH PARTITION: column-count mismatch \
710                     ({child_name:?} has {}, {parent_name:?} has {})",
711                    child_cols.len(),
712                    parent_columns.len()
713                )));
714            }
715            for (c, p) in child_cols.iter().zip(parent_columns.iter()) {
716                if !c.name.eq_ignore_ascii_case(&p.name) || c.ty != p.ty {
717                    return Err(EngineError::Unsupported(alloc::format!(
718                        "ALTER TABLE … ATTACH PARTITION: column {:?} of {child_name:?} \
719                         (type {:?}) doesn't match column {:?} of {parent_name:?} (type {:?})",
720                        c.name,
721                        c.ty,
722                        p.name,
723                        p.ty
724                    )));
725                }
726            }
727        }
728        // Resolve bounds (same gates as CREATE TABLE … PARTITION OF).
729        let role = match bounds {
730            PartitionOfBoundsAst::Default => PartitionRole::Default {
731                parent_name: parent_name.into(),
732            },
733            PartitionOfBoundsAst::Range { lower, upper } => {
734                if !matches!(parent_kind, PartitionKind::Range) {
735                    return Err(EngineError::Unsupported(alloc::format!(
736                        "ATTACH PARTITION: FOR VALUES FROM/TO only valid for a RANGE-partitioned \
737                         parent (parent {parent_name:?} is {parent_kind:?})"
738                    )));
739                }
740                let lower_b = crate::partition::evaluate_partition_bound(*lower)?;
741                let upper_b = crate::partition::evaluate_partition_bound(*upper)?;
742                if !crate::partition::ranges_overlap(&lower_b, &upper_b, &lower_b, &upper_b) {
743                    return Err(EngineError::Unsupported(alloc::format!(
744                        "ATTACH PARTITION: FROM ({}) TO ({}) is empty (lower must be < upper)",
745                        crate::partition::bound_to_diag(&lower_b),
746                        crate::partition::bound_to_diag(&upper_b),
747                    )));
748                }
749                for sib in crate::partition::children_of_parent(self.active_catalog(), parent_name)
750                {
751                    let Some(t) = self.active_catalog().get(&sib) else {
752                        continue;
753                    };
754                    if let Some(PartitionRole::Range {
755                        lower: sl,
756                        upper: su,
757                        ..
758                    }) = &t.schema().partition_role
759                    {
760                        if crate::partition::ranges_overlap(&lower_b, &upper_b, sl, su) {
761                            return Err(EngineError::Unsupported(alloc::format!(
762                                "ATTACH PARTITION: range FROM ({}) TO ({}) overlaps sibling \
763                                 {sib:?} (FROM ({}) TO ({}))",
764                                crate::partition::bound_to_diag(&lower_b),
765                                crate::partition::bound_to_diag(&upper_b),
766                                crate::partition::bound_to_diag(sl),
767                                crate::partition::bound_to_diag(su),
768                            )));
769                        }
770                    }
771                }
772                PartitionRole::Range {
773                    parent_name: parent_name.into(),
774                    lower: lower_b,
775                    upper: upper_b,
776                }
777            }
778            PartitionOfBoundsAst::List { values } => {
779                if !matches!(parent_kind, PartitionKind::List) {
780                    return Err(EngineError::Unsupported(alloc::format!(
781                        "ATTACH PARTITION: FOR VALUES IN only valid for a LIST-partitioned \
782                         parent (parent {parent_name:?} is {parent_kind:?})"
783                    )));
784                }
785                let mut bounds_v = Vec::with_capacity(values.len());
786                for v in values {
787                    bounds_v.push(crate::partition::evaluate_partition_bound(v)?);
788                }
789                for sib in crate::partition::children_of_parent(self.active_catalog(), parent_name)
790                {
791                    let Some(t) = self.active_catalog().get(&sib) else {
792                        continue;
793                    };
794                    if let Some(PartitionRole::List {
795                        values: existing, ..
796                    }) = &t.schema().partition_role
797                    {
798                        for new_b in &bounds_v {
799                            if existing.iter().any(|e| e == new_b) {
800                                // v7.39 (round 770) — PG's overlap sentence.
801                                let _ = crate::partition::bound_to_diag(new_b);
802                                return Err(EngineError::Unsupported(alloc::format!(
803                                    "partition \"{child_name}\" would overlap partition \"{sib}\"",
804                                )));
805                            }
806                        }
807                    }
808                }
809                PartitionRole::List {
810                    parent_name: parent_name.into(),
811                    values: bounds_v,
812                }
813            }
814            PartitionOfBoundsAst::Hash { modulus, remainder } => {
815                if !matches!(parent_kind, PartitionKind::Hash) {
816                    return Err(EngineError::Unsupported(alloc::format!(
817                        "ATTACH PARTITION: FOR VALUES WITH only valid for a HASH-partitioned \
818                         parent (parent {parent_name:?} is {parent_kind:?})"
819                    )));
820                }
821                if modulus == 0 || remainder >= modulus {
822                    return Err(EngineError::Unsupported(alloc::format!(
823                        "ATTACH PARTITION: HASH (MODULUS={modulus}, REMAINDER={remainder}) \
824                         must satisfy modulus > 0 and remainder < modulus"
825                    )));
826                }
827                for sib in crate::partition::children_of_parent(self.active_catalog(), parent_name)
828                {
829                    let Some(t) = self.active_catalog().get(&sib) else {
830                        continue;
831                    };
832                    if let Some(PartitionRole::Hash {
833                        modulus: m,
834                        remainder: r,
835                        ..
836                    }) = &t.schema().partition_role
837                    {
838                        if *m != modulus {
839                            return Err(EngineError::Unsupported(alloc::format!(
840                                "ATTACH PARTITION: HASH MODULUS {modulus} differs from sibling \
841                                 {sib:?} MODULUS {m} (mixed moduli not yet supported)"
842                            )));
843                        }
844                        if *r == remainder {
845                            return Err(EngineError::Unsupported(alloc::format!(
846                                "ATTACH PARTITION: HASH REMAINDER {remainder} already used \
847                                 by sibling {sib:?}"
848                            )));
849                        }
850                    }
851                }
852                PartitionRole::Hash {
853                    parent_name: parent_name.into(),
854                    modulus,
855                    remainder,
856                }
857            }
858        };
859        // PG-style "partition constraint" check — every existing row
860        // in child must satisfy the new role's predicate. For now we
861        // leave row-validation as TODO (16.3.b): pre-existing rows
862        // could violate the bound. v7.37.16.3 ships with a
863        // pessimistic gate: refuse ATTACH if the child has any rows
864        // and require the operator to either DROP them first or use
865        // a fresh empty child. This matches PG's safest behaviour
866        // (PG actually scans the rows; our scan path lands in
867        // 16.3.b). Match the spirit, not the letter.
868        // Count *visible* rows: under in-place MVCC a DELETE leaves a
869        // tombstoned physical row behind, which must not fail the
870        // empty-child gate (legacy path removed it physically).
871        // v7.39 (round 621) — 16.3.b, the row scan the gate above promised.
872        //
873        // The pessimistic "child must be empty" gate refused the ordinary
874        // migration — build a table, load it, attach it — that partitioned
875        // setups are adopted FOR. PG scans the rows; now so does this. Every
876        // visible row's key must satisfy the new bound, and one that does not
877        // raises PG's wording (`partition constraint of relation … is violated
878        // by some row`) BEFORE the role is installed, so a failed attach
879        // changes nothing.
880        let key_pos = {
881            let parent = self.active_catalog().get(parent_name);
882            match parent.and_then(|p| p.schema().partition_role.as_ref()) {
883                Some(spg_storage::PartitionRole::Parent {
884                    key_column_positions,
885                    ..
886                }) => key_column_positions.first().copied().unwrap_or(0),
887                _ => 0,
888            }
889        };
890        let snap = self.current_snapshot();
891        if let Some(t) = self.active_catalog().get(&child_name) {
892            for (_, row) in t.scan_visible(&snap) {
893                let key = row.values.get(key_pos).cloned().unwrap_or(Value::Null);
894                let fits = match &role {
895                    PartitionRole::Range { lower, upper, .. } => {
896                        crate::partition::value_to_bound(&key)
897                            .is_some_and(|b| crate::partition::value_in_range(&b, lower, upper))
898                    }
899                    PartitionRole::List { values, .. } => {
900                        values.iter().any(|b| b.equals_value(&key))
901                    }
902                    PartitionRole::Hash {
903                        modulus, remainder, ..
904                    } => {
905                        crate::partition::pg_compatible_hash(&key).rem_euclid(u64::from(*modulus))
906                            == u64::from(*remainder)
907                    }
908                    // A DEFAULT partition takes whatever no sibling claims, so
909                    // any existing row satisfies it.
910                    // v7.39 (round 645) — an inheritance child has no key
911                    // constraint at all: nothing it holds can fail to fit.
912                    PartitionRole::Default { .. }
913                    | PartitionRole::Parent { .. }
914                    | PartitionRole::Inherits { .. } => true,
915                };
916                if !fits {
917                    return Err(EngineError::Unsupported(alloc::format!(
918                        "partition constraint of relation {child_name:?} is violated by some row"
919                    )));
920                }
921            }
922        }
923        // Install role.
924        let child = self
925            .active_catalog_mut()
926            .get_mut(&child_name)
927            .expect("child existed above");
928        child.schema_mut().partition_role = Some(role);
929        Ok(())
930    }
931
932    /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
933    /// child [CONCURRENTLY] [FINALIZE]`.
934    ///
935    /// Demotes a partition back to a standalone table by clearing
936    /// `partition_role`. CONCURRENTLY + FINALIZE are accepted at the
937    /// parser; semantically SPG's single-engine model lets us detach
938    /// atomically (PG's two-phase split addresses replication lag,
939    /// which doesn't apply here).
940    fn alter_detach_partition(
941        &mut self,
942        parent_name: &str,
943        child_name: String,
944        _concurrently: bool,
945        _finalize: bool,
946    ) -> Result<(), EngineError> {
947        use spg_storage::PartitionRole;
948        // Parent gate.
949        {
950            let parent = self.active_catalog().get(parent_name).ok_or_else(|| {
951                EngineError::Storage(StorageError::TableNotFound {
952                    name: parent_name.into(),
953                })
954            })?;
955            if !matches!(
956                parent.schema().partition_role,
957                Some(PartitionRole::Parent { .. })
958            ) {
959                return Err(EngineError::Unsupported(alloc::format!(
960                    "ALTER TABLE … DETACH PARTITION: {parent_name:?} is not a partition parent"
961                )));
962            }
963        }
964        // Child gate: must be a partition of THIS parent.
965        {
966            let child = self.active_catalog().get(&child_name).ok_or_else(|| {
967                EngineError::Storage(StorageError::TableNotFound {
968                    name: child_name.clone(),
969                })
970            })?;
971            let parent_of_child = match &child.schema().partition_role {
972                Some(PartitionRole::Range { parent_name, .. })
973                | Some(PartitionRole::List { parent_name, .. })
974                | Some(PartitionRole::Hash { parent_name, .. })
975                | Some(PartitionRole::Default { parent_name }) => parent_name.clone(),
976                _ => {
977                    return Err(EngineError::Unsupported(alloc::format!(
978                        "DETACH PARTITION: {child_name:?} is not a partition"
979                    )));
980                }
981            };
982            if parent_of_child != parent_name {
983                return Err(EngineError::Unsupported(alloc::format!(
984                    "DETACH PARTITION: {child_name:?} is a partition of {parent_of_child:?}, \
985                     not {parent_name:?}"
986                )));
987            }
988        }
989        // Clear role.
990        let child = self
991            .active_catalog_mut()
992            .get_mut(&child_name)
993            .expect("child existed above");
994        child.schema_mut().partition_role = None;
995        Ok(())
996    }
997
998    /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
999    ///
1000    /// Measured on PG18: after `NO INHERIT`, the parent stops seeing the
1001    /// child's rows, `pg_inherits` loses the row, and the child keeps
1002    /// everything it had. `INHERIT` puts it back. Neither moves a row.
1003    ///
1004    /// A child of several parents keeps the others; the parent list is
1005    /// ordered, and dropping one from the middle leaves the rest in
1006    /// place — which is also what makes `pg_inherits.inhseqno` keep
1007    /// meaning what it means.
1008    fn alter_inherit(
1009        &mut self,
1010        child: &str,
1011        parent: &str,
1012        detach: bool,
1013    ) -> Result<(), EngineError> {
1014        use spg_storage::PartitionRole;
1015        if self.active_catalog().get(parent).is_none() {
1016            return Err(EngineError::Storage(
1017                spg_storage::StorageError::TableNotFound {
1018                    name: parent.to_string(),
1019                },
1020            ));
1021        }
1022        let Some(t) = self.active_catalog_mut().get_mut(child) else {
1023            return Err(EngineError::Storage(
1024                spg_storage::StorageError::TableNotFound {
1025                    name: child.to_string(),
1026                },
1027            ));
1028        };
1029        let current = match &t.schema().partition_role {
1030            Some(PartitionRole::Inherits { parent_names }) => parent_names.clone(),
1031            Some(_) => {
1032                return Err(EngineError::Unsupported(alloc::format!(
1033                    "{child:?} is a partition, not an inheritance child"
1034                )));
1035            }
1036            None => Vec::new(),
1037        };
1038        let mut names = current;
1039        if detach {
1040            let before = names.len();
1041            names.retain(|p| !p.eq_ignore_ascii_case(parent));
1042            if names.len() == before {
1043                // v7.39 (round 652) — PG names the PARENT first:
1044                // `relation "parent" is not a parent of relation "child"`.
1045                // SPG had the two the other way round, so a client
1046                // matching on the message read the wrong relation as the
1047                // one at fault.
1048                return Err(EngineError::Unsupported(alloc::format!(
1049                    "relation {parent:?} is not a parent of relation {child:?}"
1050                )));
1051            }
1052        } else {
1053            if names.iter().any(|p| p.eq_ignore_ascii_case(parent)) {
1054                return Err(EngineError::Unsupported(alloc::format!(
1055                    "relation {child:?} would be inherited from {parent:?} more than once"
1056                )));
1057            }
1058            names.push(parent.to_string());
1059        }
1060        t.schema_mut().partition_role = if names.is_empty() {
1061            None
1062        } else {
1063            Some(PartitionRole::Inherits {
1064                parent_names: names,
1065            })
1066        };
1067        Ok(())
1068    }
1069
1070    fn alter_set_hot_tier_bytes(&mut self, tbl: &str, n: u64) -> Result<(), EngineError> {
1071        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1072            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1073        })?;
1074        table.schema_mut().hot_tier_bytes = Some(n);
1075        Ok(())
1076    }
1077
1078    fn alter_add_foreign_key(
1079        &mut self,
1080        tbl: &str,
1081        fk: spg_sql::ast::ForeignKeyConstraint,
1082    ) -> Result<(), EngineError> {
1083        // v7.6.8 — resolve FK against the live catalog first
1084        // (validates parent table, columns, indices). Then
1085        // verify every existing row in the child table
1086        // satisfies the new constraint. Then install it.
1087        let cols_snapshot = self
1088            .active_catalog()
1089            .get(tbl)
1090            .ok_or_else(|| EngineError::Storage(StorageError::TableNotFound { name: tbl.into() }))?
1091            .schema()
1092            .columns
1093            .clone();
1094        let storage_fk = resolve_foreign_key(tbl, &cols_snapshot, fk, self.active_catalog())?;
1095        // Verify existing rows. Treat them as a virtual
1096        // INSERT batch — reusing the v7.6.2 enforce helper.
1097        let existing_rows: Vec<Vec<Value<'static>>> = self
1098            .active_catalog()
1099            .get(tbl)
1100            .expect("checked above")
1101            .rows()
1102            .iter()
1103            .map(|r| r.values.clone())
1104            .collect();
1105        enforce_fk_inserts(
1106            self.active_catalog(),
1107            tbl,
1108            core::slice::from_ref(&storage_fk),
1109            &existing_rows,
1110        )?;
1111        // Reject duplicate constraint name.
1112        let table = self
1113            .active_catalog_mut()
1114            .get_mut(tbl)
1115            .expect("checked above");
1116        if let Some(name) = &storage_fk.name
1117            && table
1118                .schema()
1119                .foreign_keys
1120                .iter()
1121                .any(|f| f.name.as_ref() == Some(name))
1122        {
1123            // v7.39 (read01 round 47) — PG wording (42710).
1124            return Err(EngineError::Unsupported(alloc::format!(
1125                "constraint {name:?} for relation {tbl:?} already exists"
1126            )));
1127        }
1128        table.schema_mut().foreign_keys.push(storage_fk);
1129        Ok(())
1130    }
1131
1132    /// v7.13.2 / v7.37.18 (18.17 widened) — DROP CONSTRAINT for
1133    /// FK + PK/UNIQUE + CHECK. Originally FK-only; widened to
1134    /// match PG's behaviour where `ALTER TABLE t DROP CONSTRAINT
1135    /// t_pkey` removes a PRIMARY KEY just like it would an FK.
1136    fn alter_drop_foreign_key(
1137        &mut self,
1138        tbl: &str,
1139        name: String,
1140        if_exists: bool,
1141    ) -> Result<(), EngineError> {
1142        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1143            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1144        })?;
1145        // v7.39 (read01 round 48) — 0) the stored name wins. A constraint
1146        // created with `ADD CONSTRAINT <name> …` (or the inline `CONSTRAINT
1147        // <name>` form) now carries that name, so DROP finds it directly.
1148        // Catalogs written before FILE_VERSION 60 have no stored names and
1149        // fall through to the synthesised-name lookups below, which stay
1150        // exactly as they were.
1151        {
1152            let ucs = &mut table.schema_mut().uniqueness_constraints;
1153            let before = ucs.len();
1154            ucs.retain(|u| u.name.as_deref() != Some(name.as_str()));
1155            if ucs.len() != before {
1156                return Ok(());
1157            }
1158            let checks = &mut table.schema_mut().checks;
1159            let before = checks.len();
1160            checks.retain(|c| c.name.as_deref() != Some(name.as_str()));
1161            if checks.len() != before {
1162                return Ok(());
1163            }
1164        }
1165        // 1) Try foreign keys.
1166        let fks = &mut table.schema_mut().foreign_keys;
1167        let fk_before = fks.len();
1168        fks.retain(|f| f.name.as_ref() != Some(&name));
1169        if fks.len() != fk_before {
1170            return Ok(());
1171        }
1172        // 2) Try PK / UNIQUE constraints by their SYNTHESISED name.
1173        //    v7.39 (read01 round 48) — resolve through the very
1174        //    synthesisers pg_constraint / pg_get_constraintdef report from
1175        //    (`pg_unique_conname` / `pg_check_connames`), so a name the
1176        //    catalog shows is always a name DROP accepts. The old ad-hoc
1177        //    `<table>_uniqN` / `<table>_checkN` prefixes never matched what
1178        //    the views printed (`<table>_<col>_key` / `<table>_<col>_check`).
1179        // (Single-column UNIQUE indices that don't have a UC entry need to go
1180        // through `DROP INDEX <name>` instead — indices are a slice, not a Vec.)
1181        let uc_hit = table.schema().uniqueness_constraints.iter().position(|uc| {
1182            uc.name.is_none() && crate::system_catalog::pg_unique_conname(table, uc, tbl) == name
1183        });
1184        if let Some(idx) = uc_hit {
1185            table.schema_mut().uniqueness_constraints.remove(idx);
1186            return Ok(());
1187        }
1188        // 3) CHECK constraints by their synthesised name.
1189        let check_names =
1190            crate::system_catalog::pg_check_connames(table, tbl, &table.schema().checks);
1191        let check_hit = check_names.iter().position(|n| *n == name);
1192        if let Some(idx) = check_hit {
1193            let checks = &mut table.schema_mut().checks;
1194            if idx < checks.len() {
1195                checks.remove(idx);
1196                return Ok(());
1197            }
1198        }
1199        // Nothing matched; respect IF EXISTS.
1200        if if_exists {
1201            return Ok(());
1202        }
1203        // v7.39 (read01 round 47) — PG wording (42704). Note PG's own
1204        // inconsistency: DROP CONSTRAINT says "of relation" while ADD
1205        // CONSTRAINT says "for relation" — both are matched verbatim.
1206        Err(EngineError::Unsupported(alloc::format!(
1207            "constraint {name:?} of relation {tbl:?} does not exist"
1208        )))
1209    }
1210
1211    /// v7.39.9 — MySQL's `MODIFY COLUMN c <def>` and `CHANGE COLUMN old
1212    /// new <def>`.
1213    ///
1214    /// Both REPLACE the definition, and that is the whole difficulty:
1215    /// measured on MySQL 9.7.2, a column declared `INT NOT NULL DEFAULT
1216    /// 5` is `bigint`, NULLABLE, with NO default after `MODIFY COLUMN b
1217    /// BIGINT`. Restating them keeps them; omitting them drops them. A
1218    /// version that only changed the type would silently keep a NOT
1219    /// NULL the statement removed, which is a constraint the migration
1220    /// asked to lift.
1221    fn alter_modify_column(
1222        &mut self,
1223        tbl: &str,
1224        column: String,
1225        rename_to: Option<String>,
1226        definition: ColumnDef,
1227        position: Option<spg_sql::ast::ColumnPosition>,
1228    ) -> Result<(), EngineError> {
1229        let exists = self
1230            .active_catalog()
1231            .get(tbl)
1232            .ok_or_else(|| EngineError::Storage(StorageError::TableNotFound { name: tbl.into() }))?
1233            .schema()
1234            .columns
1235            .iter()
1236            .any(|c| c.name.eq_ignore_ascii_case(&column));
1237        if !exists {
1238            return Err(EngineError::Storage(StorageError::ColumnNotFound {
1239                column: column.clone(),
1240            }));
1241        }
1242        // The type first, under the name it still has.
1243        self.alter_column_type(tbl, column.clone(), definition.ty, None, None)?;
1244        // Then the rest of the definition, replaced rather than amended.
1245        if definition.nullable {
1246            self.alter_column_drop_not_null(tbl, column.clone())?;
1247        } else {
1248            self.alter_column_set_not_null(tbl, column.clone())?;
1249        }
1250        match definition.default.clone() {
1251            Some(d) => self.alter_column_set_default(tbl, column.clone(), d)?,
1252            None => self.alter_column_drop_default(tbl, column.clone())?,
1253        }
1254        // v7.39.9 — MySQL moves the column when the statement says so,
1255        // and the move has to happen with the column's data: this is
1256        // the same rewrite `ADD … AFTER` does.
1257        if let Some(pos) = position {
1258            self.move_column(tbl, &column, &pos)?;
1259        }
1260        if let Some(new) = rename_to
1261            && !new.eq_ignore_ascii_case(&column)
1262        {
1263            self.alter_rename_column(tbl, column, new)?;
1264        }
1265        Ok(())
1266    }
1267
1268    /// v7.39.9 — move an existing column to a position, carrying its
1269    /// values. Used by `MODIFY … AFTER c` / `… FIRST`.
1270    fn move_column(
1271        &mut self,
1272        tbl: &str,
1273        column: &str,
1274        pos: &spg_sql::ast::ColumnPosition,
1275    ) -> Result<(), EngineError> {
1276        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1277            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1278        })?;
1279        let from = table
1280            .schema()
1281            .columns
1282            .iter()
1283            .position(|c| c.name.eq_ignore_ascii_case(column))
1284            .ok_or_else(|| {
1285                EngineError::Storage(StorageError::ColumnNotFound {
1286                    column: column.into(),
1287                })
1288            })?;
1289        let to = match pos {
1290            spg_sql::ast::ColumnPosition::First => 0,
1291            spg_sql::ast::ColumnPosition::After(after) => {
1292                let a = table
1293                    .schema()
1294                    .columns
1295                    .iter()
1296                    .position(|c| c.name.eq_ignore_ascii_case(after))
1297                    .ok_or_else(|| {
1298                        EngineError::Storage(StorageError::ColumnNotFound {
1299                            column: after.clone(),
1300                        })
1301                    })?;
1302                if a < from { a + 1 } else { a }
1303            }
1304        };
1305        if to != from {
1306            table.move_column(from, to);
1307        }
1308        Ok(())
1309    }
1310
1311    /// v7.39.9 — MySQL's `RENAME {INDEX|KEY} old TO new`.
1312    fn alter_rename_index(&mut self, tbl: &str, old: &str, new: &str) -> Result<(), EngineError> {
1313        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1314            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1315        })?;
1316        if table.rename_index(old, new) {
1317            Ok(())
1318        } else {
1319            // MySQL's own sentence, and a DIFFERENT one from the drop
1320            // path's: measured on 9.7.2, `RENAME INDEX k_none TO k_new`
1321            // answers `Key 'k_none' doesn't exist in table 'm1'` (1176)
1322            // where `DROP INDEX k_none ON m1` answers `Can't DROP …`
1323            // (1091). A client branching on the number can tell the two
1324            // apart, so they must not collapse into one.
1325            Err(EngineError::Unsupported(alloc::format!(
1326                "Key '{old}' doesn't exist in table '{tbl}'"
1327            )))
1328        }
1329    }
1330
1331    /// v7.39.9 — MySQL's `ALTER TABLE t AUTO_INCREMENT = n`: the value
1332    /// the NEXT insert takes. Measured on 9.7.2: after `= 100`, the
1333    /// next row's id is 100.
1334    fn alter_set_table_auto_increment(&mut self, tbl: &str, n: i64) -> Result<(), EngineError> {
1335        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1336            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1337        })?;
1338        table.set_auto_increment_next(n);
1339        Ok(())
1340    }
1341
1342    /// v7.39.9 — MySQL's `ENGINE = <name>`.
1343    ///
1344    /// SPG has one storage engine and substitutes for every name MySQL
1345    /// knows, which is what `CREATE TABLE` already does. A name MySQL
1346    /// does not know is refused with its own sentence, because a typo
1347    /// in a migration must not quietly become SPG's storage — the same
1348    /// reasoning, and the same list, as the CREATE path.
1349    fn alter_set_engine(name: &str) -> Result<(), EngineError> {
1350        if crate::MYSQL_KNOWN_ENGINES
1351            .iter()
1352            .any(|k| k.eq_ignore_ascii_case(name))
1353        {
1354            Ok(())
1355        } else {
1356            Err(EngineError::Unsupported(alloc::format!(
1357                "Unknown storage engine '{name}'"
1358            )))
1359        }
1360    }
1361
1362    /// v7.39.9 — MySQL's `CONVERT TO CHARACTER SET <cs> [COLLATE <c>]`.
1363    ///
1364    /// SPG stores UTF-8 throughout, so a charset that IS UTF-8 is
1365    /// accepted and anything else is refused with MySQL's sentence.
1366    /// Measured on 9.7.2: `utf8mb4` succeeds, `nosuchcs` answers
1367    /// `ERROR 1115 (42000) Unknown character set: 'nosuchcs'`.
1368    fn alter_convert_charset(charset: &str, _collate: Option<&str>) -> Result<(), EngineError> {
1369        // The charsets SPG can represent, which is UTF-8 and its
1370        // MySQL spellings. A conversion to anything else would change
1371        // what the bytes mean, so it is refused rather than accepted
1372        // and ignored.
1373        if ["utf8mb4", "utf8mb3", "utf8", "ascii", "binary"]
1374            .iter()
1375            .any(|k| k.eq_ignore_ascii_case(charset))
1376        {
1377            Ok(())
1378        } else {
1379            Err(EngineError::Unsupported(alloc::format!(
1380                "Unknown character set: '{charset}'"
1381            )))
1382        }
1383    }
1384
1385    fn alter_add_column(
1386        &mut self,
1387        tbl: &str,
1388        column: ColumnDef,
1389        if_not_exists: bool,
1390        position: Option<spg_sql::ast::ColumnPosition>,
1391    ) -> Result<(), EngineError> {
1392        // v7.13.0 — mailrs round-5 G1. Append-only column add
1393        // with back-fill of the DEFAULT (or NULL) into every
1394        // existing row. Column positions don't shift, so we
1395        // skip index rebuild.
1396        let clock = self.clock;
1397        let add_mysql = self.speaks_mysql;
1398        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1399            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1400        })?;
1401        if table
1402            .schema()
1403            .columns
1404            .iter()
1405            .any(|c| c.name.eq_ignore_ascii_case(&column.name))
1406        {
1407            if if_not_exists {
1408                // v7.39 (read01 round 46) — PG's IF NOT EXISTS skip NOTICE.
1409                self.notice(alloc::format!(
1410                    "column {:?} of relation {:?} already exists, skipping",
1411                    column.name,
1412                    tbl
1413                ));
1414                return Ok(());
1415            }
1416            // v7.39 (read01 round 45) — PG wording (42701 at the wire).
1417            return Err(EngineError::Unsupported(alloc::format!(
1418                "column {:?} of relation {:?} already exists",
1419                column.name,
1420                tbl
1421            )));
1422        }
1423        let col_name = column.name.clone();
1424        let nullable = column.nullable;
1425        let has_default = column.default.is_some() || column.auto_increment;
1426        // v7.38.3 (sentori 2.2) — the inline `CHECK (…)` on an ADD COLUMN.
1427        // The parser has always put it on the ColumnDef and this path has
1428        // never read it, so `ALTER TABLE t ADD COLUMN env text CHECK (env
1429        // IN ('a','b'))` was ACCEPTED and registered nothing: pg_constraint
1430        // showed no row and a violating INSERT went in. A constraint that
1431        // silently does not exist is worse than one that loudly does not
1432        // work. (The separate `ADD CONSTRAINT` form was always enforced —
1433        // only the inline-on-ADD-COLUMN spelling vanished.)
1434        let inline_check = column.check.clone().map(|e| e.to_string());
1435        let col_schema = column_def_to_schema(column, add_mysql)?;
1436        let row_count = table.row_count();
1437        // Compute the back-fill value. Literal / runtime DEFAULT
1438        // funnels through the same resolver that INSERT uses
1439        // (v7.9.21 `resolve_column_default_free`). NULL when
1440        // the column is nullable and has no DEFAULT. NOT NULL
1441        // without DEFAULT errors when the table has existing
1442        // rows — same as PG.
1443        let fill_value: Value<'static> = if has_default || col_schema.runtime_default.is_some() {
1444            resolve_column_default_free(&col_schema, clock, None)?
1445        } else if nullable || row_count == 0 {
1446            Value::Null
1447        } else {
1448            // v7.39 (read01 round 89) — PG's exact wording (23502):
1449            // `column "req" of relation "t" contains null values`.
1450            return Err(EngineError::Unsupported(alloc::format!(
1451                "column \"{col_name}\" of relation \"{tbl}\" contains null values"
1452            )));
1453        };
1454        // v7.39.9 — MySQL says where the column goes, and means it:
1455        // measured on 9.7.2, `AFTER a` lands it at ordinal 3 and pushes
1456        // the old third column to 4. Appending instead would answer a
1457        // different `SELECT *`.
1458        match &position {
1459            None => table.add_column(col_schema, fill_value),
1460            Some(spg_sql::ast::ColumnPosition::First) => {
1461                table.add_column_at(0, col_schema, fill_value);
1462            }
1463            Some(spg_sql::ast::ColumnPosition::After(after)) => {
1464                let Some(at) = table
1465                    .schema()
1466                    .columns
1467                    .iter()
1468                    .position(|c| c.name.eq_ignore_ascii_case(after))
1469                else {
1470                    return Err(EngineError::Storage(StorageError::ColumnNotFound {
1471                        column: after.clone(),
1472                    }));
1473                };
1474                table.add_column_at(at + 1, col_schema, fill_value);
1475            }
1476        }
1477        // The column exists before the CHECK is validated, because the
1478        // predicate is written in terms of it. PG validates against the
1479        // rows already there and refuses the whole statement if any fails
1480        // — measured: adding `e text CHECK (e IS NOT NULL)` to a table
1481        // with a row errors ("is violated by some row"), while the same
1482        // column with a DEFAULT that satisfies it succeeds. On refusal the
1483        // column has to come back out; nothing else has happened yet.
1484        if let Some(src) = inline_check {
1485            let pos = table.schema().columns.len() - 1;
1486            let name = alloc::format!("{tbl}_{col_name}_check");
1487            if let Err(e) =
1488                crate::constraints::validate_check_against_existing_rows(table, tbl, &name, &src)
1489            {
1490                table.drop_column(pos);
1491                return Err(e);
1492            }
1493            table
1494                .schema_mut()
1495                .checks
1496                .push(spg_storage::CheckConstraint {
1497                    // Unnamed: `pg_check_connames` synthesises PG's
1498                    // `<table>_<column>_check` from the referenced column, the
1499                    // same name the CREATE TABLE spelling gets.
1500                    name: None,
1501                    expr: src,
1502                    validated: true,
1503                });
1504        }
1505        Ok(())
1506    }
1507
1508    fn alter_column_type(
1509        &mut self,
1510        tbl: &str,
1511        column: String,
1512        new_type: spg_sql::ast::ColumnTypeName,
1513        using: Option<Expr>,
1514        collation: Option<(spg_sql::ast::Collation, alloc::string::String)>,
1515    ) -> Result<(), EngineError> {
1516        // v7.13.0 — mailrs round-5 G8. Re-evaluate each
1517        // row's column value (either through the USING
1518        // expression if supplied, or as a direct CAST of
1519        // the existing value) and re-coerce to the new
1520        // type. Indices on the column get rebuilt.
1521        let new_data_type = column_type_to_data_type(new_type);
1522        // v7.39 (round 713) — `TYPE <ty> COLLATE <name>`. PG refuses a
1523        // collation on a non-collatable type; on a collatable one it
1524        // re-collates, and NO clause resets to the type default (both
1525        // measured round 713). The clause parsed here all along and was
1526        // dropped — the statement succeeded, the ordering never changed.
1527        let is_collatable = matches!(
1528            new_data_type,
1529            DataType::Text | DataType::Varchar(_) | DataType::Char(_)
1530        );
1531        if collation.is_some() && !is_collatable {
1532            let spelled = crate::conversions::regtype_oid_to_name(
1533                crate::system_catalog::pg_type_oid(new_data_type),
1534            )
1535            .unwrap_or("this type");
1536            return Err(EngineError::Unsupported(alloc::format!(
1537                "collations are not supported by type {spelled}"
1538            )));
1539        }
1540        // v7.38.18 (G2) — a collation PostgreSQL does not have is not a
1541        // collation, and PG 18.4 says so: `collation "x" for encoding
1542        // "UTF8" does not exist`. Round 670 chose warn-not-refuse under
1543        // the zero-customer-change ruling, when this build could perform
1544        // almost nothing and refusing would have failed working DDL.
1545        // That calculus has inverted: 880 names are performable now, so
1546        // the only ones refused here are the ones PG refuses too, and
1547        // refusing is what keeps a customer's DDL behaving the same.
1548        //
1549        // The dialect decides, because MySQL's names are not in PG's
1550        // catalogue and PG rejects them — measured on 18.4.
1551        if let Some((_, name)) = &collation
1552            && !crate::collate::is_known(name)
1553        {
1554            return Err(crate::collate::unknown_collation_error(
1555                name,
1556                self.speaks_mysql,
1557            ));
1558        }
1559        // v7.38.18 — the warning that used to stand here said range
1560        // comparisons "still compare by bytes". That stopped being true
1561        // in this version: a declared collation reaches `<`, `BETWEEN`
1562        // and the index keys, verified against PG 18.4. A warning that
1563        // is false is worse than none, so only the unperformable case
1564        // keeps one.
1565        if let Some((_, name)) = &collation
1566            && !crate::collate::is_supported(name)
1567        {
1568            self.warning(alloc::format!(
1569                "column \"{column}\" declares COLLATE \"{name}\", which this build \
1570                 cannot perform; SPG records the declaration and orders this column \
1571                 by bytes (the C collation)"
1572            ));
1573        }
1574        let mysql_dialect = self.speaks_mysql;
1575        // v7.39 — under in-place MVCC the row store carries tombstoned
1576        // versions; their dead values must not join the rewrite (an
1577        // INT corpse under a TEXT conversion would abort the whole
1578        // ALTER). Snapshot BEFORE the &mut borrow.
1579        let scan_snapshot = self.current_snapshot();
1580        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1581            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1582        })?;
1583        let col_pos = table
1584            .schema()
1585            .columns
1586            .iter()
1587            .position(|c| c.name.eq_ignore_ascii_case(&column))
1588            .ok_or_else(|| {
1589                EngineError::Unsupported(alloc::format!(
1590                    "column {column:?} of relation {:?} does not exist",
1591                    tbl
1592                ))
1593            })?;
1594        // v7.36 (cold-tier coverage) — ALTER COLUMN TYPE rewrites
1595        // every row's value to the new representation. Cold-tier
1596        // rows live in segments encoded against the OLD type and
1597        // can't be rewritten in-place from this path; doing the
1598        // ALTER anyway would leave the segments unreadable under
1599        // the new schema. Match PG / MariaDB's invariant of "never
1600        // half-apply a schema change" by raising explicitly.
1601        // v7.39 (round 456) — O(1) predicate first; see the DELETE path.
1602        if table.has_cold_rows_fast() && table.count_cold_locators() > 0 {
1603            return Err(EngineError::Unsupported(alloc::format!(
1604                "ALTER COLUMN TYPE on {tbl:?}: cold-tier rows exist for this table; \
1605                 cold-tier schema rewrite is a v7.37 candidate. Run COMPACT to bring \
1606                 the cold rows back to the hot tier and retry."
1607            )));
1608        }
1609        let schema_cols = table.schema().columns.clone();
1610        let ctx = eval::EvalContext::new(&schema_cols, None);
1611        // `None` = a tombstoned version: left untouched entirely (its
1612        // slot is never rewritten, so the update_row type check on the
1613        // NEW schema never sees the old-type corpse).
1614        let mut new_values: alloc::vec::Vec<Option<Value<'static>>> =
1615            alloc::vec::Vec::with_capacity(table.row_count());
1616        for (ri, row) in table.rows().iter().enumerate() {
1617            if !table.is_row_visible(ri, &scan_snapshot) {
1618                new_values.push(None);
1619                continue;
1620            }
1621            let raw = match &using {
1622                Some(expr) => eval::eval_expr(expr, row, &ctx).map_err(|e| {
1623                    EngineError::Unsupported(alloc::format!(
1624                        "ALTER COLUMN TYPE: USING expression failed: {e:?}"
1625                    ))
1626                })?,
1627                None => row.values.get(col_pos).cloned().unwrap_or(Value::Null),
1628            };
1629            // v7.39 — PG's ALTER TYPE without USING applies the
1630            // assignment cast, which is wider than INSERT's strict
1631            // coercion: any value casts to the text family through
1632            // its output function (INT -> TEXT rewrites the column),
1633            // while a narrowing like TEXT -> INT is refused with
1634            // PG's phrasing + HINT. A USING expression bypasses this
1635            // (its result must strictly coerce).
1636            let coerced = match coerce_value(raw.clone(), new_data_type, &column, col_pos) {
1637                Ok(v) => v,
1638                Err(_)
1639                    if using.is_none()
1640                        && matches!(
1641                            new_data_type,
1642                            DataType::Text | DataType::Varchar(_) | DataType::Char(_)
1643                        ) =>
1644                {
1645                    coerce_value(
1646                        Value::text(crate::eval::value_to_text(&raw)),
1647                        new_data_type,
1648                        &column,
1649                        col_pos,
1650                    )?
1651                }
1652                Err(e) => {
1653                    if using.is_none() {
1654                        return Err(EngineError::Unsupported(alloc::format!(
1655                            "column \"{column}\" cannot be cast automatically to type \
1656                             {new_data_type:?}; You might need to specify a USING expression"
1657                        )));
1658                    }
1659                    return Err(e);
1660                }
1661            };
1662            new_values.push(Some(coerced));
1663        }
1664        table.schema_mut().columns[col_pos].ty = new_data_type;
1665        // v7.39 (round 713) — the collation lands with the type, exactly
1666        // as CREATE TABLE lands it (the round-370/676 pair of fields).
1667        // An absent clause is a RESET, not a keep: PG re-derives the
1668        // collation from the new type, so `TYPE text` alone takes the
1669        // column back to the default — under the MySQL dialect that
1670        // default is the folding collation, everywhere else byte order.
1671        {
1672            let sc = &mut table.schema_mut().columns[col_pos];
1673            match &collation {
1674                Some((cenum, name)) => {
1675                    sc.collation_name = Some(name.clone());
1676                    sc.collation = match cenum {
1677                        spg_sql::ast::Collation::Binary => spg_storage::Collation::Binary,
1678                        spg_sql::ast::Collation::CaseInsensitive => {
1679                            spg_storage::Collation::CaseInsensitive
1680                        }
1681                    };
1682                }
1683                None => {
1684                    sc.collation_name = None;
1685                    sc.collation = if mysql_dialect && is_collatable {
1686                        spg_storage::Collation::CaseInsensitive
1687                    } else {
1688                        spg_storage::Collation::Binary
1689                    };
1690                }
1691            }
1692        }
1693        for (i, v) in new_values.into_iter().enumerate() {
1694            let Some(v) = v else { continue };
1695            let mut row_values = table
1696                .rows()
1697                .get(i)
1698                .expect("bounds-checked above")
1699                .values
1700                .clone();
1701            row_values[col_pos] = v;
1702            table.update_row(i, row_values)?;
1703        }
1704        Ok(())
1705    }
1706
1707    /// v7.39 (round 652) — `ALTER TABLE … VALIDATE CONSTRAINT <name>`.
1708    /// Scans the rows against a CHECK added `NOT VALID`; on success the
1709    /// constraint becomes validated and `pg_constraint.convalidated`
1710    /// flips, which is what makes the next pg_dump stop emitting the
1711    /// `NOT VALID` suffix. Validating an already-valid constraint is a
1712    /// no-op, as in PG.
1713    fn alter_validate_constraint(&mut self, tbl: &str, name: &str) -> Result<(), EngineError> {
1714        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1715            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1716        })?;
1717        let names = crate::system_catalog::pg_check_connames(table, tbl, &table.schema().checks);
1718        let Some(idx) = names.iter().position(|n| n.eq_ignore_ascii_case(name)) else {
1719            // PG names the relation it looked in. A constraint that is
1720            // not a CHECK lands here too — SPG has no unvalidated shape
1721            // for the others, so there is nothing this could validate.
1722            return Err(EngineError::Unsupported(alloc::format!(
1723                "constraint \"{name}\" of relation \"{tbl}\" does not exist"
1724            )));
1725        };
1726        if table.schema().checks[idx].validated {
1727            return Ok(());
1728        }
1729        let src = table.schema().checks[idx].expr.clone();
1730        crate::constraints::validate_check_against_existing_rows(table, tbl, name, &src)?;
1731        table.schema_mut().checks[idx].validated = true;
1732        Ok(())
1733    }
1734
1735    #[allow(clippy::too_many_lines)]
1736    fn alter_add_table_constraint(
1737        &mut self,
1738        tbl: &str,
1739        tc: spg_sql::ast::TableConstraint,
1740    ) -> Result<(), EngineError> {
1741        // v7.14.0 — pg_dump emits PKs as a separate
1742        // ALTER TABLE ADD CONSTRAINT post-CREATE-TABLE.
1743        // For PRIMARY KEY / UNIQUE, install a UC entry
1744        // and the implicit BTree index on the leading
1745        // column. CHECK: append predicate to schema.
1746        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
1747            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
1748        })?;
1749        let is_pk = matches!(tc, spg_sql::ast::TableConstraint::PrimaryKey { .. });
1750        // v7.39 (read01 round 48) — a constraint name must be unique on the
1751        // table. PG rejects a re-used name with 42710; SPG used to drop the
1752        // name on the floor entirely, so the collision was invisible.
1753        let con_name: Option<String> = match &tc {
1754            spg_sql::ast::TableConstraint::PrimaryKey { name, .. }
1755            | spg_sql::ast::TableConstraint::Unique { name, .. }
1756            | spg_sql::ast::TableConstraint::Check { name, .. } => name.clone(),
1757            _ => None,
1758        };
1759        if let Some(n) = &con_name
1760            && constraint_name_taken(table, n)
1761        {
1762            return Err(EngineError::Unsupported(alloc::format!(
1763                "constraint {n:?} for relation {tbl:?} already exists"
1764            )));
1765        }
1766        // v7.39 (read01 round 45) — a table may have at most one PRIMARY
1767        // KEY. PG rejects a second one (even on the same column) with
1768        // 42P16; SPG used to install it silently. SPG's own dumps emit PK
1769        // inline, so restore never reaches this ALTER path.
1770        if is_pk
1771            && table
1772                .schema()
1773                .uniqueness_constraints
1774                .iter()
1775                .any(|u| u.is_primary_key)
1776        {
1777            return Err(EngineError::Unsupported(alloc::format!(
1778                "multiple primary keys for table {tbl:?} are not allowed"
1779            )));
1780        }
1781        // v7.22 (mailrs round-13 gap 6) — carry the parsed
1782        // NULLS NOT DISTINCT flag through the ALTER path;
1783        // it was hardcoded false here while the CREATE
1784        // TABLE path honoured it since v7.13.
1785        let nnd = matches!(
1786            tc,
1787            spg_sql::ast::TableConstraint::Unique {
1788                nulls_not_distinct: true,
1789                ..
1790            }
1791        );
1792        // v7.39 (round 711) — carry the timing through the ALTER path too.
1793        let timing = match tc {
1794            spg_sql::ast::TableConstraint::PrimaryKey {
1795                deferrable,
1796                initially_deferred,
1797                ..
1798            }
1799            | spg_sql::ast::TableConstraint::Unique {
1800                deferrable,
1801                initially_deferred,
1802                ..
1803            } => (deferrable, initially_deferred),
1804            _ => (false, false),
1805        };
1806        match tc {
1807            spg_sql::ast::TableConstraint::PrimaryKey { columns, .. }
1808            | spg_sql::ast::TableConstraint::Unique { columns, .. } => {
1809                let positions: Vec<usize> = columns
1810                    .iter()
1811                    .map(|c| {
1812                        table
1813                            .schema()
1814                            .columns
1815                            .iter()
1816                            .position(|sc| sc.name.eq_ignore_ascii_case(c))
1817                            .ok_or_else(|| {
1818                                EngineError::Unsupported(alloc::format!(
1819                                    "ALTER TABLE ADD CONSTRAINT: column {c:?} not found on {:?}",
1820                                    tbl
1821                                ))
1822                            })
1823                    })
1824                    .collect::<Result<Vec<_>, _>>()?;
1825                // Skip if an equivalent UC is already there
1826                // (idempotent — pg_dump's PK + a prior inline
1827                // PK shouldn't double-install).
1828                let already = table
1829                    .schema()
1830                    .uniqueness_constraints
1831                    .iter()
1832                    .any(|u| u.columns == positions);
1833                if !already {
1834                    table.schema_mut().uniqueness_constraints.push(
1835                        spg_storage::UniquenessConstraint {
1836                            is_primary_key: is_pk,
1837                            columns: positions.clone(),
1838                            nulls_not_distinct: nnd,
1839                            name: con_name.clone(),
1840                            deferrable: timing.0,
1841                            initially_deferred: timing.1,
1842                        },
1843                    );
1844                    // PK implies NOT NULL on referenced cols.
1845                    if is_pk {
1846                        for p in &positions {
1847                            if let Some(c) = table.schema_mut().columns.get_mut(*p) {
1848                                c.nullable = false;
1849                            }
1850                        }
1851                    }
1852                    // Add a BTree index on the leading
1853                    // column for INSERT-side enforcement.
1854                    let leading = &columns[0];
1855                    let already_idx = table.indices().iter().any(|idx| {
1856                        matches!(idx.kind, spg_storage::IndexKind::BTree(_))
1857                            && table.schema().columns[idx.column_position].name == *leading
1858                    });
1859                    if !already_idx {
1860                        let suffix = if is_pk { "pkey" } else { "key" };
1861                        let idx_name = alloc::format!("{}_{leading}_{suffix}", tbl);
1862                        let _ = table.add_index(idx_name.clone(), leading);
1863                        // v7.39.13 — which of the two this index is.
1864                        //
1865                        // A SINGLE-column constraint's index covers the
1866                        // whole key, so it IS the constraint's index. For a
1867                        // COMPOSITE one this covers the leading column
1868                        // only: a probe SPG builds because a composite
1869                        // B-tree cannot answer a lookup that does not start
1870                        // at its front, and one PostgreSQL has no
1871                        // equivalent of. Recorded, because the catalog
1872                        // otherwise has to guess from columns or a name —
1873                        // and guessing renamed a user's own index and
1874                        // called an expression index the primary key.
1875                        if let Some(ix) =
1876                            table.indices_mut().iter_mut().find(|i| i.name == idx_name)
1877                        {
1878                            if columns.len() >= 2 {
1879                                ix.constraint_internal = true;
1880                            } else {
1881                                ix.constraint_backing = true;
1882                            }
1883                        }
1884                    }
1885                }
1886            }
1887            spg_sql::ast::TableConstraint::Check {
1888                expr, not_valid, ..
1889            } => {
1890                let src = alloc::format!("{expr}");
1891                // v7.39 (round 652) — PG scans the rows already in the
1892                // table unless the user wrote NOT VALID, and refuses the
1893                // whole ALTER if any of them violates the predicate. SPG
1894                // used to skip that scan unconditionally, so it accepted
1895                // constraints PG rejects and left the table holding rows
1896                // that contradict its own declared CHECK — with every
1897                // reader, pg_dump included, believing otherwise.
1898                if !not_valid {
1899                    // The name PG puts in the message is the one the
1900                    // constraint would end up with, dedup suffix included,
1901                    // so ask for the whole prospective list and take the
1902                    // entry the new one occupies.
1903                    let mut prospective = table.schema().checks.clone();
1904                    prospective.push(spg_storage::CheckConstraint {
1905                        name: con_name.clone(),
1906                        expr: src.clone(),
1907                        validated: true,
1908                    });
1909                    let conname =
1910                        crate::system_catalog::pg_check_connames(table, tbl, &prospective)
1911                            .pop()
1912                            .unwrap_or_else(|| alloc::format!("{tbl}_check"));
1913                    crate::constraints::validate_check_against_existing_rows(
1914                        table, tbl, &conname, &src,
1915                    )?;
1916                }
1917                table
1918                    .schema_mut()
1919                    .checks
1920                    .push(spg_storage::CheckConstraint {
1921                        name: con_name.clone(),
1922                        expr: src,
1923                        validated: !not_valid,
1924                    });
1925            }
1926            spg_sql::ast::TableConstraint::Index { name, columns } => {
1927                // v7.15.0 — ALTER TABLE ADD KEY (cols).
1928                // mysqldump occasionally emits this
1929                // post-CREATE-TABLE shape; build a BTree
1930                // on the leading column using the
1931                // user-supplied or synthesised name.
1932                //
1933                // v7.39 (round 431) — the outcome now matches a measured
1934                // MariaDB 11 run in three ways it did not before:
1935                //   * a second index on an already-indexed column is
1936                //     BUILT, not skipped. Skipping it made the following
1937                //     `DROP INDEX <that name>` fail with "does not
1938                //     exist" — the name was never registered.
1939                //   * a name collision raises 42710 (MariaDB: 1061
1940                //     "Duplicate key name") instead of being swallowed.
1941                //   * an unknown column raises 42703 (MariaDB: 1072 "Key
1942                //     column doesn't exist in table") instead of being
1943                //     swallowed into a no-op.
1944                let leading = &columns[0];
1945                let idx_name = match name {
1946                    Some(n) => n.clone(),
1947                    // Unnamed `ADD INDEX (col)` takes the column's own
1948                    // name, with `_2`, `_3`, … on collision — measured
1949                    // on MariaDB 11.
1950                    None => {
1951                        let mut candidate = leading.clone();
1952                        let mut n = 1;
1953                        while table.indices().iter().any(|idx| idx.name == candidate) {
1954                            n += 1;
1955                            candidate = alloc::format!("{leading}_{n}");
1956                        }
1957                        candidate
1958                    }
1959                };
1960                table
1961                    .add_index(idx_name, leading)
1962                    .map_err(EngineError::Storage)?;
1963            }
1964            spg_sql::ast::TableConstraint::FulltextIndex { name, columns } => {
1965                // v7.17.0 Phase 2.2 — ALTER TABLE ADD
1966                // FULLTEXT KEY (cols). Builds one
1967                // fulltext-GIN per named column so MATCH
1968                // AGAINST gets a real inverted index.
1969                // Multi-column declarations expand to
1970                // per-column GINs (the leading column
1971                // drives MATCH AGAINST planning).
1972                for (k, col) in columns.iter().enumerate() {
1973                    let already_idx = table.indices().iter().any(|idx| {
1974                        matches!(idx.kind, spg_storage::IndexKind::GinFulltext(_))
1975                            && table.schema().columns[idx.column_position].name == *col
1976                    });
1977                    if already_idx {
1978                        continue;
1979                    }
1980                    let idx_name = match (&name, columns.len(), k) {
1981                        (Some(n), 1, _) => n.clone(),
1982                        (Some(n), _, k) => alloc::format!("{n}_{k}"),
1983                        (None, _, _) => {
1984                            alloc::format!("{}_{col}_ftidx", tbl)
1985                        }
1986                    };
1987                    let _ = table.add_gin_fulltext_index(idx_name, col);
1988                }
1989            }
1990            spg_sql::ast::TableConstraint::Exclude {
1991                name,
1992                method,
1993                elements,
1994            } => {
1995                // v7.39 (round 210/211) — ALTER TABLE ADD EXCLUDE. Resolve
1996                // element columns to positions and synthesise PG's
1997                // `<table>_<col…>_excl` name (ALL element columns joined by
1998                // `_`, e.g. `book_room_during_excl`) when unnamed.
1999                let mut els = Vec::with_capacity(elements.len());
2000                let cols_joined = elements
2001                    .iter()
2002                    .map(|(c, _)| c.clone())
2003                    .collect::<Vec<_>>()
2004                    .join("_");
2005                for (col, op) in elements {
2006                    let pos = table
2007                        .schema()
2008                        .columns
2009                        .iter()
2010                        .position(|c| c.name.eq_ignore_ascii_case(&col))
2011                        .ok_or_else(|| {
2012                            EngineError::Unsupported(alloc::format!(
2013                                "ALTER TABLE ADD EXCLUDE: column {col:?} not found on {tbl:?}"
2014                            ))
2015                        })?;
2016                    els.push((pos, op));
2017                }
2018                let ex_name = name.unwrap_or_else(|| alloc::format!("{tbl}_{cols_joined}_excl"));
2019                table
2020                    .schema_mut()
2021                    .exclusion_constraints
2022                    .push(spg_storage::ExclusionConstraint {
2023                        name: ex_name,
2024                        method,
2025                        elements: els,
2026                    });
2027            }
2028        }
2029        Ok(())
2030    }
2031
2032    fn alter_drop_column(
2033        &mut self,
2034        tbl: &str,
2035        column: String,
2036        if_exists: bool,
2037        cascade: bool,
2038    ) -> Result<(), EngineError> {
2039        // v7.13.3 — mailrs round-7 S8. Remove the column +
2040        // every row's value at that position; drop any index
2041        // on the column. RESTRICT (default) rejects when an
2042        // FK on this table or partial-index predicate
2043        // references the column; CASCADE removes those
2044        // dependents first.
2045        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
2046            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
2047        })?;
2048        let col_pos = match table
2049            .schema()
2050            .columns
2051            .iter()
2052            .position(|c| c.name.eq_ignore_ascii_case(&column))
2053        {
2054            Some(p) => p,
2055            None => {
2056                if if_exists {
2057                    // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
2058                    self.notice(alloc::format!(
2059                        "column {column:?} of relation {:?} does not exist, skipping",
2060                        tbl
2061                    ));
2062                    return Ok(());
2063                }
2064                // v7.39 (read01 round 45) — PG wording (42703 at the wire).
2065                return Err(EngineError::Unsupported(alloc::format!(
2066                    "column {column:?} of relation {:?} does not exist",
2067                    tbl
2068                )));
2069            }
2070        };
2071        // Dependent check: FKs whose local columns include
2072        // col_pos. CASCADE drops them; otherwise reject.
2073        let dependent_fks: Vec<usize> = table
2074            .schema()
2075            .foreign_keys
2076            .iter()
2077            .enumerate()
2078            .filter_map(|(i, fk)| {
2079                if fk.local_columns.contains(&col_pos) {
2080                    Some(i)
2081                } else {
2082                    None
2083                }
2084            })
2085            .collect();
2086        if !dependent_fks.is_empty() && !cascade {
2087            return Err(EngineError::Unsupported(alloc::format!(
2088                "ALTER TABLE DROP COLUMN {column:?}: column has FK dependents; \
2089                         use DROP COLUMN ... CASCADE to remove them"
2090            )));
2091        }
2092        // CASCADE the FK removals first.
2093        if cascade {
2094            // Drop in reverse so indices stay valid.
2095            let mut sorted = dependent_fks.clone();
2096            sorted.sort();
2097            sorted.reverse();
2098            let fks = &mut table.schema_mut().foreign_keys;
2099            for i in sorted {
2100                fks.remove(i);
2101            }
2102        }
2103        // v7.38.2 (sentori report 5) — PG's ALTER TABLE rule: "Indexes
2104        // and table constraints involving the column will be
2105        // automatically dropped as well." A CHECK left behind after its
2106        // column made the table permanently un-insertable (every later
2107        // INSERT hit ColumnNotFound on the ghost column). Any CHECK
2108        // whose expression references the dropped column goes with it;
2109        // an expression we can't parse can't be evaluated either way,
2110        // so it is kept untouched.
2111        let dropped = table.schema().columns[col_pos].name.clone();
2112        table.schema_mut().checks.retain(|chk| {
2113            let Ok(expr) = spg_sql::parser::parse_expression(&chk.expr) else {
2114                return true;
2115            };
2116            let mut involves = false;
2117            crate::visit_expr_columns_and_subqueries(
2118                &expr,
2119                &mut |c: &spg_sql::ast::ColumnName| {
2120                    if c.name.eq_ignore_ascii_case(&dropped) {
2121                        involves = true;
2122                    }
2123                },
2124                &mut |_| {},
2125            );
2126            !involves
2127        });
2128        // Drop the column. New helper on Table does the
2129        // row + schema + index shift atomically.
2130        table.drop_column(col_pos);
2131        Ok(())
2132    }
2133
2134    fn alter_set_trigger_enabled(
2135        &mut self,
2136        tbl: &str,
2137        which: spg_sql::ast::TriggerSelector,
2138        enabled: bool,
2139    ) -> Result<(), EngineError> {
2140        // v7.16.1 — mailrs round-9 A.2.b. pg_dump
2141        // --disable-triggers wraps each table's data
2142        // block with `ALTER TABLE … DISABLE TRIGGER ALL`
2143        // / `… ENABLE TRIGGER ALL`. Toggle the enabled
2144        // flag on every matching trigger so the row-
2145        // write paths skip them; the catalog snapshot
2146        // persists the new state across restarts.
2147        let table_name = tbl.to_string();
2148        let trigs = self.active_catalog_mut().triggers_mut();
2149        let mut touched = false;
2150        for t in trigs.iter_mut() {
2151            if !t.table.eq_ignore_ascii_case(&table_name) {
2152                continue;
2153            }
2154            match &which {
2155                spg_sql::ast::TriggerSelector::All => {
2156                    t.enabled = enabled;
2157                    touched = true;
2158                }
2159                spg_sql::ast::TriggerSelector::Named(name) => {
2160                    if t.name.eq_ignore_ascii_case(name) {
2161                        t.enabled = enabled;
2162                        touched = true;
2163                    }
2164                }
2165            }
2166        }
2167        // PG semantics: `ALL` on a table with no
2168        // triggers is a no-op (no error). A `Named`
2169        // form pointing at a non-existent trigger
2170        // raises in PG; v7.16.1 also raises so we
2171        // don't silently lose state.
2172        if !touched {
2173            if let spg_sql::ast::TriggerSelector::Named(name) = &which {
2174                return Err(EngineError::Unsupported(alloc::format!(
2175                    "ALTER TABLE {table_name:?} {} TRIGGER {name:?}: no such trigger on table",
2176                    if enabled { "ENABLE" } else { "DISABLE" },
2177                )));
2178            }
2179        }
2180        Ok(())
2181    }
2182
2183    fn alter_set_column_auto_increment(
2184        &mut self,
2185        tbl: &str,
2186        column: String,
2187        seq_name: Option<String>,
2188    ) -> Result<(), EngineError> {
2189        // pg_dump's identity form names an IMPLICIT sequence
2190        // (`… AS IDENTITY ( SEQUENCE NAME s … )`) that never
2191        // gets its own CREATE SEQUENCE statement, while the
2192        // data section still calls `setval(s, …)`. Make the
2193        // sequence exist (idempotent) so those calls land.
2194        if let Some(seq) = seq_name {
2195            let _ = self.exec_create_sequence(spg_sql::ast::CreateSequenceStatement {
2196                name: seq,
2197                if_not_exists: true,
2198                temporary: false,
2199                data_type: None,
2200                options: spg_sql::ast::SequenceOptions::default(),
2201            })?;
2202        }
2203        // v7.22 (round-13 T2) — pg_dump's serial/identity
2204        // spellings (`SET DEFAULT nextval(…)` / `ADD
2205        // GENERATED … AS IDENTITY`) lower here: flip the
2206        // column's auto-increment flag so post-import
2207        // INSERTs without an explicit value keep numbering
2208        // (max+1 semantics; the dump's setval() calls are
2209        // no-ops by construction).
2210        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
2211            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
2212        })?;
2213        let pos = table
2214            .schema()
2215            .columns
2216            .iter()
2217            .position(|c| c.name.eq_ignore_ascii_case(&column))
2218            .ok_or_else(|| {
2219                EngineError::Unsupported(alloc::format!(
2220                    "ALTER COLUMN {column:?}: no such column on {:?}",
2221                    tbl
2222                ))
2223            })?;
2224        let col = &table.schema().columns[pos];
2225        if !matches!(
2226            col.ty,
2227            spg_storage::DataType::SmallInt
2228                | spg_storage::DataType::Int
2229                | spg_storage::DataType::BigInt
2230        ) {
2231            return Err(EngineError::Unsupported(alloc::format!(
2232                "auto-increment applies to integer columns only ({column:?} is {:?})",
2233                col.ty
2234            )));
2235        }
2236        table.schema_mut().columns[pos].auto_increment = true;
2237        Ok(())
2238    }
2239
2240    /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
2241    /// Only constraints that carry a stored name can be renamed: an unnamed
2242    /// one has no name to change, and its synthesised `pg_constraint` name
2243    /// is derived, not stored. PG's wording here says "for table" (while
2244    /// DROP CONSTRAINT says "of relation") — matched verbatim.
2245    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
2246    /// The object must exist (PG errors otherwise); `IS NULL` removes the
2247    /// comment. Stored in the catalog's comment map under `"<kind>:<name>"`
2248    /// and read back by obj_description / col_description / pg_description.
2249    pub(crate) fn exec_comment_on(
2250        &mut self,
2251        kind: &str,
2252        name: &str,
2253        comment: Option<&str>,
2254    ) -> Result<QueryResult, EngineError> {
2255        let cat = self.active_catalog();
2256        // Validate existence for the kinds SPG catalogues. PG's wording for a
2257        // missing relation is "relation \"x\" does not exist" (42P01).
2258        match kind {
2259            "table" | "view" => {
2260                if cat.get(name).is_none() {
2261                    return Err(EngineError::Unsupported(alloc::format!(
2262                        "relation {name:?} does not exist"
2263                    )));
2264                }
2265            }
2266            "column" => {
2267                let (tbl, col) = name.split_once('.').ok_or_else(|| {
2268                    EngineError::Unsupported(alloc::format!("column {name:?} does not exist"))
2269                })?;
2270                let t = cat.get(tbl).ok_or_else(|| {
2271                    EngineError::Unsupported(alloc::format!("relation {tbl:?} does not exist"))
2272                })?;
2273                if !t
2274                    .schema()
2275                    .columns
2276                    .iter()
2277                    .any(|c| c.name.eq_ignore_ascii_case(col))
2278                {
2279                    return Err(EngineError::Unsupported(alloc::format!(
2280                        "column {col:?} of relation {tbl:?} does not exist"
2281                    )));
2282                }
2283            }
2284            "index" => {
2285                let found = cat.table_names().iter().any(|tn| {
2286                    cat.get(tn)
2287                        .is_some_and(|t| t.indices().iter().any(|i| i.name == name))
2288                });
2289                if !found {
2290                    return Err(EngineError::Unsupported(alloc::format!(
2291                        "relation {name:?} does not exist"
2292                    )));
2293                }
2294            }
2295            "sequence" => {
2296                if !cat.has_sequence(name) {
2297                    return Err(EngineError::Unsupported(alloc::format!(
2298                        "relation {name:?} does not exist"
2299                    )));
2300                }
2301            }
2302            // schema / type / database / function: accepted and stored without
2303            // a catalogue lookup (SPG's registries for these are partial).
2304            _ => {}
2305        }
2306        let key = alloc::format!("{kind}:{name}");
2307        self.active_catalog_mut().set_comment(&key, comment);
2308        Ok(QueryResult::CommandOk {
2309            affected: 0,
2310            modified_catalog: self.catalog_change_is_committed(),
2311        })
2312    }
2313
2314    fn alter_rename_constraint(
2315        &mut self,
2316        tbl: &str,
2317        old: &str,
2318        new: String,
2319    ) -> Result<(), EngineError> {
2320        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
2321            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
2322        })?;
2323        if !constraint_name_taken(table, old) {
2324            return Err(EngineError::Unsupported(alloc::format!(
2325                "constraint {old:?} for table {tbl:?} does not exist"
2326            )));
2327        }
2328        if constraint_name_taken(table, &new) {
2329            return Err(EngineError::Unsupported(alloc::format!(
2330                "constraint {new:?} for relation {tbl:?} already exists"
2331            )));
2332        }
2333        let sch = table.schema_mut();
2334        for f in &mut sch.foreign_keys {
2335            if f.name.as_deref() == Some(old) {
2336                f.name = Some(new);
2337                return Ok(());
2338            }
2339        }
2340        for u in &mut sch.uniqueness_constraints {
2341            if u.name.as_deref() == Some(old) {
2342                u.name = Some(new);
2343                return Ok(());
2344            }
2345        }
2346        for c in &mut sch.checks {
2347            if c.name.as_deref() == Some(old) {
2348                c.name = Some(new);
2349                return Ok(());
2350            }
2351        }
2352        Ok(())
2353    }
2354
2355    fn alter_rename_table(&mut self, tbl: &str, new: String) -> Result<(), EngineError> {
2356        // v7.16.2 — table-level rename (mailrs round-10
2357        // A.5 — used by migrate-042's `ALTER TABLE
2358        // contacts RENAME TO email_contacts`). Storage
2359        // helper updates the schema + by_name index +
2360        // dangling FK / trigger references in one
2361        // atomic step.
2362        let old = tbl.to_string();
2363        // v7.39 (read01 round 47) — PG rejects a rename onto a name that
2364        // already names a relation (42P07), including a rename onto the
2365        // table's own name. SPG used to accept both silently.
2366        if self.active_catalog().get(&new).is_some() {
2367            return Err(EngineError::Unsupported(alloc::format!(
2368                "relation {new:?} already exists"
2369            )));
2370        }
2371        self.active_catalog_mut()
2372            .rename_table(&old, &new)
2373            .map_err(EngineError::Storage)?;
2374        // r192 — carry the non-transactional DML counters to the new
2375        // name (PG keeps stats across a rename). After the storage
2376        // rename succeeded, so a failed rename leaves them keyed as-is.
2377        if let Some(stats) = self.table_write_stats.remove(&old) {
2378            self.table_write_stats.insert(new.clone(), stats);
2379        }
2380        Ok(())
2381    }
2382
2383    fn alter_rename_column(
2384        &mut self,
2385        tbl: &str,
2386        old: String,
2387        new: String,
2388    ) -> Result<(), EngineError> {
2389        // v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO
2390        // new`. Rename the column in the schema; rewrite
2391        // every stored source string on this table that
2392        // references it as a (potentially-qualified)
2393        // column identifier: CHECK predicates, partial-
2394        // index predicates, runtime DEFAULT expressions.
2395        // Then walk catalog triggers on this table and
2396        // patch any `UPDATE OF` column list. Function and
2397        // trigger bodies are NOT auto-rewritten — that
2398        // surface is dynamic SQL territory; users update
2399        // those separately (matches PG plpgsql behavior:
2400        // a column rename invalidates name-referencing
2401        // plpgsql at call time, not rename time).
2402        let table = self.active_catalog_mut().get_mut(tbl).ok_or_else(|| {
2403            EngineError::Storage(StorageError::TableNotFound { name: tbl.into() })
2404        })?;
2405        let col_pos = table
2406            .schema()
2407            .columns
2408            .iter()
2409            .position(|c| c.name.eq_ignore_ascii_case(&old))
2410            .ok_or_else(|| {
2411                // v7.39 (read01 round 47) — PG wording (42703). PG omits
2412                // the "of relation" qualifier on RENAME COLUMN (unlike the
2413                // ALTER COLUMN family below) — match it exactly.
2414                EngineError::Unsupported(alloc::format!("column {old:?} does not exist"))
2415            })?;
2416        // Reject same-name (case-insensitive) collision.
2417        if table
2418            .schema()
2419            .columns
2420            .iter()
2421            .enumerate()
2422            .any(|(i, c)| i != col_pos && c.name.eq_ignore_ascii_case(&new))
2423        {
2424            // v7.39 (read01 round 47) — PG wording (42701).
2425            return Err(EngineError::Unsupported(alloc::format!(
2426                "column {new:?} of relation {:?} already exists",
2427                tbl
2428            )));
2429        }
2430        // Schema rename first — even idempotent same-name
2431        // rename (`ALTER TABLE t RENAME a TO a`) needs to
2432        // be a no-op, not an error.
2433        if old.eq_ignore_ascii_case(&new) {
2434            return Ok(());
2435        }
2436        table.rename_column(col_pos, &new);
2437        // Rewrite per-column runtime_default sources on
2438        // every column of this table — a DEFAULT expression
2439        // on column X may reference column Y by name (rare,
2440        // but legal in PG when the value is supplied via a
2441        // function that takes the row).
2442        let n_cols = table.schema().columns.len();
2443        for i in 0..n_cols {
2444            let rt = table.schema().columns[i].runtime_default.clone();
2445            if let Some(src) = rt {
2446                let rewritten = rewrite_column_in_source(&src, &old, &new)?;
2447                table.schema_mut().columns[i].runtime_default = Some(rewritten);
2448            }
2449        }
2450        // Rewrite table-level CHECK predicates.
2451        let checks = table.schema().checks.clone();
2452        let mut new_checks = Vec::with_capacity(checks.len());
2453        for chk in checks {
2454            // v7.39 (read01 round 48) — rewrite the predicate, keep the name.
2455            new_checks.push(spg_storage::CheckConstraint {
2456                name: chk.name,
2457                expr: rewrite_column_in_source(&chk.expr, &old, &new)?,
2458                // Renaming a column does not re-scan the rows, so it cannot
2459                // turn an unvalidated constraint into a valid one.
2460                validated: chk.validated,
2461            });
2462        }
2463        table.schema_mut().checks = new_checks;
2464        // Rewrite per-index partial_predicate sources.
2465        let n_idx = table.indices().len();
2466        for i in 0..n_idx {
2467            let pred = table.indices()[i].partial_predicate.clone();
2468            if let Some(src) = pred {
2469                let rewritten = rewrite_column_in_source(&src, &old, &new)?;
2470                // SAFETY: indices_mut would be cleanest, but
2471                // partial_predicate is the only mutable field
2472                // here; reach in via the public mut accessor.
2473                table.set_partial_predicate(i, Some(rewritten));
2474            }
2475        }
2476        // Walk catalog triggers; patch `update_columns` on
2477        // triggers attached to this table.
2478        let table_name = tbl.to_string();
2479        for trig in self.active_catalog_mut().triggers_mut() {
2480            if !trig.table.eq_ignore_ascii_case(&table_name) {
2481                continue;
2482            }
2483            for c in &mut trig.update_columns {
2484                if c.eq_ignore_ascii_case(&old) {
2485                    *c = new.clone();
2486                }
2487            }
2488        }
2489        Ok(())
2490    }
2491
2492    /// v6.0.4 — synchronous `ALTER INDEX <name> REBUILD [WITH
2493    /// (encoding = …)]`. Walks every table in the active catalog
2494    /// looking for an index matching `stmt.name`, then delegates the
2495    /// rebuild (including any encoding switch) to
2496    /// `Table::rebuild_nsw_index`. The "live" non-blocking
2497    /// optimisation is v6.0.4.1 / v6.1.x territory.
2498    pub(crate) fn exec_alter_index(
2499        &mut self,
2500        stmt: spg_sql::ast::AlterIndexStatement,
2501    ) -> Result<QueryResult, EngineError> {
2502        // Translate the optional SQL-side encoding choice into the
2503        // storage-side enum; the same SqlVecEncoding -> VecEncoding
2504        // bridge `column_type_to_data_type` uses.
2505        let spg_sql::ast::AlterIndexStatement {
2506            name: idx_name,
2507            target,
2508        } = stmt;
2509        // v7.16.2 — RENAME TO branch (mailrs round-10 migrate-042).
2510        // IF EXISTS makes a missing index a no-op rather than an
2511        // error, mirroring PG semantics.
2512        if let spg_sql::ast::AlterIndexTarget::Rename { new, if_exists } = target {
2513            let renamed = self.active_catalog_mut().rename_index(&idx_name, &new);
2514            return match renamed {
2515                Ok(()) => Ok(QueryResult::CommandOk {
2516                    affected: 0,
2517                    modified_catalog: self.catalog_change_is_committed(),
2518                }),
2519                Err(StorageError::IndexNotFound { .. }) if if_exists => {
2520                    Ok(QueryResult::CommandOk {
2521                        affected: 0,
2522                        modified_catalog: false,
2523                    })
2524                }
2525                // v7.39 (round 700) — PG18 answers `relation "x" does not
2526                // exist` here, not `index "x" …`. An index IS a relation
2527                // there, and the wire classifier reads the relation wording
2528                // for 42P01; SPG's own spelling missed both.
2529                Err(StorageError::IndexNotFound { .. }) => Err(EngineError::Unsupported(
2530                    alloc::format!("relation \"{idx_name}\" does not exist"),
2531                )),
2532                Err(e) => Err(EngineError::Storage(e)),
2533            };
2534        }
2535        // v7.39 (round 710) — SET/RESET storage params: validate the
2536        // index, no-op the parameters (PG resolves the relation first —
2537        // `relation "x" does not exist` — and SPG engine-manages storage
2538        // parameters, as the ALTER TABLE arms already record).
2539        if matches!(target, spg_sql::ast::AlterIndexTarget::StorageParams) {
2540            let cat = self.active_catalog();
2541            let exists = cat.table_names().iter().any(|tn| {
2542                cat.get(tn.as_str())
2543                    .is_some_and(|t| t.indices().iter().any(|i| i.name == idx_name))
2544            });
2545            if !exists {
2546                return Err(EngineError::Unsupported(alloc::format!(
2547                    "relation \"{idx_name}\" does not exist"
2548                )));
2549            }
2550            return Ok(QueryResult::CommandOk {
2551                affected: 0,
2552                modified_catalog: false,
2553            });
2554        }
2555        let spg_sql::ast::AlterIndexTarget::Rebuild { encoding } = target else {
2556            unreachable!("Rename branch returned above");
2557        };
2558        let target = encoding.map(|e| match e {
2559            SqlVecEncoding::F32 => VecEncoding::F32,
2560            SqlVecEncoding::Sq8 => VecEncoding::Sq8,
2561            SqlVecEncoding::F16 => VecEncoding::F16,
2562        });
2563        // Linear scan: index names are globally unique within a
2564        // catalog (enforced by add_nsw_index_inner) so the first
2565        // match is the only one. Save the table name to avoid
2566        // borrowing while we then take a mut borrow.
2567        let table_name = {
2568            let cat = self.active_catalog();
2569            let mut found: Option<String> = None;
2570            for tname in cat.table_names() {
2571                if let Some(t) = cat.get(&tname)
2572                    && t.indices().iter().any(|i| i.name == idx_name)
2573                {
2574                    found = Some(tname);
2575                    break;
2576                }
2577            }
2578            found.ok_or_else(|| {
2579                EngineError::Storage(StorageError::IndexNotFound {
2580                    name: idx_name.clone(),
2581                })
2582            })?
2583        };
2584        let table = self
2585            .active_catalog_mut()
2586            .get_mut(&table_name)
2587            .expect("table found above");
2588        table.rebuild_nsw_index(&idx_name, target)?;
2589        // v6.3.1 — ALTER INDEX REBUILD potentially with new encoding
2590        // changes cost characteristics; evict any cached plans.
2591        self.plan_cache.evict_referencing(&table_name);
2592        Ok(QueryResult::CommandOk {
2593            affected: 0,
2594            modified_catalog: self.catalog_change_is_committed(),
2595        })
2596    }
2597
2598    /// v7.39 (read01 round 93) — derive PG's generated index name for an
2599    /// unnamed `CREATE INDEX`. PG's `ChooseIndexName` builds
2600    /// `<table>_<label1>_<label2>…_idx`, where each label is a key
2601    /// column's name, an expression's leading function name, or `expr`
2602    /// for a non-function expression; INCLUDE columns contribute labels
2603    /// too. On a name clash within the relation an integer counter is
2604    /// appended (`_idx`, `_idx1`, `_idx2`, …).
2605    fn choose_auto_index_name(&self, stmt: &CreateIndexStatement) -> String {
2606        let mut labels: Vec<String> = Vec::new();
2607        match &stmt.expression {
2608            Some(Expr::FunctionCall { name, .. }) => labels.push(name.to_ascii_lowercase()),
2609            Some(_) => labels.push("expr".to_string()),
2610            None => labels.push(stmt.column.clone()),
2611        }
2612        labels.extend(stmt.extra_columns.iter().cloned());
2613        labels.extend(stmt.included_columns.iter().cloned());
2614        let mut base = alloc::format!("{}_{}_idx", stmt.table, labels.join("_"));
2615        // PG truncates the generated name to NAMEDATALEN-1 (63) bytes.
2616        truncate_ident(&mut base);
2617        // Collision counter — index names live in the relation's index
2618        // list (SPG keys index-name uniqueness per table), which is where
2619        // a same-column repeat collides, matching PG's observable output.
2620        let existing: Vec<String> = self
2621            .active_catalog()
2622            .get(&stmt.table)
2623            .map(|t| t.indices().iter().map(|i| i.name.clone()).collect())
2624            .unwrap_or_default();
2625        if !existing.iter().any(|n| *n == base) {
2626            return base;
2627        }
2628        let mut counter = 1u32;
2629        loop {
2630            let mut cand = alloc::format!("{base}{counter}");
2631            truncate_ident(&mut cand);
2632            if !existing.iter().any(|n| *n == cand) {
2633                return cand;
2634            }
2635            counter += 1;
2636        }
2637    }
2638
2639    pub(crate) fn exec_create_index(
2640        &mut self,
2641        mut stmt: CreateIndexStatement,
2642    ) -> Result<QueryResult, EngineError> {
2643        // v7.39 (read01 round 93) — an omitted index name (`CREATE INDEX
2644        // ON t (a)`) is filled in with a PG-style generated name here, so
2645        // the name is chosen against the live catalog (for the collision
2646        // counter). Done before the partition-parent fan-out so children
2647        // inherit a fully-named template.
2648        if stmt.name.is_empty() {
2649            stmt.name = self.choose_auto_index_name(&stmt);
2650        }
2651        // v7.37.6-B(sentori Epic 2 P0)— `CREATE INDEX … ON parent`
2652        // when `parent` is a partition-parent fans out to every
2653        // existing child and records the Display-form source so
2654        // future children also build the same index at creation.
2655        // Parent itself holds no rows, so the build is skipped on
2656        // the parent table.
2657        if crate::partition::is_partition_parent(self.active_catalog(), &stmt.table) {
2658            return self.exec_create_index_on_partition_parent(stmt);
2659        }
2660        // v7.36 — collect cold-tier rows BEFORE taking the mutable
2661        // borrow on the table (the duplicate-scan post-CREATE UNIQUE
2662        // INDEX consumes them). `iter_cold_rows_of_parent` borrows
2663        // the catalog immutably so it would conflict with the
2664        // `active_catalog_mut` borrow below.
2665        let cold_rows_for_unique_scan: alloc::vec::Vec<spg_storage::Row> =
2666            if let Some(t) = self.active_catalog().get(&stmt.table) {
2667                crate::constraints::iter_cold_rows_of_parent(self.active_catalog(), t)
2668            } else {
2669                alloc::vec::Vec::new()
2670            };
2671        let table = self
2672            .active_catalog_mut()
2673            .get_mut(&stmt.table)
2674            .ok_or_else(|| {
2675                EngineError::Storage(StorageError::TableNotFound {
2676                    name: stmt.table.clone(),
2677                })
2678            })?;
2679        // `IF NOT EXISTS` reduces DuplicateIndex to a no-op CommandOk.
2680        if stmt.if_not_exists && table.indices().iter().any(|i| i.name == stmt.name) {
2681            // v7.39 (read01 round 46) — PG's IF NOT EXISTS skip NOTICE
2682            // (an index is a relation, so PG says "relation").
2683            self.notice(alloc::format!(
2684                "relation {:?} already exists, skipping",
2685                stmt.name
2686            ));
2687            return Ok(QueryResult::CommandOk {
2688                affected: 0,
2689                modified_catalog: false,
2690            });
2691        }
2692        // v7.9.14 — multi-column index parses through; engine
2693        // builds a single-column BTree on the leading column only.
2694        // The trailing index columns are resolved + persisted below
2695        // (for every index, not just UNIQUE) so the catalog reports the
2696        // full column list; the BTree still keys on the leading column.
2697        let table_name = stmt.table.clone();
2698        // v6.8.0 — resolve INCLUDE column names to positions. Done
2699        // before `add_index` so a typo error surfaces before any
2700        // catalog mutation lands.
2701        let included_positions: Vec<usize> = if stmt.included_columns.is_empty() {
2702            Vec::new()
2703        } else {
2704            let schema = table.schema();
2705            stmt.included_columns
2706                .iter()
2707                .map(|c| {
2708                    schema.column_position(c).ok_or_else(|| {
2709                        EngineError::Storage(StorageError::ColumnNotFound { column: c.clone() })
2710                    })
2711                })
2712                .collect::<Result<Vec<_>, _>>()?
2713        };
2714        // r1038 — an operator class that does not exist is refused here,
2715        // with PG's wording and its access method.
2716        //
2717        // The parser recognises an opclass by its position, so it no longer
2718        // rejects an unknown NAME as a syntax error the way its old
2719        // eighteen-name whitelist did as a side effect. That whitelist was
2720        // the sentori defect (`jsonb_path_ops` is ordinary PG and did not
2721        // parse); the refusal it was also doing belongs here, where the
2722        // access method is known and the error can carry it.
2723        if let Some(op) = &stmt.opclass
2724            && !crate::opclass::exists_for_access_method(op, stmt.method_name.as_deref())
2725        {
2726            return Err(EngineError::Unsupported(alloc::format!(
2727                "operator class {op:?} does not exist for access method {:?}",
2728                stmt.method_name.as_deref().unwrap_or("btree")
2729            )));
2730        }
2731        // v7.39 (round 475) — an expression key a method cannot take is
2732        // refused BEFORE anything is built.
2733        //
2734        // The check used to run after the index was created, so
2735        // `CREATE INDEX gx ON g USING gin (to_tsvector('simple', doc))`
2736        // raised an error AND left a btree index named `gx` on `doc`
2737        // behind. The message said nothing had happened, the catalog said
2738        // otherwise, and a dump carried an index the user never wrote.
2739        let gin_fulltext_col = match (&stmt.expression, stmt.method) {
2740            (Some(e), IndexMethod::Gin) => tsvector_source_column(e),
2741            _ => None,
2742        };
2743        // v7.38.16 — a GIN index on an expression is PG's ordinary
2744        // spelling for full-text search, and SPG refused it outright:
2745        // `USING gin (to_tsvector('english', title || ' ' || body))` and
2746        // `USING gin (coalesce(title,''))` and `USING gin ((meta ->
2747        // 'tags'))` all failed the DDL, so a customer's schema did not
2748        // load at all. Only `to_tsvector(col)` worked, because
2749        // `tsvector_source_column` recognises a bare column as the last
2750        // argument and nothing else.
2751        //
2752        // The index kind follows the EXPRESSION's result type, since
2753        // there is no column whose type could decide it.
2754        let gin_expr_kind = match (&stmt.expression, stmt.method) {
2755            // Every GIN expression key, including `to_tsvector(col)`.
2756            // That one used to route to the MySQL FULLTEXT posting list,
2757            // which tokenises with the `simple` rule — so a query written
2758            // `to_tsvector('english', body) @@ to_tsquery('english','lazy')`
2759            // looked for the stem `lazi` in a list that held `lazy`, found
2760            // nothing, and returned NO ROWS where the same query without
2761            // the index returned one. Keying on the evaluated tsvector
2762            // puts the query's own configuration in the index.
2763            (Some(e), IndexMethod::Gin) => {
2764                crate::describe::describe_expr_type(e, &table.schema().columns)
2765            }
2766            _ => None,
2767        };
2768        if let Some(key_expr) = &stmt.expression
2769            && gin_fulltext_col.is_none()
2770            && gin_expr_kind.is_none()
2771            && matches!(
2772                stmt.method,
2773                IndexMethod::Hnsw | IndexMethod::Brin | IndexMethod::Gin
2774            )
2775        {
2776            // The old wording named HNSW and BRIN while also covering GIN,
2777            // so a refused GIN index reported two methods it was not.
2778            let method = match stmt.method {
2779                IndexMethod::Hnsw => "HNSW",
2780                IndexMethod::Brin => "BRIN",
2781                _ => "GIN",
2782            };
2783            return Err(EngineError::Unsupported(alloc::format!(
2784                "expression keys are not supported on {method} indexes: {key_expr}"
2785            )));
2786        }
2787        if let Some(ty) = gin_expr_kind {
2788            // The expression's own type picks the posting-list shape.
2789            // `column_position` still names the expression's leading
2790            // column so the catalog stays well-formed; the ENTRIES come
2791            // from `expr_index::refresh` below, never from that column.
2792            let anchor = stmt.column.clone();
2793            match ty {
2794                spg_storage::DataType::TsVector => table
2795                    .add_gin_index_on_expression(stmt.name.clone(), &anchor)
2796                    .map_err(EngineError::Storage)?,
2797                spg_storage::DataType::Json | spg_storage::DataType::Jsonb => table
2798                    .add_gin_jsonb_index(stmt.name.clone(), &anchor)
2799                    .map_err(EngineError::Storage)?,
2800                spg_storage::DataType::Text | spg_storage::DataType::Varchar(_) => table
2801                    .add_gin_trgm_index(stmt.name.clone(), &anchor)
2802                    .map_err(EngineError::Storage)?,
2803                _ => {
2804                    return Err(EngineError::Unsupported(alloc::format!(
2805                        "GIN cannot index an expression of type {ty:?}: {}",
2806                        stmt.expression.as_ref().map_or_else(
2807                            alloc::string::String::new,
2808                            alloc::string::ToString::to_string
2809                        )
2810                    )));
2811                }
2812            }
2813        } else if let Some(col) = gin_fulltext_col.clone() {
2814            table
2815                .add_gin_fulltext_index(stmt.name.clone(), &col)
2816                .map_err(EngineError::Storage)?;
2817        } else {
2818            match stmt.method {
2819                IndexMethod::BTree => {
2820                    table.add_index(stmt.name.clone(), &stmt.column)?;
2821                    // v7.38 P0 元机制 A — index has been pushed onto
2822                    // the table's index vector. Tests use this point
2823                    // to race a sealed index against a concurrent
2824                    // read.
2825                    crate::injection_point!("index_build_post_seal", &stmt.name);
2826                }
2827                IndexMethod::Hnsw => {
2828                    if !included_positions.is_empty() {
2829                        return Err(EngineError::Unsupported(
2830                            "INCLUDE columns are not supported on HNSW indexes".into(),
2831                        ));
2832                    }
2833                    table.add_nsw_index(
2834                        stmt.name.clone(),
2835                        &stmt.column,
2836                        spg_storage::NSW_DEFAULT_M,
2837                    )?;
2838                }
2839                // v6.7.1 — BRIN. Pure metadata; no in-memory data.
2840                IndexMethod::Brin => {
2841                    if !included_positions.is_empty() {
2842                        return Err(EngineError::Unsupported(
2843                            "INCLUDE columns are not supported on BRIN indexes".into(),
2844                        ));
2845                    }
2846                    table.add_brin_index(stmt.name.clone(), &stmt.column)?;
2847                }
2848                // v7.12.3 — GIN inverted index. Real posting-list-backed
2849                // GIN when the indexed column is `tsvector`; falls back
2850                // to a BTree on the leading column for any other column
2851                // type so v7.9.26b's `pg_dump` compatibility (GIN on
2852                // JSONB etc. silently loading as BTree) is preserved.
2853                // Operators see the real GIN only where it matters; old
2854                // schemas keep loading.
2855                IndexMethod::Gin => {
2856                    if !included_positions.is_empty() {
2857                        return Err(EngineError::Unsupported(
2858                            "INCLUDE columns are not supported on GIN indexes".into(),
2859                        ));
2860                    }
2861                    let col_pos =
2862                        table
2863                            .schema()
2864                            .column_position(&stmt.column)
2865                            .ok_or_else(|| {
2866                                EngineError::Storage(StorageError::ColumnNotFound {
2867                                    column: stmt.column.clone(),
2868                                })
2869                            })?;
2870                    let col_ty = table.schema().columns[col_pos].ty;
2871                    // v7.15.0 — `gin_trgm_ops` on a TEXT/VARCHAR
2872                    // column dispatches to the real trigram-shingle
2873                    // GIN build (LIKE / similarity acceleration).
2874                    // Other GIN opclasses fall through to the regular
2875                    // tsvector-vs-BTree split below.
2876                    let is_trgm = stmt
2877                        .opclass
2878                        .as_deref()
2879                        .is_some_and(|op| op.eq_ignore_ascii_case("gin_trgm_ops"));
2880                    if is_trgm
2881                        && matches!(
2882                            col_ty,
2883                            spg_storage::DataType::Text | spg_storage::DataType::Varchar(_)
2884                        )
2885                    {
2886                        table
2887                            .add_gin_trgm_index(stmt.name.clone(), &stmt.column)
2888                            .map_err(EngineError::Storage)?;
2889                    } else if col_ty == spg_storage::DataType::TsVector {
2890                        table
2891                            .add_gin_index(stmt.name.clone(), &stmt.column)
2892                            .map_err(EngineError::Storage)?;
2893                    } else if matches!(
2894                        col_ty,
2895                        spg_storage::DataType::Json | spg_storage::DataType::Jsonb
2896                    ) {
2897                        // v7.37.8(sentori Epic 5 P2)— real JSONB-GIN
2898                        // posting list. Pre-7.37.8 the same DDL loaded
2899                        // as a BTree fallback so `pg_dump` scripts that
2900                        // named GIN on JSONB stayed loadable but the
2901                        // posting-list acceleration was missing; the
2902                        // sentori dashboard's `labels @> '...'` queries
2903                        // fell back to full scan. The planner picks
2904                        // this index up via the `@>` seek in
2905                        // `index_access::try_gin_jsonb_seek`.
2906                        table
2907                            .add_gin_jsonb_index(stmt.name.clone(), &stmt.column)
2908                            .map_err(EngineError::Storage)?;
2909                    } else {
2910                        // v7.9.26b BTree fallback — the catalog still
2911                        // gets an index entry on the leading column so
2912                        // pg_dump scripts that name GIN on other column
2913                        // types load clean; query-time gain stays opt-in
2914                        // for tsvector / JSONB callers.
2915                        table.add_index(stmt.name.clone(), &stmt.column)?;
2916                    }
2917                }
2918            }
2919        }
2920        if !included_positions.is_empty()
2921            && let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name)
2922        {
2923            idx.included_columns = included_positions;
2924        }
2925        // v6.8.1 — persist partial-index predicate. Stored as the
2926        // expression's Display form so the catalog snapshot stays
2927        // pure (storage has no spg-sql dependency). The runtime
2928        // maintenance path treats partial indexes identically to
2929        // full indexes for v6.8.1 (over-maintenance is safe; the
2930        // planner-side "use partial when query WHERE implies the
2931        // predicate" pass is STABILITY carve-out).
2932        if let Some(pred_expr) = &stmt.partial_predicate {
2933            let canonical = pred_expr.to_string();
2934            // v7.13.2 — mailrs round-6 S2. PG's `pg_trgm` uses
2935            // `CREATE INDEX … USING gin(col gin_trgm_ops) WHERE …`
2936            // routinely to slim trigram indexes. SPG now persists
2937            // the predicate for GIN / BRIN / HNSW the same way it
2938            // already does for BTree — same v6.8.1 "over-maintain
2939            // is safe; planner-side partial routing is STABILITY
2940            // carve-out" semantics. HNSW carries an additional
2941            // caveat: the predicate isn't applied at index build
2942            // time (would require per-row eval inside the NSW
2943            // construction loop), so the index oversamples; query
2944            // time the WHERE clause still filters correctly.
2945            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
2946                idx.partial_predicate = Some(canonical);
2947            }
2948        }
2949        // v6.8.2 — persist expression index key. Same Display-form
2950        // storage; the runtime maintenance pass evaluates each
2951        // row's expression to derive the index key, but for v6.8.2
2952        // the engine falls through to the bare-column-reference
2953        // path and the expression is preserved for format-layer
2954        // round-trip + future planner work. Carved-out in
2955        // STABILITY § "Out of v6.8".
2956        if let Some(key_expr) = &stmt.expression {
2957            // v7.39 (round 475) — the method check moved above, before
2958            // anything is built.
2959            let canonical = key_expr.to_string();
2960            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
2961                idx.expression = Some(canonical);
2962            }
2963            // v7.38.16 — and now FILL it with the expression's values.
2964            // Until this call the B-tree holds the leading column's
2965            // values, which is what the index was built from and what no
2966            // lookup of `lower(s) = …` could ever match. `refresh` is a
2967            // no-op for a GIN full-text index, whose expression names a
2968            // source column that its own maintenance path already reads.
2969            crate::expr_index::refresh(table)?;
2970        }
2971        // v7.38.18 (S0) — and a locale-collated column index, for the
2972        // same reason: `Table::add_index` deliberately leaves its tree
2973        // EMPTY because only this crate can encode ICU sort keys, so
2974        // without this the index would exist, be skipped by every seek
2975        // (`Table::index_on` declines an incomplete one), and cost
2976        // maintenance for nothing.
2977        crate::expr_index::refresh(table)?;
2978        // v7.9.29 — persist `is_unique` flag on the storage Index.
2979        // Combined with `partial_predicate`, INSERT enforcement
2980        // checks that no other row whose predicate evaluates true
2981        // shares the same indexed key. Parser already rejected
2982        // `UNIQUE` on HNSW / BRIN, so plain BTree here.
2983        // Resolve the trailing index columns to positions and persist
2984        // them on EVERY index, unique or not — the BTree keys on the
2985        // leading column, but the extras drive uniqueness enforcement
2986        // (unique) and the catalog / pg_get_indexdef column list
2987        // (both), so a plain `CREATE INDEX t (a, b)` reports (a, b).
2988        {
2989            let mut extra_positions: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
2990            for col_name in &stmt.extra_columns {
2991                let pos = table
2992                    .schema()
2993                    .columns
2994                    .iter()
2995                    .position(|c| c.name.eq_ignore_ascii_case(col_name))
2996                    .ok_or_else(|| {
2997                        EngineError::Unsupported(alloc::format!(
2998                            "INDEX {:?}: extra column {col_name:?} not in table {:?}",
2999                            stmt.name,
3000                            stmt.table
3001                        ))
3002                    })?;
3003                extra_positions.push(pos);
3004            }
3005            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3006                idx.extra_column_positions = extra_positions;
3007                // v7.39.11 — and each extra's ordering clause, which the
3008                // parser used to drop. See `Index::extra_orders`.
3009                idx.extra_orders = stmt
3010                    .extra_orders
3011                    .iter()
3012                    .map(|o| spg_storage::KeyOrder {
3013                        descending: o.descending,
3014                        nulls_first: o.nulls_first,
3015                    })
3016                    .collect();
3017            }
3018            // v7.38.1 (L12) — a multi-column CREATE INDEX becomes a REAL
3019            // composite B-tree: the key is the whole column tuple, so an
3020            // equality on any prefix seeks instead of filtering a
3021            // leading-column candidate flood. Expression / partial /
3022            // GIN-shaped indexes are declined inside and stay as built;
3023            // the indexdef already printed the full column list either
3024            // way, so nothing catalog-visible changes.
3025            table
3026                .convert_index_to_multi(&stmt.name)
3027                .map_err(EngineError::Storage)?;
3028        }
3029        // v7.39 (round 537) — the key column's ordering clause, as
3030        // written. It changes no lookup; `indexdef` reproduces the DDL,
3031        // and dropping it made `(a DESC NULLS LAST)` read back as `(a)`.
3032        if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3033            idx.descending = stmt.key_order.descending;
3034            idx.nulls_first = stmt.key_order.nulls_first;
3035            idx.collation.clone_from(&stmt.key_collation);
3036        }
3037        if stmt.is_unique {
3038            if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == stmt.name) {
3039                idx.is_unique = true;
3040                // v7.39 (read01 round 52) — NULLS NOT DISTINCT (PG 15+).
3041                idx.nulls_not_distinct = stmt.nulls_not_distinct;
3042            }
3043            // At index-creation time, check the existing rows for
3044            // pre-existing duplicates that would have violated the
3045            // new constraint — otherwise CREATE UNIQUE INDEX would
3046            // silently leave duplicates in place.
3047            let snapshot_indices = table.indices().to_vec();
3048            let mut snapshot_rows: alloc::vec::Vec<spg_storage::Row> =
3049                table.rows().iter().cloned().collect();
3050            // v7.36 (cold-tier coverage) — CREATE UNIQUE INDEX must
3051            // detect a duplicate that would violate the new
3052            // uniqueness contract even when the duplicate is in the
3053            // cold tier; otherwise the constraint declaration
3054            // succeeds but the on-disk segments carry stale
3055            // duplicates and later INSERTs see phantom-conflict
3056            // behaviour. Use the catalog-borrowing variant from
3057            // `constraints` so we don't double-borrow `self` mut.
3058            snapshot_rows.extend(cold_rows_for_unique_scan);
3059            let snapshot_schema = table.schema().clone();
3060            let idx_ref = snapshot_indices
3061                .iter()
3062                .find(|i| i.name == stmt.name)
3063                .expect("just-added index");
3064            // v7.39 (read01 round 52) — the index was already installed above,
3065            // so a validation failure must ROLL IT BACK. PG's CREATE UNIQUE
3066            // INDEX is atomic; SPG used to leave the half-built index in the
3067            // catalog (pg_indexes listed an index that "failed" to create).
3068            if let Err(e) = check_existing_unique_violation(
3069                idx_ref,
3070                &snapshot_schema,
3071                &snapshot_rows,
3072                self.speaks_mysql,
3073            ) {
3074                let name = stmt.name.clone();
3075                self.active_catalog_mut().drop_named_index(&name);
3076                return Err(e);
3077            }
3078        }
3079        // v6.3.1 — adding an index can change the optimal plan for
3080        // any cached query that references this table.
3081        self.plan_cache.evict_referencing(&table_name);
3082        Ok(QueryResult::CommandOk {
3083            affected: 0,
3084            modified_catalog: self.catalog_change_is_committed(),
3085        })
3086    }
3087
3088    /// v7.37.6-B(sentori Epic 2 P0)— `CREATE INDEX … ON parent`
3089    /// fans the index out to every existing child plus records
3090    /// the Display-form source so future children build it too.
3091    /// The parent itself stays index-less because it holds no rows.
3092    fn exec_create_index_on_partition_parent(
3093        &mut self,
3094        stmt: CreateIndexStatement,
3095    ) -> Result<QueryResult, EngineError> {
3096        let parent_name = stmt.table.clone();
3097        // Display-form source (round-trips through fmt::Display)
3098        // → store on parent's PartitionRole::Parent template list.
3099        let template_source = alloc::format!("{stmt}");
3100        let children = crate::partition::children_of_parent(self.active_catalog(), &parent_name);
3101        // Append the template to the parent schema before fanning
3102        // out, so a child whose CREATE FAILS halfway through still
3103        // records the template the user asked for. Idempotency is
3104        // handled at child-create time via `IF NOT EXISTS`.
3105        {
3106            let parent = self
3107                .active_catalog_mut()
3108                .get_mut(&parent_name)
3109                .ok_or_else(|| {
3110                    EngineError::Storage(StorageError::TableNotFound {
3111                        name: parent_name.clone(),
3112                    })
3113                })?;
3114            if let Some(PartitionRole::Parent {
3115                index_template_sources,
3116                ..
3117            }) = parent.schema_mut().partition_role.as_mut()
3118            {
3119                index_template_sources.push(template_source.clone());
3120            }
3121        }
3122        for child in children {
3123            self.execute_partition_index_template(&child, &template_source)?;
3124        }
3125        Ok(QueryResult::CommandOk {
3126            affected: 0,
3127            modified_catalog: self.catalog_change_is_committed(),
3128        })
3129    }
3130
3131    /// v7.13.3 — mailrs round-7 S9. SPG-specific reconciliation
3132    /// for `CREATE TABLE IF NOT EXISTS` when the table already
3133    /// exists. Adds missing columns + inline FKs from the new
3134    /// definition; existing columns / constraints stay untouched.
3135    /// New columns with a `NOT NULL` declaration without a
3136    /// `DEFAULT` are reported as a clear error rather than
3137    /// silently dropped — this is the "fail loud on real
3138    /// incompatibility, fail silent on schema-superset" tradeoff.
3139    fn reconcile_table_if_not_exists(
3140        &mut self,
3141        stmt: CreateTableStatement,
3142    ) -> Result<QueryResult, EngineError> {
3143        let table_name = stmt.name.clone();
3144        let clock = self.clock;
3145        let existing_col_names: alloc::collections::BTreeSet<String> = self
3146            .active_catalog()
3147            .get(&table_name)
3148            .expect("checked above")
3149            .schema()
3150            .columns
3151            .iter()
3152            .map(|c| c.name.to_ascii_lowercase())
3153            .collect();
3154        let row_count = self
3155            .active_catalog()
3156            .get(&table_name)
3157            .expect("checked above")
3158            .row_count();
3159        // Collect missing column defs in source order.
3160        let new_columns: alloc::vec::Vec<spg_sql::ast::ColumnDef> = stmt
3161            .columns
3162            .iter()
3163            .filter(|c| !existing_col_names.contains(&c.name.to_ascii_lowercase()))
3164            .cloned()
3165            .collect();
3166        for col_def in new_columns {
3167            let col_name = col_def.name.clone();
3168            let nullable = col_def.nullable;
3169            let has_default = col_def.default.is_some() || col_def.auto_increment;
3170            let col_schema = column_def_to_schema(col_def, self.speaks_mysql)?;
3171            let fill_value: Value<'static> = if has_default || col_schema.runtime_default.is_some()
3172            {
3173                resolve_column_default_free(&col_schema, clock, None)?
3174            } else if nullable || row_count == 0 {
3175                Value::Null
3176            } else {
3177                return Err(EngineError::Unsupported(alloc::format!(
3178                    "CREATE TABLE IF NOT EXISTS {table_name:?}: reconciling \
3179                     column {col_name:?} requires DEFAULT (existing rows would violate NOT NULL)"
3180                )));
3181            };
3182            let table = self
3183                .active_catalog_mut()
3184                .get_mut(&table_name)
3185                .expect("checked above");
3186            table.add_column(col_schema, fill_value);
3187        }
3188        // Resolve any newly-added inline FKs (column-level
3189        // REFERENCES forms) and install. Skip FKs whose local
3190        // columns we didn't have in the existing table.
3191        let table_cols_now = self
3192            .active_catalog()
3193            .get(&table_name)
3194            .expect("checked above")
3195            .schema()
3196            .columns
3197            .clone();
3198        for fk in stmt.foreign_keys {
3199            // Only install FKs whose every local column resolves
3200            // — older catalogs may have a column the new FK
3201            // references but not the column the new FK declares.
3202            let all_resolved = fk.columns.iter().all(|c| {
3203                table_cols_now
3204                    .iter()
3205                    .any(|sc| sc.name.eq_ignore_ascii_case(c))
3206            });
3207            if !all_resolved {
3208                continue;
3209            }
3210            let already_present = {
3211                let table = self
3212                    .active_catalog()
3213                    .get(&table_name)
3214                    .expect("checked above");
3215                table.schema().foreign_keys.iter().any(|f| {
3216                    f.parent_table.eq_ignore_ascii_case(&fk.parent_table)
3217                        && f.local_columns.len() == fk.columns.len()
3218                })
3219            };
3220            if already_present {
3221                continue;
3222            }
3223            let storage_fk =
3224                resolve_foreign_key(&table_name, &table_cols_now, fk, self.active_catalog())?;
3225            let table = self
3226                .active_catalog_mut()
3227                .get_mut(&table_name)
3228                .expect("checked above");
3229            table.schema_mut().foreign_keys.push(storage_fk);
3230        }
3231        Ok(QueryResult::CommandOk {
3232            affected: 0,
3233            modified_catalog: self.catalog_change_is_committed(),
3234        })
3235    }
3236
3237    /// v7.14.0 — DROP TABLE handler (pg_dump / mysqldump preamble).
3238    pub(crate) fn exec_drop_table(
3239        &mut self,
3240        names: Vec<String>,
3241        if_exists: bool,
3242    ) -> Result<QueryResult, EngineError> {
3243        for name in names {
3244            // v7.39 (round 642) — dropping a partition parent drops its
3245            // partitions with it.
3246            //
3247            // v7.37.6-B refused instead, on the premise that PG needs an
3248            // explicit CASCADE here. Measured on PG18, it does not: a
3249            // plain `DROP TABLE pp` takes pp and every partition, and so
3250            // does the CASCADE spelling. The refusal made the parent
3251            // undroppable by either spelling — `DROP TABLE IF EXISTS pp
3252            // CASCADE` at the head of a script failed, and every
3253            // statement after it failed on the leftovers.
3254            //
3255            // v7.39 (round 645) — inheritance is the other way round.
3256            // Measured on PG18: `DROP TABLE <inheritance parent>` with a
3257            // child is "cannot drop table par because other objects
3258            // depend on it / table ch depends on table par", and the
3259            // child survives. Only a PARTITION parent takes its children
3260            // with it.
3261            if crate::partition::has_inheritance_children(self.active_catalog(), &name) {
3262                let kids = crate::partition::children_of_parent(self.active_catalog(), &name);
3263                return Err(EngineError::Unsupported(alloc::format!(
3264                    "cannot drop table {name} because other objects depend on it\n\
3265                     DETAIL:  table {} depends on table {name}",
3266                    kids.first().map_or("?", |k| k.as_str())
3267                )));
3268            }
3269            // Depth-first: a partition may itself be partitioned, and
3270            // its children have to go before it does.
3271            let mut to_drop = alloc::vec::Vec::new();
3272            let mut frontier = alloc::vec![name.clone()];
3273            while let Some(cur) = frontier.pop() {
3274                for kid in crate::partition::children_of_parent(self.active_catalog(), &cur) {
3275                    frontier.push(kid.clone());
3276                    to_drop.push(kid);
3277                }
3278            }
3279            // Deepest first, so no parent is removed while a child of it
3280            // is still listed.
3281            for kid in to_drop.into_iter().rev() {
3282                let kid_was_temp = self.temp_tables.contains(&kid);
3283                if self.active_catalog_mut().drop_table(&kid) {
3284                    if kid_was_temp {
3285                        self.temp_tables.remove(&kid);
3286                        self.refresh_temp_prefix();
3287                    }
3288                    self.table_write_stats.remove(&kid);
3289                }
3290            }
3291            // v7.39 (round 436) — if this was one of the session's TEMPORARY
3292            // tables, forget it too, so a permanent namesake becomes visible
3293            // again and `end_session` does not chase a gone table.
3294            let was_temp = self.temp_tables.contains(&name);
3295            let dropped = self.active_catalog_mut().drop_table(&name);
3296            if dropped && was_temp {
3297                self.temp_tables.remove(&name);
3298                self.refresh_temp_prefix();
3299            }
3300            if dropped {
3301                // r192 — drop the non-transactional DML counters so a
3302                // later same-named table starts at zero (PG resets
3303                // stats on DROP).
3304                self.table_write_stats.remove(&name);
3305                // v7.39 (read01 round 50) — purge the table's comments (and its
3306                // columns') so a later table of the same name can't inherit them.
3307                self.active_catalog_mut().drop_comments_for("table", &name);
3308            }
3309            if !dropped {
3310                if !if_exists {
3311                    // v7.39 (read01 round 45) — PG wording (42P01 at the wire);
3312                    // PG says "table", not "relation", for DROP TABLE.
3313                    return Err(EngineError::Unsupported(alloc::format!(
3314                        "table {name:?} does not exist"
3315                    )));
3316                }
3317                // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
3318                self.notice(alloc::format!("table {name:?} does not exist, skipping"));
3319            }
3320        }
3321        Ok(QueryResult::CommandOk {
3322            affected: 0,
3323            modified_catalog: self.catalog_change_is_committed(),
3324        })
3325    }
3326
3327    /// v7.14.0 — DROP INDEX handler.
3328    pub(crate) fn exec_drop_index(
3329        &mut self,
3330        name: String,
3331        if_exists: bool,
3332        table: Option<String>,
3333    ) -> Result<QueryResult, EngineError> {
3334        // v7.39.7 — `DROP INDEX i ON t` scopes the drop to `t`, because
3335        // MySQL keys an index name inside its table. Measured on MySQL
3336        // 9.7.2: the index existing on ANOTHER table is `Can't DROP
3337        // 'ix'` (1091), the same answer as no such index, and a missing
3338        // TABLE is 1146 — a different error, so the two are kept apart
3339        // here.
3340        let dropped = if let Some(t) = &table {
3341            match self.active_catalog_mut().drop_named_index_on(t, &name) {
3342                Some(d) => d,
3343                None => {
3344                    return Err(EngineError::Storage(StorageError::TableNotFound {
3345                        name: t.clone(),
3346                    }));
3347                }
3348            }
3349        } else {
3350            self.active_catalog_mut().drop_named_index(&name)
3351        };
3352        if !dropped {
3353            if !if_exists {
3354                return Err(EngineError::Storage(StorageError::IndexNotFound { name }));
3355            }
3356            // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
3357            self.notice(alloc::format!("index {name:?} does not exist, skipping"));
3358        }
3359        Ok(QueryResult::CommandOk {
3360            affected: 0,
3361            modified_catalog: self.catalog_change_is_committed(),
3362        })
3363    }
3364
3365    pub(crate) fn exec_create_table(
3366        &mut self,
3367        mut stmt: CreateTableStatement,
3368    ) -> Result<QueryResult, EngineError> {
3369        // v7.39 — an ENGINE MySQL does not know is refused, as MySQL does.
3370        // The clause was consumed and dropped, so `ENGINE=NONSUCH` built a
3371        // table while `sql_mode` claimed `NO_ENGINE_SUBSTITUTION` — a typo
3372        // in a dump quietly became SPG's storage.
3373        //
3374        // SPG has one storage engine and substitutes for every name in the
3375        // list, so it cannot honour that flag in MySQL's full sense. What
3376        // it can honour is the half a client can act on: a name MySQL
3377        // rejects is rejected here, with MySQL's own message and errno 1286
3378        // (measured on 9.7.2, `ERROR 1286 (42000) Unknown storage engine`).
3379        // Checked before anything is created, so a refused statement leaves
3380        // nothing behind.
3381        if let Some(engine) = &stmt.engine
3382            && !crate::MYSQL_KNOWN_ENGINES
3383                .iter()
3384                .any(|k| k.eq_ignore_ascii_case(engine))
3385        {
3386            return Err(EngineError::Unsupported(alloc::format!(
3387                "Unknown storage engine '{engine}'"
3388            )));
3389        }
3390        // v7.39.2 — a column named twice is refused, which it was not.
3391        //
3392        // `CREATE TABLE t (a int, a int)` built the table. Measured:
3393        // `information_schema.columns` then carried TWO rows named `a`,
3394        // every later reference to that name was ambiguous, and a dump
3395        // of it restores into neither engine. PostgreSQL 18.6 answers
3396        // `column "a" specified more than once`; MySQL 9.7.2 answers
3397        // `ERROR 1060 (42S21) Duplicate column name 'a'`. Six places
3398        // could produce this table and exactly one — ALTER TABLE ADD
3399        // COLUMN — refused it.
3400        //
3401        // Compared case-INSENSITIVELY, which is both engines' answer:
3402        // PG folds an unquoted name, and MySQL's column names never
3403        // distinguish case. Measured on both, `(a int, A int)` is the
3404        // same refusal.
3405        //
3406        // Before anything is created, like the ENGINE check above.
3407        if let Some(dup) = first_duplicate(
3408            stmt.columns.iter().map(|c| c.name.as_str()),
3409            self.speaks_mysql,
3410        ) {
3411            return Err(EngineError::Unsupported(duplicate_column_message(
3412                &dup,
3413                self.speaks_mysql,
3414            )));
3415        }
3416        // The same name twice inside one PRIMARY KEY or UNIQUE list.
3417        // PostgreSQL has its own sentence for this one — measured,
3418        // `column "a" appears twice in primary key constraint` — and
3419        // MySQL reuses 1060.
3420        for tc in &stmt.table_constraints {
3421            let (cols, kind) = match tc {
3422                spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } => {
3423                    (columns, "primary key")
3424                }
3425                spg_sql::ast::TableConstraint::Unique { columns, .. } => (columns, "unique"),
3426                _ => continue,
3427            };
3428            if let Some(dup) = first_duplicate(
3429                cols.iter().map(alloc::string::String::as_str),
3430                self.speaks_mysql,
3431            ) {
3432                return Err(EngineError::Unsupported(if self.speaks_mysql {
3433                    alloc::format!("Duplicate column name '{dup}'")
3434                } else {
3435                    alloc::format!("column \"{dup}\" appears twice in {kind} constraint")
3436                }));
3437            }
3438        }
3439        // v7.39 (round 436) — a TEMPORARY table is created under the calling
3440        // session's namespace prefix and remembered there, so it shadows a
3441        // permanent table of the same name, stays invisible to other
3442        // sessions, and goes away with the session. Everything downstream
3443        // (the whole DDL body, and every later statement) then works on an
3444        // ordinary table: name resolution happens at the ONE place a name
3445        // becomes an index, `Catalog::resolve_index`.
3446        if stmt.temporary {
3447            let logical = stmt.name.clone();
3448            let mangled = self.session_temp_name(&logical);
3449            let mut inner = stmt;
3450            inner.temporary = false;
3451            inner.name = mangled;
3452            let result = self.exec_create_table(inner)?;
3453            self.temp_tables.insert(logical);
3454            self.refresh_temp_prefix();
3455            return Ok(result);
3456        }
3457        if stmt.if_not_exists && self.active_catalog().get(&stmt.name).is_some() {
3458            // v7.39 (read01 round 46) — PG's IF NOT EXISTS skip NOTICE.
3459            self.notice(alloc::format!(
3460                "relation {:?} already exists, skipping",
3461                stmt.name
3462            ));
3463            // v7.16.2 — PG-strict silent no-op (mailrs round-10
3464            // surfaced this). v7.13.3's "reconcile by adding
3465            // missing columns" was friendly for mailrs round-7
3466            // where init-schema's `contacts` and migrate-023's
3467            // CardDAV `contacts` collided; but it ALSO silently
3468            // added columns to existing tables when later
3469            // migrations had a duplicate `CREATE TABLE IF NOT
3470            // EXISTS <t> (different-shape-cols)` shape. mailrs's
3471            // migrate-030 has exactly that — re-declares
3472            // system_config with `key` even though init-schema
3473            // already created it with `config_key`. PG's silent
3474            // no-op leaves system_config at `config_key`;
3475            // v7.13.3 added a phantom `key` column that then
3476            // tripped migrate-040's idempotent rename guard.
3477            // mailrs v1.7.106 ships the proper PG-style
3478            // contacts rename via DO + IF EXISTS, so SPG can
3479            // revert to PG-strict here without re-breaking the
3480            // round-7 case.
3481            return Ok(QueryResult::CommandOk {
3482                affected: 0,
3483                modified_catalog: false,
3484            });
3485        }
3486        // v7.37.6-B(sentori Epic 2 P0)— `CREATE TABLE c PARTITION
3487        // OF parent <bounds>`: the child inherits its column list
3488        // from the parent and gets a `PartitionRole::Range` or
3489        // `Default` tag. Parent-table bookkeeping (index template
3490        // fan-out) runs in `register_partition_child`.
3491        if stmt.partition_of.is_some() {
3492            return self.exec_create_table_partition_of(stmt);
3493        }
3494        let table_name = stmt.name.clone();
3495        // v7.9.13 — pluck the names of any columns marked
3496        // `PRIMARY KEY` inline so the post-create-table pass can
3497        // build an implicit BTree index. mailrs F1.
3498        let inline_pk_columns: Vec<String> = stmt
3499            .columns
3500            .iter()
3501            .filter(|c| c.is_primary_key)
3502            .map(|c| c.name.clone())
3503            .collect();
3504        let like_specs = core::mem::take(&mut stmt.like_specs);
3505        let mut schema = self.build_create_table_schema(
3506            &table_name,
3507            stmt.columns,
3508            &stmt.table_constraints,
3509            stmt.foreign_keys,
3510            &inline_pk_columns,
3511        )?;
3512        // v7.39 (round 531) — expand each `LIKE <table>` in the column
3513        // list. The source's shape lives in the catalog, so the parser
3514        // recorded the clause and it is copied here, at the position it
3515        // was written.
3516        let mut like_indexes: Vec<CreateIndexStatement> = Vec::new();
3517        self.apply_like_specs(&mut schema, &like_specs, &mut like_indexes)?;
3518        // v7.39 (round 645) — `INHERITS (p1, p2)`. Each parent's columns
3519        // land BEFORE the child's own, in the order the parents were
3520        // written, which is the order PG uses and the order
3521        // `pg_inherits.inhseqno` numbers them in.
3522        //
3523        // NOT NULL, DEFAULT and CHECK come with a column; PRIMARY KEY
3524        // and UNIQUE do not — measured on PG18, a child of a table with
3525        // a primary key has no `contype = 'p'` row of its own.
3526        //
3527        // A name the child also declares is not duplicated: PG merges
3528        // the two, keeping one column, and requires the types to agree.
3529        if !stmt.inherits.is_empty() {
3530            let mut merged: Vec<spg_storage::ColumnSchema> = Vec::new();
3531            for parent in &stmt.inherits {
3532                let Some(p) = self.active_catalog().get(parent) else {
3533                    return Err(EngineError::Storage(
3534                        spg_storage::StorageError::TableNotFound {
3535                            name: parent.clone(),
3536                        },
3537                    ));
3538                };
3539                for col in &p.schema().columns {
3540                    if merged
3541                        .iter()
3542                        .any(|c| c.name.eq_ignore_ascii_case(&col.name))
3543                    {
3544                        continue;
3545                    }
3546                    if let Some(own) = schema
3547                        .columns
3548                        .iter()
3549                        .find(|c| c.name.eq_ignore_ascii_case(&col.name))
3550                        && own.ty != col.ty
3551                    {
3552                        return Err(EngineError::Unsupported(alloc::format!(
3553                            "column \"{}\" inherited from \"{parent}\" has type {}                              but the child declares {}",
3554                            col.name,
3555                            crate::conversions::pg_type_name_for_error(col.ty),
3556                            crate::conversions::pg_type_name_for_error(own.ty)
3557                        )));
3558                    }
3559                    merged.push(col.clone());
3560                }
3561            }
3562            // The child's own columns follow, minus any the parents
3563            // already supplied.
3564            for col in &schema.columns {
3565                if !merged
3566                    .iter()
3567                    .any(|c| c.name.eq_ignore_ascii_case(&col.name))
3568                {
3569                    merged.push(col.clone());
3570                }
3571            }
3572            schema.columns = merged;
3573            // v7.39 (round 646) — CHECK constraints inherit too. Measured
3574            // on PG18: a child of a table with `CHECK (a > 0)` gets its
3575            // own `contype = 'c'` row. PRIMARY KEY and UNIQUE do NOT —
3576            // the same probe reads 0 for `contype = 'p'` — so only the
3577            // checks are copied.
3578            //
3579            // A constraint the child already declares by the same name is
3580            // left alone; PG merges the two rather than carrying both.
3581            for parent in &stmt.inherits {
3582                let Some(p) = self.active_catalog().get(parent) else {
3583                    continue;
3584                };
3585                // The NAME travels with the constraint. An unnamed CHECK
3586                // is auto-named per table, so copying it as-is would give
3587                // the child `<child>_a_check` where PG reports the
3588                // parent's `<parent>_a_check` — measured in the violation
3589                // message, which is where a user meets the name. Resolve
3590                // the parent's name once and carry it explicitly.
3591                let names = crate::system_catalog::pg_check_connames(p, parent, &p.schema().checks);
3592                for (ci, (chk, name)) in p.schema().checks.iter().zip(names).enumerate() {
3593                    let dup = schema.checks.iter().any(|c| match (&c.name, &chk.name) {
3594                        (Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
3595                        _ => c.expr == chk.expr,
3596                    });
3597                    if !dup {
3598                        // A child copies the parent's constraint, validation
3599                        // state and all.
3600                        schema.checks.push(spg_storage::CheckConstraint {
3601                            name: Some(name),
3602                            expr: chk.expr.clone(),
3603                            validated: chk.validated,
3604                        });
3605                    }
3606                }
3607            }
3608            schema.partition_role = Some(spg_storage::PartitionRole::Inherits {
3609                parent_names: stmt.inherits.clone(),
3610            });
3611        }
3612        // v7.37.6-B — `CREATE TABLE p (...) PARTITION BY RANGE (key)`:
3613        // attach the parent role to the freshly-built schema before
3614        // it lands in the catalog. Key column must be TIMESTAMPTZ
3615        // at v7.37.6-B (the only sentori shape); other key types are
3616        // a phase-2 carve-out.
3617        if let Some(by) = stmt.partition_by {
3618            let kind = match by.kind {
3619                PartitionKindAst::Range => PartitionKind::Range,
3620                PartitionKindAst::List => PartitionKind::List,
3621                PartitionKindAst::Hash => PartitionKind::Hash,
3622            };
3623            let mut key_column_positions = Vec::with_capacity(by.key_columns.len());
3624            for col_name in &by.key_columns {
3625                let pos = schema
3626                    .columns
3627                    .iter()
3628                    .position(|c| c.name.eq_ignore_ascii_case(col_name))
3629                    .ok_or_else(|| {
3630                        EngineError::Unsupported(alloc::format!(
3631                            "PARTITION BY: key column {col_name:?} not in column list"
3632                        ))
3633                    })?;
3634                // v7.37.16 (16.1/16.2/16.6) — accept the typed PG
3635                // builtins per partition strategy:
3636                //   RANGE → TIMESTAMPTZ / TIMESTAMP / DATE / BIGINT
3637                //           / INTEGER / SMALLINT
3638                //   LIST  → BIGINT / INTEGER / SMALLINT / DATE / TEXT
3639                //   HASH  → BIGINT / INTEGER / SMALLINT / TEXT / DATE
3640                //           / TIMESTAMPTZ
3641                let key_ty = &schema.columns[pos].ty;
3642                let key_ok = matches!(
3643                    key_ty,
3644                    DataType::Timestamptz
3645                        | DataType::Timestamp
3646                        | DataType::Date
3647                        | DataType::BigInt
3648                        | DataType::Int
3649                        | DataType::SmallInt
3650                        | DataType::Text
3651                        | DataType::Varchar(_)
3652                );
3653                if !key_ok {
3654                    return Err(EngineError::Unsupported(alloc::format!(
3655                        "PARTITION BY {:?}: key column {col_name:?} type {key_ty:?} \
3656                         is not yet supported (16.1/16.2/16.6 accept TIMESTAMPTZ, \
3657                         TIMESTAMP, DATE, BIGINT, INTEGER, SMALLINT, TEXT/VARCHAR)",
3658                        kind,
3659                    )));
3660                }
3661                key_column_positions.push(pos);
3662            }
3663            schema.partition_role = Some(PartitionRole::Parent {
3664                kind,
3665                key_column_positions,
3666                index_template_sources: Vec::new(),
3667            });
3668        }
3669        self.active_catalog_mut().create_table(schema)?;
3670        // v7.39 (round 621) — the indexes an `INCLUDING INDEXES` asked for,
3671        // created once the table they sit on exists.
3672        for mut ci in like_indexes {
3673            ci.table = table_name.clone();
3674            self.exec_create_index(ci)?;
3675        }
3676        self.install_implicit_indexes(&table_name, &inline_pk_columns, &stmt.table_constraints)?;
3677        self.install_excl_range_indexes(&table_name);
3678        Ok(QueryResult::CommandOk {
3679            affected: 0,
3680            modified_catalog: self.catalog_change_is_committed(),
3681        })
3682    }
3683
3684    /// v7.37.6-B — child-table branch of `CREATE TABLE`. The parser
3685    /// guarantees `stmt.partition_of.is_some()` + `stmt.columns`
3686    /// is empty before we land here.
3687    fn exec_create_table_partition_of(
3688        &mut self,
3689        stmt: CreateTableStatement,
3690    ) -> Result<QueryResult, EngineError> {
3691        let spec = stmt
3692            .partition_of
3693            .expect("caller checked partition_of.is_some()");
3694        // Lift parent schema bits (columns + partition_role + index
3695        // template list) so we don't trip the active_catalog_mut()
3696        // borrow when we splice the child in.
3697        let (parent_columns, parent_kind, index_template_sources) = {
3698            let parent = self
3699                .active_catalog()
3700                .get(&spec.parent_name)
3701                .ok_or_else(|| {
3702                    EngineError::Storage(StorageError::TableNotFound {
3703                        name: spec.parent_name.clone(),
3704                    })
3705                })?;
3706            match &parent.schema().partition_role {
3707                Some(PartitionRole::Parent {
3708                    kind,
3709                    index_template_sources,
3710                    ..
3711                }) => (
3712                    parent.schema().columns.clone(),
3713                    *kind,
3714                    index_template_sources.clone(),
3715                ),
3716                _ => {
3717                    return Err(EngineError::Unsupported(alloc::format!(
3718                        "CREATE TABLE … PARTITION OF: table {:?} is not a \
3719                         partitioned parent",
3720                        spec.parent_name
3721                    )));
3722                }
3723            }
3724        };
3725        // Resolve bounds before we mutate the catalog so a bad
3726        // literal surfaces before any visible state changes.
3727        let role = match spec.bounds {
3728            PartitionOfBoundsAst::Default => PartitionRole::Default {
3729                parent_name: spec.parent_name.clone(),
3730            },
3731            PartitionOfBoundsAst::Range { lower, upper } => {
3732                let lower_b = crate::partition::evaluate_partition_bound(*lower)?;
3733                let upper_b = crate::partition::evaluate_partition_bound(*upper)?;
3734                // Half-open: lower must be < upper. Same-bound or
3735                // inverted ranges accept no rows in PG; SPG raises
3736                // because every sentori migration shapes intentional
3737                // calendar windows.
3738                if !crate::partition::ranges_overlap(&lower_b, &upper_b, &lower_b, &upper_b) {
3739                    return Err(EngineError::Unsupported(alloc::format!(
3740                        "PARTITION OF: FROM ({}) TO ({}) is empty (lower must be < upper)",
3741                        crate::partition::bound_to_diag(&lower_b),
3742                        crate::partition::bound_to_diag(&upper_b),
3743                    )));
3744                }
3745                // Overlap check against every existing sibling Range
3746                // child of the same parent. DEFAULT siblings don't
3747                // participate(they're a catch-all, not a range).
3748                let siblings =
3749                    crate::partition::children_of_parent(self.active_catalog(), &spec.parent_name);
3750                // Partition-key column of the parent (RANGE uses one key).
3751                let key_pos = match &self
3752                    .active_catalog()
3753                    .get(&spec.parent_name)
3754                    .and_then(|p| p.schema().partition_role.clone())
3755                {
3756                    Some(PartitionRole::Parent {
3757                        key_column_positions,
3758                        ..
3759                    }) => key_column_positions.first().copied().unwrap_or(0),
3760                    _ => 0,
3761                };
3762                for sib in &siblings {
3763                    let Some(t) = self.active_catalog().get(sib) else {
3764                        continue;
3765                    };
3766                    match &t.schema().partition_role {
3767                        Some(PartitionRole::Range {
3768                            lower: sl,
3769                            upper: su,
3770                            ..
3771                        }) => {
3772                            if crate::partition::ranges_overlap(&lower_b, &upper_b, sl, su) {
3773                                return Err(EngineError::Unsupported(alloc::format!(
3774                                    "PARTITION OF: range FROM ({}) TO ({}) overlaps existing \
3775                                     child {sib:?} (FROM ({}) TO ({}))",
3776                                    crate::partition::bound_to_diag(&lower_b),
3777                                    crate::partition::bound_to_diag(&upper_b),
3778                                    crate::partition::bound_to_diag(sl),
3779                                    crate::partition::bound_to_diag(su),
3780                                )));
3781                            }
3782                        }
3783                        // v7.38 (read01) — DEFAULT-partition cross-check:
3784                        // any row already parked in the default partition
3785                        // that falls in the new range means adding it would
3786                        // strand that row in the wrong partition. PG rejects
3787                        // rather than allow the inconsistency.
3788                        Some(PartitionRole::Default { .. }) => {
3789                            for row in t.rows().iter() {
3790                                let Some(v) = row.values.get(key_pos) else {
3791                                    continue;
3792                                };
3793                                if v.is_null() {
3794                                    continue;
3795                                }
3796                                let Some(kb) = crate::partition::value_to_bound(v) else {
3797                                    continue;
3798                                };
3799                                if crate::partition::value_in_range(&kb, &lower_b, &upper_b) {
3800                                    return Err(EngineError::Unsupported(alloc::format!(
3801                                        "updated partition constraint for default partition \
3802                                         {sib:?} would be violated by some row"
3803                                    )));
3804                                }
3805                            }
3806                        }
3807                        _ => {}
3808                    }
3809                }
3810                PartitionRole::Range {
3811                    parent_name: spec.parent_name.clone(),
3812                    lower: lower_b,
3813                    upper: upper_b,
3814                }
3815            }
3816            // v7.37.16 (16.1) — LIST child create.
3817            PartitionOfBoundsAst::List { values } => {
3818                if !matches!(parent_kind, PartitionKind::List) {
3819                    return Err(EngineError::Unsupported(alloc::format!(
3820                        "PARTITION OF: FOR VALUES IN (...) only valid for \
3821                         a LIST-partitioned parent (parent {:?} is {:?})",
3822                        spec.parent_name,
3823                        parent_kind,
3824                    )));
3825                }
3826                let mut bounds = Vec::with_capacity(values.len());
3827                for v in values {
3828                    bounds.push(crate::partition::evaluate_partition_bound(v)?);
3829                }
3830                // Reject duplicate values across siblings (PG raises
3831                // "is already specified in partition X" at create
3832                // time so the dispatch never sees ambiguity).
3833                let siblings =
3834                    crate::partition::children_of_parent(self.active_catalog(), &spec.parent_name);
3835                for sib in &siblings {
3836                    let Some(t) = self.active_catalog().get(sib) else {
3837                        continue;
3838                    };
3839                    if let Some(PartitionRole::List {
3840                        values: existing, ..
3841                    }) = &t.schema().partition_role
3842                    {
3843                        for new_b in &bounds {
3844                            if existing.iter().any(|e| e == new_b) {
3845                                // v7.39 (round 770, F31 tranche 6 #170) —
3846                                // PG's sentence, measured: `partition "b"
3847                                // would overlap partition "a"`.
3848                                let _ = crate::partition::bound_to_diag(new_b);
3849                                return Err(EngineError::Unsupported(alloc::format!(
3850                                    "partition \"{}\" would overlap partition \"{sib}\"",
3851                                    stmt.name,
3852                                )));
3853                            }
3854                        }
3855                    }
3856                }
3857                PartitionRole::List {
3858                    parent_name: spec.parent_name.clone(),
3859                    values: bounds,
3860                }
3861            }
3862            // v7.37.16 (16.2) — HASH child create.
3863            PartitionOfBoundsAst::Hash { modulus, remainder } => {
3864                if !matches!(parent_kind, PartitionKind::Hash) {
3865                    return Err(EngineError::Unsupported(alloc::format!(
3866                        "PARTITION OF: FOR VALUES WITH (MODULUS, REMAINDER) only \
3867                         valid for a HASH-partitioned parent (parent {:?} is {:?})",
3868                        spec.parent_name,
3869                        parent_kind,
3870                    )));
3871                }
3872                if modulus == 0 || remainder >= modulus {
3873                    return Err(EngineError::Unsupported(alloc::format!(
3874                        "PARTITION OF HASH: invalid (MODULUS={modulus}, REMAINDER={remainder}); \
3875                         require modulus > 0 and remainder < modulus",
3876                    )));
3877                }
3878                // Reject duplicate (modulus, remainder) and partial overlap
3879                // (different modulus / same residue class) — PG handles
3880                // multi-modulus by requiring divisibility; we keep it
3881                // simple and demand modulus equality across HASH siblings.
3882                let siblings =
3883                    crate::partition::children_of_parent(self.active_catalog(), &spec.parent_name);
3884                for sib in &siblings {
3885                    let Some(t) = self.active_catalog().get(sib) else {
3886                        continue;
3887                    };
3888                    if let Some(PartitionRole::Hash {
3889                        modulus: m,
3890                        remainder: r,
3891                        ..
3892                    }) = &t.schema().partition_role
3893                    {
3894                        if *m != modulus {
3895                            return Err(EngineError::Unsupported(alloc::format!(
3896                                "PARTITION OF HASH: MODULUS {modulus} differs from \
3897                                 sibling {sib:?} MODULUS {m} (mixed moduli not yet \
3898                                 supported in v7.37.16.2)",
3899                            )));
3900                        }
3901                        if *r == remainder {
3902                            return Err(EngineError::Unsupported(alloc::format!(
3903                                "PARTITION OF HASH: REMAINDER {remainder} already \
3904                                 used by sibling {sib:?}",
3905                            )));
3906                        }
3907                    }
3908                }
3909                PartitionRole::Hash {
3910                    parent_name: spec.parent_name.clone(),
3911                    modulus,
3912                    remainder,
3913                }
3914            }
3915        };
3916        // For DEFAULT children, reject when the parent already has
3917        // one(PG semantics — exactly 0 or 1 DEFAULT per parent).
3918        if matches!(role, PartitionRole::Default { .. }) {
3919            for sib in
3920                crate::partition::children_of_parent(self.active_catalog(), &spec.parent_name)
3921            {
3922                if let Some(t) = self.active_catalog().get(&sib)
3923                    && matches!(
3924                        t.schema().partition_role,
3925                        Some(PartitionRole::Default { .. })
3926                    )
3927                {
3928                    return Err(EngineError::Unsupported(alloc::format!(
3929                        "PARTITION OF DEFAULT: parent {:?} already has a DEFAULT \
3930                         partition ({sib:?})",
3931                        spec.parent_name
3932                    )));
3933                }
3934            }
3935        }
3936        let _ = parent_kind; // v7.37.6-B locks RANGE; future kinds key off this.
3937        let mut schema = TableSchema::new(stmt.name.clone(), parent_columns);
3938        // v7.39 (read01 round 57) — whoever runs CREATE TABLE owns it.
3939        schema.owner = Some(alloc::string::String::from(self.current_role()));
3940        schema.partition_role = Some(role);
3941        self.active_catalog_mut().create_table(schema)?;
3942        // Replay parent's CREATE INDEX templates against the new
3943        // child so every parent-declared index materialises now.
3944        for tmpl in &index_template_sources {
3945            self.execute_partition_index_template(&stmt.name, tmpl)?;
3946        }
3947        Ok(QueryResult::CommandOk {
3948            affected: 0,
3949            modified_catalog: self.catalog_change_is_committed(),
3950        })
3951    }
3952
3953    /// v7.37.6-B — parse a stored `CREATE INDEX ON parent (…)`
3954    /// template and re-execute it against `child_name`(by rewriting
3955    /// the table reference on the AST before dispatch). Used both
3956    /// at child-create time and after `CREATE INDEX ON parent` for
3957    /// existing children.
3958    fn execute_partition_index_template(
3959        &mut self,
3960        child_name: &str,
3961        template_source: &str,
3962    ) -> Result<(), EngineError> {
3963        let stmt = spg_sql::parser::parse_statement(template_source).map_err(EngineError::Parse)?;
3964        let Statement::CreateIndex(mut ci) = stmt else {
3965            return Err(EngineError::Unsupported(alloc::format!(
3966                "PARTITION index template is not CREATE INDEX: {template_source:?}"
3967            )));
3968        };
3969        ci.table = child_name.to_string();
3970        // Name suffix per child so different children don't collide
3971        // on the same `<idx_name>`. Skip when the original index has
3972        // no explicit name(SPG auto-generates).
3973        if !ci.name.is_empty() {
3974            ci.name = alloc::format!("{}__{}", ci.name, child_name);
3975        }
3976        // IF NOT EXISTS to make replay idempotent — when this is
3977        // called from the CREATE INDEX ON parent fan-out we want to
3978        // tolerate the case where a child already has the index
3979        // from an earlier CREATE INDEX run.
3980        ci.if_not_exists = true;
3981        self.exec_create_index(ci)?;
3982        Ok(())
3983    }
3984
3985    /// Build the `TableSchema` for a CREATE TABLE: column schemas with
3986    /// ENUM / DOMAIN bindings resolved, table-level + inline PRIMARY KEY
3987    /// NOT NULL marking, FK resolution (deferring to `pending_foreign_keys`
3988    /// when checks are off and the parent is absent), and uniqueness /
3989    /// CHECK constraint translation.
3990    #[allow(clippy::too_many_lines)]
3991    /// v7.39 (round 531) — copy a source table's shape into the new one.
3992    ///
3993    /// Measured on PG18: a bare `LIKE` copies names, types and NOT NULL
3994    /// and nothing else — a copied generated column becomes a plain one
3995    /// and a copied identity column loses its identity. Each INCLUDING
3996    /// adds one property back, and `INCLUDING ALL` adds them all.
3997    #[allow(clippy::too_many_lines)]
3998    fn apply_like_specs(
3999        &mut self,
4000        schema: &mut spg_storage::TableSchema,
4001        specs: &[spg_sql::ast::LikeSpec],
4002        out_indexes: &mut Vec<CreateIndexStatement>,
4003    ) -> Result<(), EngineError> {
4004        // Applied back to front so an earlier spec's insert position is
4005        // still the one it was written at.
4006        for spec in specs.iter().rev() {
4007            let src = self.active_catalog().get(&spec.source).ok_or_else(|| {
4008                EngineError::Storage(spg_storage::StorageError::TableNotFound {
4009                    name: spec.source.clone(),
4010                })
4011            })?;
4012            let src_schema = src.schema();
4013            let o = spec.options;
4014            let mut copied: Vec<spg_storage::ColumnSchema> = Vec::new();
4015            for c in &src_schema.columns {
4016                let mut col = c.clone();
4017                if !o.defaults {
4018                    col.default = None;
4019                    col.default_text = None;
4020                    col.runtime_default = None;
4021                }
4022                if !o.identity {
4023                    col.auto_increment = false;
4024                    col.identity_always = false;
4025                    col.auto_restart = None;
4026                }
4027                if !o.generated {
4028                    col.generated_stored_expr = None;
4029                }
4030                if !o.comments {
4031                    // Comments live in the catalog's comment map, not on
4032                    // the column, so there is nothing to clear here; the
4033                    // copy below simply does not carry them.
4034                }
4035                copied.push(col);
4036            }
4037            let at = spec.at.min(schema.columns.len());
4038            for (i, col) in copied.into_iter().enumerate() {
4039                schema.columns.insert(at + i, col);
4040            }
4041            if o.constraints {
4042                for chk in &src_schema.checks {
4043                    schema.checks.push(chk.clone());
4044                }
4045            }
4046            // v7.39 (round 621) — INCLUDING INDEXES copies them.
4047            //
4048            // Round 531 refused it rather than dropping them silently, and the
4049            // reason it gave was right: "a table that reports the right columns
4050            // and none of the indexes is the shape that looks fine until it is
4051            // slow". But refusing takes `INCLUDING ALL` down with it, which is
4052            // what schema tools write, so the restore stopped instead.
4053            //
4054            // The index is rebuilt from its own definition rather than copied
4055            // as a structure, so it goes through the same path a written-out
4056            // CREATE INDEX takes. PG names the copies after the new table and
4057            // lets the auto-namer resolve collisions, which is what an empty
4058            // name asks for here.
4059            if o.indexes {
4060                for idx in src.indices() {
4061                    let Some(col) = src_schema.columns.get(idx.column_position) else {
4062                        continue;
4063                    };
4064                    out_indexes.push(CreateIndexStatement {
4065                        concurrently: false,
4066                        name: String::new(),
4067                        key_order: spg_sql::ast::IndexColumnOrder::default(),
4068                        key_collation: None,
4069                        table: String::new(),
4070                        column: col.name.clone(),
4071                        nulls_not_distinct: idx.nulls_not_distinct,
4072                        method: spg_sql::ast::IndexMethod::BTree,
4073                        if_not_exists: false,
4074                        included_columns: Vec::new(),
4075                        partial_predicate: None,
4076                        expression: None,
4077                        extra_columns: Vec::new(),
4078                        extra_orders: Vec::new(),
4079                        is_unique: idx.is_unique,
4080                        opclass: None,
4081                        method_name: None,
4082                    });
4083                }
4084            }
4085        }
4086        Ok(())
4087    }
4088
4089    fn build_create_table_schema(
4090        &mut self,
4091        table_name: &str,
4092        columns: Vec<ColumnDef>,
4093        table_constraints: &[spg_sql::ast::TableConstraint],
4094        foreign_keys: Vec<spg_sql::ast::ForeignKeyConstraint>,
4095        inline_pk_columns: &[String],
4096    ) -> Result<TableSchema, EngineError> {
4097        // v7.39 (round 711) — the inline PK's timing clause, captured
4098        // before `columns` is consumed into the schema below.
4099        let inline_pk_timing: (bool, bool) =
4100            columns
4101                .iter()
4102                .filter(|c| c.is_primary_key)
4103                .fold((false, false), |acc, c| {
4104                    (
4105                        acc.0 | c.constraint_deferrable,
4106                        acc.1 | c.constraint_initially_deferred,
4107                    )
4108                });
4109        // v7.9.19 — table-level constraints: PRIMARY KEY (a, b, ...)
4110        // and UNIQUE (a, b, ...). Each builds a BTree index on the
4111        // leading column (the existing single-column storage tier)
4112        // and registers a UniquenessConstraint on the schema for
4113        // INSERT-time enforcement of the full tuple. mailrs G1/G6.
4114        let mysql = self.speaks_mysql;
4115        let cols = columns
4116            .into_iter()
4117            .map(|c| column_def_to_schema(c, mysql))
4118            .collect::<Result<Vec<_>, _>>()?;
4119        // v7.39 (round 679) — say so when a declared collation is stored but
4120        // not applied.
4121        //
4122        // Round 670 measured three rules colliding here: refusing the DDL
4123        // breaks a customer's pg_dump restore (zero-customer-change), while
4124        // accepting it silently is what F36 records as the defect — the
4125        // declaration taken and ignored. A WARNING is the option that was
4126        // not available then: rounds 676-677 gave the name somewhere to
4127        // live, and round 678 gave `collate::is_supported` a way to say
4128        // whether this build can perform it. The restore still succeeds;
4129        // the gap stops being silent.
4130        //
4131        // SPG performs C and POSIX, so those warn about nothing.
4132        for c in &cols {
4133            let Some(name) = c.collation_name.as_deref() else {
4134                continue;
4135            };
4136            // v7.38.22 — the type has to be able to carry one.
4137            //
4138            // PostgreSQL 18.4 refuses `CREATE TABLE t (c INT COLLATE
4139            // "en_US.utf8")` with 42804; SPG took the declaration and
4140            // stored it, which is the same "taken and ignored" shape F36
4141            // was opened for, one level up — and it then travels into
4142            // every comparison the column takes part in.
4143            if !crate::collate::is_collatable(&c.ty) {
4144                return Err(crate::collate::not_collatable_error(
4145                    crate::eval::pg_typeof_name_for_datatype(c.ty).unwrap_or("unknown"),
4146                ));
4147            }
4148            if crate::collate::is_supported(name)
4149                && (name.eq_ignore_ascii_case("C")
4150                    || name.eq_ignore_ascii_case("POSIX")
4151                    || name.eq_ignore_ascii_case("default"))
4152            {
4153                continue;
4154            }
4155            // v7.39 (round 692) — the message says what is true TODAY.
4156            // Rounds 683–692 made ORDER BY, DISTINCT, GROUP BY, joins,
4157            // min/max and window ordering follow a declared collation, so
4158            // the old wording ("orders this column by bytes") had become
4159            // the wrong warning — and a wrong warning is worse than none,
4160            // because a customer reads it and plans around it.
4161            //
4162            // What is still true is the range comparison: `BETWEEN`, `<`,
4163            // `>` go through `binop::compare`, which takes two values and
4164            // no column. That one is not wiring; it needs collation
4165            // derivation at a comparison, and `compare` is the dominant
4166            // cost of a scan, so it needs a bench with it.
4167            if !crate::collate::is_known(name) {
4168                // v7.38.18 (G2) — see the ALTER site: PG 18.4 refuses a
4169                // name that is not in its catalogue, and so does this.
4170                return Err(crate::collate::unknown_collation_error(
4171                    name,
4172                    self.speaks_mysql,
4173                ));
4174            }
4175            if !crate::collate::is_supported(name) {
4176                self.warning(alloc::format!(
4177                    "column \"{}\" declares COLLATE \"{name}\", which this build cannot \
4178                     perform; SPG records the declaration and orders this column by bytes \
4179                     (the C collation)",
4180                    c.name
4181                ));
4182            }
4183        }
4184        // v7.17.0 Phase 1.4 + 1.5 — classify every raw
4185        // user_type_ref (parked as user_enum_type by
4186        // column_def_to_schema) into either an enum binding or a
4187        // domain binding. For domains, also rewrite the column's
4188        // base DataType from the placeholder Text to the domain's
4189        // declared base. Unknown idents are still a hard error
4190        // here (same as Phase 1.4) so silent acceptance never
4191        // happens.
4192        let mut cols = cols;
4193        for col in cols.iter_mut() {
4194            let Some(name) = col.user_enum_type.take() else {
4195                continue;
4196            };
4197            let cat = self.active_catalog();
4198            if cat.enum_types().contains_key(&name) {
4199                col.user_enum_type = Some(name);
4200                continue;
4201            }
4202            if let Some(dom) = cat.domain_types().get(&name) {
4203                let base_type = dom.base_type;
4204                let dom_default = dom.default.clone();
4205                col.ty = base_type;
4206                col.user_domain_type = Some(name);
4207                if !dom.nullable {
4208                    col.nullable = false;
4209                }
4210                // v7.39 (round 259) — two DEFAULT problems on a domain
4211                // column, both because the column was typed Text (the
4212                // parser's placeholder for an unknown type name) while its
4213                // DEFAULT was being resolved, and only re-typed here:
4214                //   * a COLUMN-level default failed to coerce and the
4215                //     whole CREATE TABLE errored ("type mismatch") — a
4216                //     hard failure on valid SQL;
4217                //   * the DOMAIN's own default was never adopted, so an
4218                //     omitted column landed NULL where PG gives the
4219                //     domain default (probed: 42, and a column default
4220                //     of 7 overrides it).
4221                if let Some(d) = col.default.take() {
4222                    col.default = Some(crate::conversions::coerce_value(
4223                        d, base_type, &col.name, 0,
4224                    )?);
4225                } else if let Some(src) = dom_default {
4226                    let expr = spg_sql::parser::parse_expression(&src).map_err(|e| {
4227                        EngineError::Storage(spg_storage::StorageError::Corrupt(alloc::format!(
4228                            "domain default {src:?} failed to re-parse: {e:?}"
4229                        )))
4230                    })?;
4231                    let empty: alloc::vec::Vec<spg_storage::ColumnSchema> = alloc::vec::Vec::new();
4232                    let ctx = crate::eval::EvalContext::new(&empty, None);
4233                    let row = spg_storage::Row {
4234                        values: alloc::vec::Vec::new(),
4235                    };
4236                    let v = crate::eval::eval_expr(&expr, &row, &ctx).map_err(EngineError::Eval)?;
4237                    col.default = Some(crate::conversions::coerce_value(
4238                        v, base_type, &col.name, 0,
4239                    )?);
4240                }
4241                continue;
4242            }
4243            // v7.37.42-T2 ζ-B — composite type bound to a column.
4244            // Stored as JSONB at the storage tier (positional + named
4245            // field access via JSONB path operators is the canonical
4246            // PG-compatible surface until Value::Composite lands).
4247            // The composite identity stays in `catalog.composite_types`
4248            // for introspection / DROP TYPE / column-type-DDL
4249            // round-trip.
4250            if cat.composite_types().contains_key(&name) {
4251                // v7.39 (read01 round 56) — the on-disk form stays JSONB, but
4252                // the column now RECORDS which composite type it holds. The
4253                // engine rehydrates the stored JSON into a Value::Composite on
4254                // read, so field access / ROW comparison / ordering / the
4255                // canonical `(2,b)` text form all work — every one of those was
4256                // already implemented on Value::Composite; the column simply
4257                // never remembered its type.
4258                col.ty = spg_storage::DataType::Jsonb;
4259                col.user_composite_type = Some(name.clone());
4260                continue;
4261            }
4262            // v7.38.19 — a PSEUDO-type is a different refusal. The name
4263            // exists; it just cannot hold a value, which PG reports as an
4264            // INVALID TABLE DEFINITION (42P16) naming the column rather
4265            // than an undefined type (42704) naming the type.
4266            if let Some(pseudo) = crate::conversions::pseudo_type(&name) {
4267                return Err(EngineError::Unsupported(alloc::format!(
4268                    "column \"{}\" has pseudo-type {pseudo}",
4269                    col.name
4270                )));
4271            }
4272            // v7.39 (read01 round 89) — PG's 42704 wording. The old
4273            // "column X: unknown column type Y (...)" carried SPG's own
4274            // vocabulary and fell to the generic error class; PG says
4275            // simply `type "Y" does not exist`.
4276            return Err(EngineError::Unsupported(alloc::format!(
4277                "type \"{name}\" does not exist"
4278            )));
4279        }
4280        for tc in table_constraints {
4281            if let spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } = tc {
4282                for col_name in columns {
4283                    if let Some(col) = cols.iter_mut().find(|c| c.name == *col_name) {
4284                        col.nullable = false;
4285                    }
4286                }
4287            }
4288        }
4289        // v7.6.1 — resolve every FK in the statement against the
4290        // already-known catalog. Validates: parent table exists,
4291        // parent column names exist, arity matches, parent columns
4292        // have a PK / UNIQUE index. Self-referencing FKs (parent
4293        // table == this table) resolve against the column list we
4294        // just built — they don't need the catalog yet.
4295        let mut fks: Vec<spg_storage::ForeignKeyConstraint> =
4296            Vec::with_capacity(foreign_keys.len());
4297        for fk in foreign_keys {
4298            // v7.14.0 — when SET FOREIGN_KEY_CHECKS=0 is in effect
4299            // (mysqldump preamble + bulk imports), defer FK
4300            // resolution if the parent table isn't in the catalog
4301            // yet. The FK is queued and resolved when checks flip
4302            // back on. Self-references stay in-band (the parent is
4303            // the same as the child we're building).
4304            let needs_parent = !fk.parent_table.eq_ignore_ascii_case(table_name);
4305            if !self.foreign_key_checks
4306                && needs_parent
4307                && self.active_catalog().get(&fk.parent_table).is_none()
4308            {
4309                self.pending_foreign_keys.push((table_name.to_string(), fk));
4310                continue;
4311            }
4312            fks.push(resolve_foreign_key(
4313                table_name,
4314                &cols,
4315                fk,
4316                self.active_catalog(),
4317            )?);
4318        }
4319        let mut schema = TableSchema::new(table_name.to_string(), cols);
4320        // v7.39 (read01 round 57) — whoever runs CREATE TABLE owns it (PG
4321        // `pg_class.relowner`); the owner holds every privilege implicitly.
4322        schema.owner = Some(alloc::string::String::from(self.current_role()));
4323        schema.foreign_keys = fks;
4324        // v7.9.19 — translate AST table_constraints to storage
4325        // UniquenessConstraints (column name → position) so the
4326        // INSERT enforcement helper sees positions directly.
4327        let mut uc_storage: Vec<spg_storage::UniquenessConstraint> = Vec::new();
4328        // v7.39 (read01 round 48) — the AST has carried `name` all along;
4329        // the schema now keeps it instead of dropping it on the floor.
4330        let mut check_exprs: Vec<spg_storage::CheckConstraint> = Vec::new();
4331        // v7.39 (round 210) — EXCLUDE constraints translate column names to
4332        // positions and synthesise PG's `<table>_<leading-col>_excl` name
4333        // when the user left it unnamed.
4334        let mut excl_storage: Vec<spg_storage::ExclusionConstraint> = Vec::new();
4335        for tc in table_constraints {
4336            let (is_pk, names, nnd, con_name, timing) = match tc {
4337                spg_sql::ast::TableConstraint::PrimaryKey {
4338                    name,
4339                    columns,
4340                    deferrable,
4341                    initially_deferred,
4342                } => (
4343                    true,
4344                    columns.clone(),
4345                    false,
4346                    name.clone(),
4347                    (*deferrable, *initially_deferred),
4348                ),
4349                spg_sql::ast::TableConstraint::Unique {
4350                    name,
4351                    columns,
4352                    nulls_not_distinct,
4353                    deferrable,
4354                    initially_deferred,
4355                } => (
4356                    false,
4357                    columns.clone(),
4358                    *nulls_not_distinct,
4359                    name.clone(),
4360                    (*deferrable, *initially_deferred),
4361                ),
4362                spg_sql::ast::TableConstraint::Check { name, expr, .. } => {
4363                    // v7.13.0 — collect CHECK predicate sources;
4364                    // they get attached to the schema below.
4365                    // A CREATE TABLE CHECK has no rows to grandfather; the
4366                    // parser refuses NOT VALID there, as PG does, so every
4367                    // one of these is validated and none needs a mark.
4368                    check_exprs.push(spg_storage::CheckConstraint {
4369                        name: name.clone(),
4370                        expr: alloc::format!("{expr}"),
4371                        validated: true,
4372                    });
4373                    continue;
4374                }
4375                spg_sql::ast::TableConstraint::Exclude {
4376                    name,
4377                    method,
4378                    elements,
4379                } => {
4380                    let mut els = Vec::with_capacity(elements.len());
4381                    for (col, op) in elements {
4382                        let pos = schema
4383                            .columns
4384                            .iter()
4385                            .position(|c| c.name == *col)
4386                            .ok_or_else(|| {
4387                                EngineError::Unsupported(alloc::format!(
4388                                    "EXCLUDE constraint references unknown column {col:?}"
4389                                ))
4390                            })?;
4391                        els.push((pos, op.clone()));
4392                    }
4393                    // v7.39 (round 211) — PG auto-names an unnamed EXCLUDE
4394                    // `<table>_<col…>_excl`, joining ALL element columns
4395                    // (e.g. `book_room_during_excl`), not just the leading one.
4396                    let cols_joined = elements
4397                        .iter()
4398                        .map(|(c, _)| c.clone())
4399                        .collect::<Vec<_>>()
4400                        .join("_");
4401                    let con_name = name
4402                        .clone()
4403                        .unwrap_or_else(|| alloc::format!("{table_name}_{cols_joined}_excl"));
4404                    excl_storage.push(spg_storage::ExclusionConstraint {
4405                        name: con_name,
4406                        method: method.clone(),
4407                        elements: els,
4408                    });
4409                    continue;
4410                }
4411                // v7.15.0 — plain `KEY (cols)` from MySQL inline
4412                // is NOT a uniqueness constraint; skip the UC
4413                // build path entirely. The BTree index lands in
4414                // the post-create loop below alongside the PK/UQ
4415                // implicit indexes.
4416                spg_sql::ast::TableConstraint::Index { .. } => continue,
4417                // v7.17.0 Phase 2.2 — MySQL FULLTEXT KEY is not
4418                // a uniqueness constraint either; its GIN gets
4419                // built in the post-create loop below.
4420                spg_sql::ast::TableConstraint::FulltextIndex { .. } => continue,
4421            };
4422            let mut positions = Vec::with_capacity(names.len());
4423            for n in &names {
4424                let pos = schema
4425                    .columns
4426                    .iter()
4427                    .position(|c| c.name == *n)
4428                    .ok_or_else(|| {
4429                        EngineError::Unsupported(alloc::format!(
4430                            "table constraint references unknown column {n:?}"
4431                        ))
4432                    })?;
4433                positions.push(pos);
4434            }
4435            uc_storage.push(spg_storage::UniquenessConstraint {
4436                is_primary_key: is_pk,
4437                columns: positions,
4438                nulls_not_distinct: nnd,
4439                name: con_name,
4440                deferrable: timing.0,
4441                initially_deferred: timing.1,
4442            });
4443        }
4444        // v7.24 (round-16 collateral) — inline `PRIMARY KEY` column
4445        // constraints used to build only the implicit BTree index;
4446        // uniqueness was NEVER registered, so duplicate keys were
4447        // silently accepted (table-level PRIMARY KEY did enforce).
4448        // Register the same UniquenessConstraint the table-level
4449        // form gets, unless one already covers the column set.
4450        if !inline_pk_columns.is_empty() {
4451            let mut positions = Vec::with_capacity(inline_pk_columns.len());
4452            for n in inline_pk_columns {
4453                if let Some(pos) = schema.columns.iter().position(|c| c.name == *n) {
4454                    positions.push(pos);
4455                }
4456            }
4457            if !uc_storage
4458                .iter()
4459                .any(|uc| uc.is_primary_key || uc.columns == positions)
4460            {
4461                uc_storage.push(spg_storage::UniquenessConstraint {
4462                    is_primary_key: true,
4463                    columns: positions,
4464                    nulls_not_distinct: false,
4465                    deferrable: inline_pk_timing.0,
4466                    initially_deferred: inline_pk_timing.1,
4467                    // Inline `col INT PRIMARY KEY` carries no name.
4468                    name: None,
4469                });
4470            }
4471        }
4472        schema.uniqueness_constraints = uc_storage.clone();
4473        schema.checks = check_exprs;
4474        schema.exclusion_constraints = excl_storage;
4475        Ok(schema)
4476    }
4477
4478    /// Install the implicit BTree / fulltext-GIN indexes a freshly-created
4479    /// table needs: one per inline PRIMARY KEY column, plus one per
4480    /// v7.39 (round 215) — build a range-overlap index for every EXCLUDE
4481    /// constraint whose `&&` element sits on an integer-keyable range column
4482    /// (int4/int8/date/ts/tstz range). Turns the O(n) enforcement scan into an
4483    /// O(log n) predecessor+successor probe. Idempotent — safe to call again
4484    /// after ALTER or on catalog load. Constraints the index can't cover
4485    /// (numrange, `@>`/`<@`/geometry operators) simply get no index and keep
4486    /// the correct O(n) scan.
4487    pub(crate) fn install_excl_range_indexes(&mut self, table_name: &str) {
4488        let Some(table) = self.active_catalog_mut().get_mut(table_name) else {
4489            return;
4490        };
4491        let cols: Vec<usize> = table
4492            .schema()
4493            .exclusion_constraints
4494            .iter()
4495            .filter_map(|ex| excl_index_column(table.schema(), ex))
4496            .collect();
4497        for c in cols {
4498            table.ensure_excl_range_index(c);
4499        }
4500    }
4501
4502    /// table-level PRIMARY KEY / UNIQUE / KEY / FULLTEXT constraint.
4503    fn install_implicit_indexes(
4504        &mut self,
4505        table_name: &str,
4506        inline_pk_columns: &[String],
4507        table_constraints: &[spg_sql::ast::TableConstraint],
4508    ) -> Result<(), EngineError> {
4509        // v7.9.13 — implicit BTree per inline PK column +
4510        // v7.9.19 — implicit BTree on the leading column of every
4511        // table-level PRIMARY KEY / UNIQUE constraint.
4512        let table = self
4513            .active_catalog_mut()
4514            .get_mut(table_name)
4515            .expect("just created");
4516        let mut inline_lead_added: Option<alloc::string::String> = None;
4517        for (i, col_name) in inline_pk_columns.iter().enumerate() {
4518            let idx_name = if inline_pk_columns.len() == 1 {
4519                alloc::format!("{table_name}_pkey")
4520            } else {
4521                alloc::format!("{table_name}_pkey_{i}")
4522            };
4523            if let Err(e) = table.add_index(idx_name.clone(), col_name) {
4524                return Err(EngineError::Storage(e));
4525            }
4526            if i == 0 {
4527                if let Some(ix) = table.indices_mut().iter_mut().find(|i| i.name == idx_name) {
4528                    ix.constraint_backing = true;
4529                }
4530                inline_lead_added = Some(idx_name);
4531            } else if inline_pk_columns.len() >= 2 {
4532                // v7.39.13 — a probe index for a non-leading key column.
4533                // The lead one becomes the composite below and IS the
4534                // constraint's index; these exist so a probe that does
4535                // not start at the key's front still has a B-tree.
4536                if let Some(ix) = table.indices_mut().iter_mut().find(|i| i.name == idx_name) {
4537                    ix.constraint_internal = true;
4538                }
4539            }
4540        }
4541        // v7.38.1 (L12) — a multi-column PRIMARY KEY's leading index
4542        // becomes a REAL composite B-tree over the whole key, exactly
4543        // like PG's one `t_pkey` index. The k≥1 per-column B-trees
4544        // stay: they serve probes on non-leading columns, which a
4545        // composite cannot (a prefix must start at the front).
4546        if inline_pk_columns.len() >= 2
4547            && let Some(lead_name) = inline_lead_added
4548        {
4549            let mut extras: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
4550            for col_name in &inline_pk_columns[1..] {
4551                if let Some(p) = table
4552                    .schema()
4553                    .columns
4554                    .iter()
4555                    .position(|c| c.name.eq_ignore_ascii_case(col_name))
4556                {
4557                    extras.push(p);
4558                }
4559            }
4560            if extras.len() == inline_pk_columns.len() - 1 {
4561                if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == lead_name) {
4562                    idx.extra_column_positions = extras;
4563                }
4564                table
4565                    .convert_index_to_multi(&lead_name)
4566                    .map_err(EngineError::Storage)?;
4567            }
4568        }
4569        for (i, tc) in table_constraints.iter().enumerate() {
4570            // v7.17.0 Phase 2.2 — FULLTEXT KEY lands a real
4571            // tsvector-GIN per declared column instead of the
4572            // BTree the PK / UQ / KEY paths build. Branch early
4573            // so the BTree loop never sees the FULLTEXT shape.
4574            if let spg_sql::ast::TableConstraint::FulltextIndex { name, columns } = tc {
4575                for (k, col) in columns.iter().enumerate() {
4576                    let already = table.indices().iter().any(|idx| {
4577                        matches!(idx.kind, spg_storage::IndexKind::GinFulltext(_))
4578                            && table.schema().columns[idx.column_position].name == *col
4579                    });
4580                    if already {
4581                        continue;
4582                    }
4583                    let idx_name = match (name.as_ref(), columns.len(), k) {
4584                        (Some(n), 1, _) => n.clone(),
4585                        (Some(n), _, k) => alloc::format!("{n}_{k}"),
4586                        (None, _, _) => {
4587                            alloc::format!("{table_name}_{col}_ftidx")
4588                        }
4589                    };
4590                    if let Err(e) = table.add_gin_fulltext_index(idx_name, col) {
4591                        return Err(EngineError::Storage(e));
4592                    }
4593                }
4594                continue;
4595            }
4596            // v7.15.0 — plain KEY/INDEX rides this same loop so
4597            // the implicit BTree gets built. It carries its own
4598            // user-supplied name; PK/UQ still synthesise.
4599            let (suffix, names, explicit_name): (&str, &Vec<String>, Option<&String>) = match tc {
4600                spg_sql::ast::TableConstraint::PrimaryKey { columns, .. } => {
4601                    ("pkey", columns, None)
4602                }
4603                spg_sql::ast::TableConstraint::Unique { columns, .. } => ("key", columns, None),
4604                spg_sql::ast::TableConstraint::Index { name, columns } => {
4605                    ("idx", columns, name.as_ref())
4606                }
4607                spg_sql::ast::TableConstraint::Check { .. } => continue,
4608                // Handled by the early-branch above.
4609                spg_sql::ast::TableConstraint::FulltextIndex { .. } => continue,
4610                // v7.39 (round 210) — EXCLUDE builds no implicit index in
4611                // Phase 0 (O(n)-scan enforcement); a real GiST index is a
4612                // later perf phase.
4613                spg_sql::ast::TableConstraint::Exclude { .. } => continue,
4614            };
4615            // 7.38.1 S7 (tpcc decomposition finding) — a composite
4616            // PRIMARY KEY / UNIQUE built a BTree on the LEADING column
4617            // only, and TPC-C's keys all lead with the warehouse id:
4618            // at scale=1 every "index scan" selected the WHOLE table
4619            // (customer point lookup measured 19.9 ms over 30k rows).
4620            // SPG's BTree keys one column, so until composite-keyed
4621            // BTrees land (ledgered), the constraint builds one BTree
4622            // PER KEY COLUMN — the planner can then pick the selective
4623            // one (c_id: 10 rows) instead of the degenerate leading
4624            // one (c_w_id: all 30k). Mirrors what the inline-PK loop
4625            // above has always done.
4626            let mut lead_added: Option<alloc::string::String> = None;
4627            for (k, col_name) in names.iter().enumerate() {
4628                let already = table.indices().iter().any(|idx| {
4629                    matches!(idx.kind, spg_storage::IndexKind::BTree(_))
4630                        && table.schema().columns[idx.column_position].name == *col_name
4631                });
4632                if already {
4633                    continue;
4634                }
4635                let idx_name = if let (Some(n), 0) = (explicit_name, k) {
4636                    n.clone()
4637                } else if names.len() == 1 {
4638                    alloc::format!("{table_name}_{col_name}_{suffix}")
4639                } else {
4640                    alloc::format!("{table_name}_{col_name}_{suffix}_{i}_{k}")
4641                };
4642                if let Err(e) = table.add_index(idx_name.clone(), col_name) {
4643                    return Err(EngineError::Storage(e));
4644                }
4645                if k == 0 {
4646                    if let Some(ix) = table.indices_mut().iter_mut().find(|i| i.name == idx_name) {
4647                        ix.constraint_backing = true;
4648                    }
4649                    lead_added = Some(idx_name);
4650                } else if names.len() >= 2 {
4651                    // v7.39.13 — see the inline-PK loop above: a probe
4652                    // index for a non-leading key column, not the
4653                    // constraint's own.
4654                    if let Some(ix) = table.indices_mut().iter_mut().find(|i| i.name == idx_name) {
4655                        ix.constraint_internal = true;
4656                    }
4657                }
4658            }
4659            // v7.38.1 (L12) — same upgrade as the inline-PK path: the
4660            // leading index of a composite PK / UNIQUE / KEY becomes a
4661            // real multi-column B-tree over the whole declared tuple.
4662            if names.len() >= 2
4663                && let Some(lead_name) = lead_added
4664            {
4665                let mut extras: alloc::vec::Vec<usize> = alloc::vec::Vec::new();
4666                for col_name in &names[1..] {
4667                    if let Some(p) = table
4668                        .schema()
4669                        .columns
4670                        .iter()
4671                        .position(|c| c.name.eq_ignore_ascii_case(col_name))
4672                    {
4673                        extras.push(p);
4674                    }
4675                }
4676                if extras.len() == names.len() - 1 {
4677                    if let Some(idx) = table.indices_mut().iter_mut().find(|i| i.name == lead_name)
4678                    {
4679                        idx.extra_column_positions = extras;
4680                    }
4681                    table
4682                        .convert_index_to_multi(&lead_name)
4683                        .map_err(EngineError::Storage)?;
4684                }
4685            }
4686        }
4687        Ok(())
4688    }
4689}
4690
4691impl Engine {
4692    /// v7.39 (RLS) — `CREATE POLICY`. Stores the policy on the table schema
4693    /// (independent of the RLS enable flag). Enforcement is Phase 1.
4694    pub(crate) fn exec_create_policy(
4695        &mut self,
4696        s: spg_sql::ast::CreatePolicyStatement,
4697    ) -> Result<QueryResult, EngineError> {
4698        let cmd = policy_cmd_to_storage(s.cmd);
4699        let using_expr = s.using.as_ref().map(deparse_policy_qual);
4700        let with_check_expr = s.with_check.as_ref().map(deparse_policy_qual);
4701        let table = self.active_catalog_mut().get_mut(&s.table).ok_or_else(|| {
4702            EngineError::Storage(StorageError::TableNotFound {
4703                name: s.table.clone(),
4704            })
4705        })?;
4706        if table.schema().policies.iter().any(|p| p.name == s.name) {
4707            return Err(EngineError::Unsupported(alloc::format!(
4708                "policy {:?} for table {:?} already exists",
4709                s.name,
4710                s.table
4711            )));
4712        }
4713        table.schema_mut().policies.push(spg_storage::PolicyDef {
4714            name: s.name,
4715            cmd,
4716            permissive: s.permissive,
4717            roles: s.roles,
4718            using_expr,
4719            with_check_expr,
4720        });
4721        Ok(QueryResult::CommandOk {
4722            affected: 0,
4723            modified_catalog: self.catalog_change_is_committed(),
4724        })
4725    }
4726
4727    /// v7.39 (RLS) — `ALTER POLICY … { RENAME TO | [TO roles] [USING] [WITH
4728    /// CHECK] }`.
4729    pub(crate) fn exec_alter_policy(
4730        &mut self,
4731        s: spg_sql::ast::AlterPolicyStatement,
4732    ) -> Result<QueryResult, EngineError> {
4733        let new_using = s.using.as_ref().map(deparse_policy_qual);
4734        let new_check = s.with_check.as_ref().map(deparse_policy_qual);
4735        let table = self.active_catalog_mut().get_mut(&s.table).ok_or_else(|| {
4736            EngineError::Storage(StorageError::TableNotFound {
4737                name: s.table.clone(),
4738            })
4739        })?;
4740        // Duplicate-name pre-check for RENAME (before taking the mutable slot).
4741        if let Some(new) = &s.rename_to
4742            && table.schema().policies.iter().any(|p| &p.name == new)
4743        {
4744            return Err(EngineError::Unsupported(alloc::format!(
4745                "policy {new:?} for table {:?} already exists",
4746                s.table
4747            )));
4748        }
4749        let pol = table
4750            .schema_mut()
4751            .policies
4752            .iter_mut()
4753            .find(|p| p.name == s.name)
4754            .ok_or_else(|| {
4755                EngineError::Unsupported(alloc::format!(
4756                    "policy {:?} for table {:?} does not exist",
4757                    s.name,
4758                    s.table
4759                ))
4760            })?;
4761        if let Some(new) = s.rename_to {
4762            pol.name = new;
4763        } else {
4764            if let Some(roles) = s.roles {
4765                pol.roles = roles;
4766            }
4767            if new_using.is_some() {
4768                pol.using_expr = new_using;
4769            }
4770            if new_check.is_some() {
4771                pol.with_check_expr = new_check;
4772            }
4773        }
4774        Ok(QueryResult::CommandOk {
4775            affected: 0,
4776            modified_catalog: self.catalog_change_is_committed(),
4777        })
4778    }
4779
4780    /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
4781    pub(crate) fn exec_drop_policy(
4782        &mut self,
4783        s: spg_sql::ast::DropPolicyStatement,
4784    ) -> Result<QueryResult, EngineError> {
4785        let table = match self.active_catalog_mut().get_mut(&s.table) {
4786            Some(t) => t,
4787            None if s.if_exists => {
4788                return Ok(QueryResult::CommandOk {
4789                    affected: 0,
4790                    modified_catalog: self.catalog_change_is_committed(),
4791                });
4792            }
4793            None => {
4794                return Err(EngineError::Storage(StorageError::TableNotFound {
4795                    name: s.table.clone(),
4796                }));
4797            }
4798        };
4799        let before = table.schema().policies.len();
4800        table.schema_mut().policies.retain(|p| p.name != s.name);
4801        if table.schema().policies.len() == before && !s.if_exists {
4802            return Err(EngineError::Unsupported(alloc::format!(
4803                "policy {:?} for table {:?} does not exist",
4804                s.name,
4805                s.table
4806            )));
4807        }
4808        Ok(QueryResult::CommandOk {
4809            affected: 0,
4810            modified_catalog: self.catalog_change_is_committed(),
4811        })
4812    }
4813
4814    pub(crate) fn exec_create_user(
4815        &mut self,
4816        s: &CreateUserStatement,
4817    ) -> Result<QueryResult, EngineError> {
4818        // v7.37 (round 828) — no transaction guard any more. PG treats
4819        // roles as ordinary catalog rows: BEGIN; CREATE ROLE r;
4820        // ROLLBACK leaves nothing, COMMIT publishes (measured against
4821        // PG18: count 0 after rollback, 1 after commit). The per-slot
4822        // guard that stood here since round 794 refused the statement
4823        // outright, which no drop-in client expects. Writes now go
4824        // through the TX role shadow (`role_ddl_users_mut`), so both
4825        // halves of PG's behaviour hold.
4826        let role = users::Role::parse(&s.role).ok_or_else(|| {
4827            EngineError::Unsupported(alloc::format!("invalid role: {:?}", s.role))
4828        })?;
4829        // Prefer the host-injected RNG. Falls back to a deterministic
4830        // salt derived from the username only when no RNG is wired —
4831        // acceptable for tests; the server always installs one.
4832        let salt = self.salt_fn.map_or_else(
4833            || {
4834                let mut s_bytes = [0u8; 16];
4835                let digest = spg_crypto::hash(s.name.as_bytes());
4836                s_bytes.copy_from_slice(&digest[..16]);
4837                s_bytes
4838            },
4839            |f| f(),
4840        );
4841        // v7.39 (TLS/SCRAM) — route through `create_user`, not `users.create`,
4842        // so the SQL path also derives the SCRAM-SHA-256 verifier. Without
4843        // this, a `CREATE USER … PASSWORD` user had `scram = None` and silently
4844        // fell back to cleartext pgwire auth.
4845        if self.effective_users().contains(&s.name) {
4846            return Err(EngineError::Unsupported(alloc::format!(
4847                "role \"{}\" already exists",
4848                s.name
4849            )));
4850        }
4851        // v7.39 (read01 round 58) — a bare `CREATE ROLE devs` carries no
4852        // password. It cannot log in (NOLOGIN is its default), so it needs no
4853        // credential; give it an unguessable one derived from its own salt so
4854        // no code path ever sees an empty-password record.
4855        let password = if s.password.is_empty() {
4856            let digest = spg_crypto::hash(&salt);
4857            hex_of(&digest[..16])
4858        } else {
4859            s.password.clone()
4860        };
4861        self.create_user(&s.name, &password, role, salt)
4862            .map_err(|e| EngineError::Unsupported(alloc::format!("CREATE USER: {e}")))?;
4863        // PG's attribute defaults: LOGIN iff spelled CREATE USER, INHERIT, and
4864        // NOSUPERUSER — but SPG's own coarse `ROLE 'admin'` still means
4865        // superuser, which is how the existing admin account keeps working.
4866        // v7.39 (round 548) — remember whether a password was DECLARED,
4867        // not just whether the record ended up with one: the branch
4868        // above substitutes an unguessable credential for a bare
4869        // CREATE ROLE, and the wire's open-vs-authenticated decision
4870        // has to tell the two apart.
4871        self.role_ddl_users_mut()
4872            .set_password_declared(&s.name, !s.password.is_empty());
4873        self.role_ddl_users_mut().set_attributes(
4874            &s.name,
4875            s.login.unwrap_or(s.is_user),
4876            s.inherit.unwrap_or(true),
4877            s.superuser
4878                .unwrap_or_else(|| matches!(role, users::Role::Admin)),
4879        );
4880        Ok(QueryResult::CommandOk {
4881            affected: 1,
4882            modified_catalog: true,
4883        })
4884    }
4885
4886    pub(crate) fn exec_drop_user(
4887        &mut self,
4888        name: &str,
4889        if_exists: bool,
4890    ) -> Result<QueryResult, EngineError> {
4891        // v7.37 (round 828) — transactional now; see exec_create_user.
4892        // v7.39 (read01 round 58) — PG's IF EXISTS skip NOTICE.
4893        if if_exists && !self.effective_users().contains(name) {
4894            self.notice(alloc::format!("role {name:?} does not exist, skipping"));
4895            return Ok(QueryResult::CommandOk {
4896                affected: 0,
4897                modified_catalog: false,
4898            });
4899        }
4900        // v7.39 (read01 round 58) — PG refuses to drop a role that still holds
4901        // privileges: they would become dangling aclitems. It names the tables.
4902        let depends: alloc::vec::Vec<alloc::string::String> = self
4903            .active_catalog()
4904            .table_names()
4905            .into_iter()
4906            .filter(|t| {
4907                self.active_catalog().get(t).is_some_and(|tb| {
4908                    tb.schema()
4909                        .acl
4910                        .iter()
4911                        .any(|a| a.grantee.eq_ignore_ascii_case(name))
4912                        || tb
4913                            .schema()
4914                            .owner
4915                            .as_deref()
4916                            .is_some_and(|o| o.eq_ignore_ascii_case(name))
4917                })
4918            })
4919            .collect();
4920        if !depends.is_empty() {
4921            return Err(EngineError::Unsupported(alloc::format!(
4922                "role \"{name}\" cannot be dropped because some objects depend on it DETAIL: privileges for table {}",
4923                depends.join(", ")
4924            )));
4925        }
4926        self.role_ddl_users_mut()
4927            .drop(name)
4928            .map_err(|e| EngineError::Unsupported(alloc::format!("DROP USER: {e}")))?;
4929        Ok(QueryResult::CommandOk {
4930            affected: 1,
4931            modified_catalog: true,
4932        })
4933    }
4934
4935    /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. Stores the
4936    /// function metadata in the catalog. PL/pgSQL bodies are
4937    /// already parsed by the SQL parser; we re-canonicalise the
4938    /// body to source text for storage (the executor re-parses
4939    /// it at trigger fire time — see the trigger fire path).
4940    pub(crate) fn exec_create_function(
4941        &mut self,
4942        s: spg_sql::ast::CreateFunctionStatement,
4943    ) -> Result<QueryResult, EngineError> {
4944        let args_repr = render_function_args(&s.args);
4945        let returns = match &s.returns {
4946            spg_sql::ast::FunctionReturn::Trigger => alloc::string::String::from("TRIGGER"),
4947            spg_sql::ast::FunctionReturn::Void => alloc::string::String::from("VOID"),
4948            spg_sql::ast::FunctionReturn::Type(t) => alloc::format!("{t}"),
4949            spg_sql::ast::FunctionReturn::Other(s) => s.clone(),
4950        };
4951        let body_text = match &s.body {
4952            spg_sql::ast::FunctionBody::PlPgSql(b) => alloc::format!("{b}"),
4953            spg_sql::ast::FunctionBody::Raw(s) => s.clone(),
4954        };
4955        let def = spg_storage::FunctionDef {
4956            name: s.name.clone(),
4957            args_repr,
4958            returns,
4959            language: s.language.clone(),
4960            body: body_text,
4961            // v7.39 (read01 round 61) — whoever runs CREATE FUNCTION owns it.
4962            owner: Some(alloc::string::String::from(self.current_role())),
4963            acl: alloc::vec::Vec::new(),
4964            // v7.39 (round 322, V46) — the declared attribute clauses.
4965            volatility: match s.attrs.volatility {
4966                spg_sql::ast::FunctionVolatility::Immutable => spg_storage::FN_IMMUTABLE,
4967                spg_sql::ast::FunctionVolatility::Stable => spg_storage::FN_STABLE,
4968                spg_sql::ast::FunctionVolatility::Volatile => spg_storage::FN_VOLATILE,
4969            },
4970            strict: s.attrs.strict,
4971            security_definer: s.attrs.security_definer,
4972            leakproof: s.attrs.leakproof,
4973            parallel: match s.attrs.parallel {
4974                spg_sql::ast::FunctionParallel::Safe => spg_storage::FN_PARALLEL_SAFE,
4975                spg_sql::ast::FunctionParallel::Restricted => spg_storage::FN_PARALLEL_RESTRICTED,
4976                spg_sql::ast::FunctionParallel::Unsafe => spg_storage::FN_PARALLEL_UNSAFE,
4977            },
4978            cost: s.attrs.cost,
4979            rows: s.attrs.rows,
4980        };
4981        self.active_catalog_mut()
4982            .create_function(def, s.or_replace)
4983            .map_err(EngineError::Storage)?;
4984        Ok(QueryResult::CommandOk {
4985            affected: 0,
4986            modified_catalog: true,
4987        })
4988    }
4989
4990    /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. The referenced
4991    /// function must already exist in the catalog (forward
4992    /// references defer to a later release). Persists the
4993    /// trigger metadata for the row-write hooks below to consult.
4994    pub(crate) fn exec_create_trigger(
4995        &mut self,
4996        s: spg_sql::ast::CreateTriggerStatement,
4997    ) -> Result<QueryResult, EngineError> {
4998        let timing = match s.timing {
4999            spg_sql::ast::TriggerTiming::Before => "BEFORE",
5000            spg_sql::ast::TriggerTiming::After => "AFTER",
5001            spg_sql::ast::TriggerTiming::InsteadOf => "INSTEAD OF",
5002        };
5003        let events: Vec<alloc::string::String> = s
5004            .events
5005            .iter()
5006            .map(|e| match e {
5007                spg_sql::ast::TriggerEvent::Insert => alloc::string::String::from("INSERT"),
5008                spg_sql::ast::TriggerEvent::Update => alloc::string::String::from("UPDATE"),
5009                spg_sql::ast::TriggerEvent::Delete => alloc::string::String::from("DELETE"),
5010                spg_sql::ast::TriggerEvent::Truncate => alloc::string::String::from("TRUNCATE"),
5011            })
5012            .collect();
5013        let for_each = match s.for_each {
5014            spg_sql::ast::TriggerForEach::Row => "ROW",
5015            spg_sql::ast::TriggerForEach::Statement => "STATEMENT",
5016        };
5017        // v7.39 (round 137) — INSTEAD OF triggers may only target views; BEFORE /
5018        // AFTER row triggers may only target base tables. PG's exact wording.
5019        let target_is_view = self.active_catalog().has_view(&s.table);
5020        if matches!(s.timing, spg_sql::ast::TriggerTiming::InsteadOf) {
5021            if !target_is_view {
5022                return Err(EngineError::Unsupported(alloc::format!(
5023                    "\"{}\" is a table DETAIL: Tables cannot have INSTEAD OF triggers.",
5024                    s.table
5025                )));
5026            }
5027            // v7.39 (round 137) — PG: INSTEAD OF triggers must be row-level.
5028            if matches!(s.for_each, spg_sql::ast::TriggerForEach::Statement) {
5029                return Err(EngineError::Unsupported(
5030                    "INSTEAD OF triggers must be FOR EACH ROW".into(),
5031                ));
5032            }
5033            // v7.39 (round 138) — PG: INSTEAD OF triggers cannot have WHEN.
5034            if s.when_condition.is_some() {
5035                return Err(EngineError::Unsupported(
5036                    "INSTEAD OF triggers cannot have WHEN conditions".into(),
5037                ));
5038            }
5039        } else if target_is_view {
5040            return Err(EngineError::Unsupported(alloc::format!(
5041                "\"{}\" is a view DETAIL: Views cannot have row-level BEFORE or AFTER triggers.",
5042                s.table
5043            )));
5044        }
5045        let def = spg_storage::TriggerDef {
5046            name: s.name.clone(),
5047            table: s.table.clone(),
5048            timing: alloc::string::String::from(timing),
5049            events,
5050            for_each: alloc::string::String::from(for_each),
5051            function: s.function.clone(),
5052            update_columns: s.update_columns.clone(),
5053            // v7.16.1 — every trigger is born enabled. Toggled
5054            // by ALTER TABLE … { ENABLE | DISABLE } TRIGGER.
5055            enabled: true,
5056            // v7.39 (round 138) — deparse the WHEN predicate to text; re-parsed
5057            // at fire time. Empty when there is no WHEN.
5058            when_condition: s
5059                .when_condition
5060                .as_ref()
5061                .map(|e| e.to_string())
5062                .unwrap_or_default(),
5063        };
5064        self.active_catalog_mut()
5065            .create_trigger(def, s.or_replace)
5066            .map_err(EngineError::Storage)?;
5067        Ok(QueryResult::CommandOk {
5068            affected: 0,
5069            modified_catalog: true,
5070        })
5071    }
5072
5073    pub(crate) fn exec_drop_trigger(
5074        &mut self,
5075        name: &str,
5076        table: &str,
5077        if_exists: bool,
5078    ) -> Result<QueryResult, EngineError> {
5079        let removed = self.active_catalog_mut().drop_trigger(name, table);
5080        if !removed && !if_exists {
5081            // v7.39 (round 700) — two fixes in one line, and they are the
5082            // same fix round 698 made for sequences.
5083            //
5084            // `StorageError::Corrupt` prefixes its Display with `corrupt
5085            // on-disk format: `, so a misspelt trigger name reported a
5086            // CORRUPTION to the client. And the wording was SPG's own
5087            // (`on "t"`); PG18 says `for table "t"`, which is what the
5088            // wire's classifier and any tool matching on it expect.
5089            //
5090            // Round 698 said its sweep found nothing else. It swept the
5091            // sequence / view / type shapes and not the trigger one — the
5092            // sweep was narrower than the sentence claimed.
5093            return Err(EngineError::Unsupported(alloc::format!(
5094                "trigger \"{name}\" for table \"{table}\" does not exist"
5095            )));
5096        }
5097        // v7.39 (round 282) — PG raises a NOTICE when IF EXISTS skips, and
5098        // it distinguishes the two ways a DROP TRIGGER can find nothing:
5099        // the RELATION is missing (so the trigger could not be looked up
5100        // at all), or the relation is there and the trigger is not.
5101        if !removed && if_exists {
5102            if self.active_catalog().get(table).is_none() {
5103                self.notice(alloc::format!(
5104                    "relation \"{table}\" does not exist, skipping"
5105                ));
5106            } else {
5107                self.notice(alloc::format!(
5108                    "trigger \"{name}\" for relation \"{table}\" does not exist, skipping"
5109                ));
5110            }
5111        }
5112        Ok(QueryResult::CommandOk {
5113            affected: usize::from(removed),
5114            modified_catalog: removed,
5115        })
5116    }
5117
5118    // v7.39 (round 139) — CREATE RULE (query-rewrite rules). Phase 1 supports
5119    // ON {INSERT|UPDATE|DELETE} TO table [WHERE cond] DO [ALSO|INSTEAD]
5120    // {NOTHING | command}. ON SELECT rules are PG's view mechanism; use CREATE
5121    // VIEW instead. The WHEN/commands are deparsed to text and re-parsed at DML
5122    // rewrite time, mirroring how triggers carry their WHEN predicate.
5123    pub(crate) fn exec_create_rule(
5124        &mut self,
5125        s: spg_sql::ast::CreateRuleStatement,
5126    ) -> Result<QueryResult, EngineError> {
5127        if s.event.eq_ignore_ascii_case("SELECT") {
5128            return Err(EngineError::Unsupported(
5129                "ON SELECT rules are not supported; use CREATE VIEW".into(),
5130            ));
5131        }
5132        // v7.39 (round 333, V59) — the conditional `DO INSTEAD <command>`
5133        // form is supported now: the rows the WHERE holds for take the
5134        // command, the rest run the original operation. It used to be
5135        // refused up front, which made a rule PG accepts a hard error.
5136        // Measured on PG 18.4: with `ON UPDATE TO r WHERE old.id > 1 DO
5137        // INSTEAD INSERT INTO log …`, `UPDATE r SET v = 999` answers
5138        // `UPDATE 1` — only the non-matching row is updated — and the
5139        // matching rows produce log entries instead.
5140        // Rules may target base tables (and, in PG, views); require the relation
5141        // to exist so a typo does not silently create a dead rule.
5142        let known = self.active_catalog().table_names().contains(&s.table)
5143            || self.active_catalog().has_view(&s.table);
5144        if !known {
5145            return Err(EngineError::Unsupported(alloc::format!(
5146                "relation \"{}\" does not exist",
5147                s.table
5148            )));
5149        }
5150        let def = spg_storage::RuleDef {
5151            name: s.name.clone(),
5152            table: s.table.clone(),
5153            event: s.event.to_ascii_uppercase(),
5154            instead: s.instead,
5155            when_condition: s
5156                .when_condition
5157                .as_ref()
5158                .map(|e| e.to_string())
5159                .unwrap_or_default(),
5160            commands: s.commands.iter().map(|c| c.to_string()).collect(),
5161        };
5162        self.active_catalog_mut()
5163            .create_rule(def, s.or_replace)
5164            .map_err(EngineError::Storage)?;
5165        Ok(QueryResult::CommandOk {
5166            affected: 0,
5167            modified_catalog: true,
5168        })
5169    }
5170
5171    pub(crate) fn exec_drop_rule(
5172        &mut self,
5173        name: &str,
5174        table: &str,
5175        if_exists: bool,
5176    ) -> Result<QueryResult, EngineError> {
5177        let removed = self.active_catalog_mut().drop_rule(name, table);
5178        if !removed && !if_exists {
5179            // v7.39 (round 708) — PG's order and words, both measured: the
5180            // RELATION resolves first (`relation "t" does not exist`), and
5181            // only then the rule, spelled `for relation`, not `on`. The old
5182            // message also rode `StorageError::Corrupt`, whose Display put
5183            // `corrupt on-disk format:` in front of a typo — the same
5184            // wrapper rounds 698 and 700 kept meeting.
5185            if self.active_catalog().get(table).is_none() {
5186                return Err(EngineError::Unsupported(alloc::format!(
5187                    "relation \"{table}\" does not exist"
5188                )));
5189            }
5190            return Err(EngineError::Unsupported(alloc::format!(
5191                "rule \"{name}\" for relation \"{table}\" does not exist"
5192            )));
5193        }
5194        Ok(QueryResult::CommandOk {
5195            affected: usize::from(removed),
5196            modified_catalog: removed,
5197        })
5198    }
5199
5200    pub(crate) fn exec_drop_function(
5201        &mut self,
5202        name: &str,
5203        args: Option<&[alloc::string::String]>,
5204        if_exists: bool,
5205    ) -> Result<QueryResult, EngineError> {
5206        // v7.39 (read01 round 62) — with overloads, the signature says WHICH one.
5207        let removed = match args {
5208            Some(types) => {
5209                let repr = alloc::format!("({})", types.join(", "));
5210                let key = spg_storage::function_signature_key(name, &repr);
5211                self.active_catalog_mut().drop_function_by_key(&key)
5212            }
5213            None => {
5214                // PG refuses a bare `DROP FUNCTION f` when `f` is overloaded —
5215                // it cannot know which one is meant.
5216                if self.active_catalog().functions_named(name).len() > 1 {
5217                    return Err(EngineError::Unsupported(alloc::format!(
5218                        "function name \"{name}\" is not unique DETAIL: Specify the argument list to select the function unambiguously."
5219                    )));
5220                }
5221                self.active_catalog_mut().drop_function(name)
5222            }
5223        };
5224        if !removed && !if_exists {
5225            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5226                alloc::format!("function {name:?} does not exist"),
5227            )));
5228        }
5229        // v7.39 (round 282) — the skipped-function NOTICE. Alone among the
5230        // IF EXISTS family PG does NOT quote the name, because it renders a
5231        // signature rather than an identifier.
5232        if !removed && if_exists {
5233            let sig = match args {
5234                Some(types) => types
5235                    .iter()
5236                    .map(|t| pg_signature_type_name(t))
5237                    .collect::<alloc::vec::Vec<_>>()
5238                    .join(","),
5239                None => alloc::string::String::new(),
5240            };
5241            self.notice(alloc::format!(
5242                "function {name}({sig}) does not exist, skipping"
5243            ));
5244        }
5245        Ok(QueryResult::CommandOk {
5246            affected: usize::from(removed),
5247            modified_catalog: removed,
5248        })
5249    }
5250
5251    /// v7.17.0 — `CREATE SEQUENCE` engine path. Resolves
5252    /// `min_value` / `max_value` / `start` against PG defaults
5253    /// when omitted, then installs the SequenceDef in the catalog.
5254    pub(crate) fn exec_create_sequence(
5255        &mut self,
5256        s: spg_sql::ast::CreateSequenceStatement,
5257    ) -> Result<QueryResult, EngineError> {
5258        // v7.39 (round 469) — a TEMPORARY sequence lives in the calling
5259        // session's namespace, exactly as round 436 put temporary tables
5260        // there. Until this round the keyword parsed and was dropped, so
5261        // the sequence was permanent: another connection saw it in
5262        // pg_class and could call nextval() on it. Measured against PG18,
5263        // where a second session sees nothing and errors on use.
5264        if s.temporary {
5265            let logical = s.name.clone();
5266            let mut inner = s;
5267            inner.temporary = false;
5268            inner.name = self.session_temp_name(&logical);
5269            let result = self.exec_create_sequence(inner)?;
5270            self.temp_sequences.insert(logical);
5271            self.refresh_temp_prefix();
5272            return Ok(result);
5273        }
5274        use spg_sql::ast::{SeqBound, SequenceDataType as AstDt};
5275        use spg_storage::{SequenceDataType, SequenceDef};
5276        let dt = match s.data_type {
5277            None => SequenceDataType::BigInt,
5278            Some(AstDt::SmallInt) => SequenceDataType::SmallInt,
5279            Some(AstDt::Int) => SequenceDataType::Int,
5280            Some(AstDt::BigInt) => SequenceDataType::BigInt,
5281        };
5282        let increment = s.options.increment.unwrap_or(1);
5283        if increment == 0 {
5284            return Err(EngineError::Unsupported(
5285                "INCREMENT must not be zero".into(),
5286            ));
5287        }
5288        let (def_min, def_max) = dt.default_bounds(increment > 0);
5289        let min_value = match s.options.min_value {
5290            None | Some(SeqBound::NoBound) => def_min,
5291            Some(SeqBound::Value(n)) => n,
5292        };
5293        let max_value = match s.options.max_value {
5294            None | Some(SeqBound::NoBound) => def_max,
5295            Some(SeqBound::Value(n)) => n,
5296        };
5297        if min_value > max_value {
5298            return Err(EngineError::Unsupported(alloc::format!(
5299                "MINVALUE ({min_value}) must be <= MAXVALUE ({max_value})"
5300            )));
5301        }
5302        let start = s
5303            .options
5304            .start
5305            .unwrap_or(if increment > 0 { min_value } else { max_value });
5306        // v7.39 (round 244) — PG splits the refusal into two named cases
5307        // (22023): below MINVALUE and above MAXVALUE.
5308        if start < min_value {
5309            return Err(EngineError::Unsupported(alloc::format!(
5310                "START value ({start}) cannot be less than MINVALUE ({min_value})"
5311            )));
5312        }
5313        if start > max_value {
5314            return Err(EngineError::Unsupported(alloc::format!(
5315                "START value ({start}) cannot be greater than MAXVALUE ({max_value})"
5316            )));
5317        }
5318        let cache = s.options.cache.unwrap_or(1);
5319        if cache < 1 {
5320            return Err(EngineError::Unsupported("CACHE must be >= 1".into()));
5321        }
5322        let cycle = s.options.cycle.unwrap_or(false);
5323        let owned_by = match s.options.owned_by {
5324            None | Some(spg_sql::ast::SequenceOwnedBy::None) => None,
5325            Some(spg_sql::ast::SequenceOwnedBy::Column { table, column }) => Some((table, column)),
5326        };
5327        let def = SequenceDef {
5328            name: s.name.clone(),
5329            data_type: dt,
5330            start,
5331            increment,
5332            min_value,
5333            max_value,
5334            cache,
5335            cycle,
5336            owned_by,
5337            last_value: start,
5338            is_called: false,
5339            // v7.39 (read01 round 60) — whoever runs CREATE SEQUENCE owns it.
5340            owner: Some(alloc::string::String::from(self.current_role())),
5341            acl: alloc::vec::Vec::new(),
5342        };
5343        // v7.39 (read01 round 46) — PG's IF NOT EXISTS skip NOTICE. The
5344        // storage call swallows the collision when the flag is set, so
5345        // detect it here before handing over.
5346        if s.if_not_exists && self.active_catalog().has_sequence(&s.name) {
5347            self.notice(alloc::format!(
5348                "relation {:?} already exists, skipping",
5349                s.name
5350            ));
5351        }
5352        self.active_catalog_mut()
5353            .create_sequence(def, s.if_not_exists)
5354            .map_err(EngineError::Storage)?;
5355        Ok(QueryResult::CommandOk {
5356            affected: 0,
5357            modified_catalog: self.catalog_change_is_committed(),
5358        })
5359    }
5360
5361    /// v7.17.0 — `ALTER SEQUENCE` engine path. Re-uses the catalog
5362    /// `alter_sequence` merge helper.
5363    pub(crate) fn exec_alter_sequence(
5364        &mut self,
5365        s: spg_sql::ast::AlterSequenceStatement,
5366    ) -> Result<QueryResult, EngineError> {
5367        use spg_sql::ast::SeqBound;
5368        // v7.29 (round-23a) - implicit serial sequences materialise
5369        // on first address, ALTER SEQUENCE included.
5370        self.ensure_implicit_sequence(&s.name);
5371        // v7.39 (read01 round 49) — RENAME TO is its own form, not an option.
5372        if let Some(new) = s.rename_to {
5373            self.active_catalog_mut()
5374                .rename_sequence(&s.name, &new)
5375                .map_err(EngineError::Storage)?;
5376            return Ok(QueryResult::CommandOk {
5377                affected: 0,
5378                modified_catalog: self.catalog_change_is_committed(),
5379            });
5380        }
5381        let cat = self.active_catalog_mut();
5382        if !cat.has_sequence(&s.name) {
5383            if s.if_exists {
5384                return Ok(QueryResult::CommandOk {
5385                    affected: 0,
5386                    modified_catalog: false,
5387                });
5388            }
5389            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5390                alloc::format!("sequence {:?} does not exist", s.name),
5391            )));
5392        }
5393        let min_value = match s.options.min_value {
5394            None => None,
5395            Some(SeqBound::NoBound) => None, // NO MINVALUE → keep current
5396            Some(SeqBound::Value(n)) => Some(n),
5397        };
5398        let max_value = match s.options.max_value {
5399            None => None,
5400            Some(SeqBound::NoBound) => None,
5401            Some(SeqBound::Value(n)) => Some(n),
5402        };
5403        let owned_by = s.options.owned_by.map(|ob| match ob {
5404            spg_sql::ast::SequenceOwnedBy::None => None,
5405            spg_sql::ast::SequenceOwnedBy::Column { table, column } => Some((table, column)),
5406        });
5407        cat.alter_sequence(
5408            &s.name,
5409            s.options.increment,
5410            min_value,
5411            max_value,
5412            s.options.start,
5413            s.options.restart,
5414            s.options.cache,
5415            s.options.cycle,
5416            owned_by,
5417        )
5418        .map_err(EngineError::Storage)?;
5419        Ok(QueryResult::CommandOk {
5420            affected: 0,
5421            modified_catalog: self.catalog_change_is_committed(),
5422        })
5423    }
5424
5425    /// v7.17.0 Phase 1.2 — `CREATE VIEW` engine path. Stores the
5426    /// Display-rendered body verbatim in the catalog; SELECT-from-
5427    /// view at exec time re-parses + prepends as a synthetic CTE.
5428    pub(crate) fn exec_create_view(
5429        &mut self,
5430        s: spg_sql::ast::CreateViewStatement,
5431    ) -> Result<QueryResult, EngineError> {
5432        // v7.39.2 — a name twice in the view's own column list. Both
5433        // engines refuse it; SPG built the view and every reference to
5434        // the name after that was ambiguous.
5435        if let Some(dup) = first_duplicate(
5436            s.columns.iter().map(alloc::string::String::as_str),
5437            self.speaks_mysql,
5438        ) {
5439            return Err(EngineError::Unsupported(duplicate_column_message(
5440                &dup,
5441                self.speaks_mysql,
5442            )));
5443        }
5444        // v7.39 (round 469) — same as the temporary sequence above: the
5445        // keyword parsed and was dropped, so the view was permanent and
5446        // every other connection could select from it.
5447        if s.temporary {
5448            let logical = s.name.clone();
5449            let mut inner = s;
5450            inner.temporary = false;
5451            inner.name = self.session_temp_name(&logical);
5452            let result = self.exec_create_view(inner)?;
5453            self.temp_views.insert(logical);
5454            self.refresh_temp_prefix();
5455            return Ok(result);
5456        }
5457        // v7.39 (round 151) — PG rejects data-modifying CTEs in a view
5458        // body (DefineView, view.c): the definition would run the write
5459        // on every reference. Read-only WITH is fine.
5460        if s.body.ctes.iter().any(|c| c.body.is_modifying()) {
5461            return Err(EngineError::Unsupported(
5462                "views must not contain data-modifying statements in WITH".into(),
5463            ));
5464        }
5465        // v7.39 (read01 round 81) — CREATE OR REPLACE VIEW may only APPEND
5466        // columns; PG forbids renaming, dropping, reordering or retyping an
5467        // existing column ("cannot change name of view column …", "cannot drop
5468        // columns from view", "cannot change data type of view column …"). SPG
5469        // let every one of these through and silently swapped the view's shape,
5470        // so a downstream `SELECT known_col FROM v` would start resolving to a
5471        // different column, or vanish — data corruption disguised as a DDL.
5472        if s.or_replace && self.active_catalog().has_view(&s.name) {
5473            self.check_view_replace_columns(&s)?;
5474        }
5475        // v7.39 (round 700) — the BODY has to resolve. PG analyses a view
5476        // definition at CREATE time, so `CREATE VIEW v AS SELECT * FROM
5477        // nosuch` is `relation "nosuch" does not exist`. SPG stored it and
5478        // reported success, leaving a view that appears in `pg_views`, that
5479        // every SELECT against fails, and that a dump then carries forward
5480        // — a broken object made by a statement that said it worked.
5481        //
5482        // The probe is `view_output_columns`, which the OR REPLACE path
5483        // already runs: a `LIMIT 0` execution of the same body. It resolves
5484        // relations and columns without producing rows, so the check costs
5485        // one empty plan and cannot disagree with what the view will do,
5486        // because it IS what the view will do.
5487        self.view_output_columns(&s.body, &s.columns)?;
5488        // Render the SELECT body to canonical form so the catalog
5489        // round-trips a deterministic source (no whitespace /
5490        // comment surprises in the on-disk snapshot).
5491        let columns = s.columns.clone();
5492        let name = s.name.clone();
5493        let or_replace = s.or_replace;
5494        let if_not_exists = s.if_not_exists;
5495        // v7.39 (round 132) — persist WITH CHECK OPTION as a u8 (0/1/2).
5496        let check_option = match s.check_option {
5497            None => 0,
5498            Some(spg_sql::ast::ViewCheckOption::Local) => 1,
5499            Some(spg_sql::ast::ViewCheckOption::Cascaded) => 2,
5500        };
5501        let body_repr = alloc::format!("{}", spg_sql::ast::Statement::Select(s.body));
5502        let def = spg_storage::ViewDef {
5503            name,
5504            columns,
5505            body: body_repr,
5506            check_option,
5507        };
5508        self.active_catalog_mut()
5509            .create_view(def, or_replace, if_not_exists)
5510            .map_err(EngineError::Storage)?;
5511        Ok(QueryResult::CommandOk {
5512            affected: 0,
5513            modified_catalog: self.catalog_change_is_committed(),
5514        })
5515    }
5516
5517    /// The (name, type) of each column a view body produces. Runs the body
5518    /// through the real executor with a zero-row bound, so it reflects exactly
5519    /// what a SELECT from the view would return — column overrides, view-on-view
5520    /// expansion, joins and all. Types come from the empty result's schema.
5521    pub(crate) fn view_output_columns(
5522        &self,
5523        body: &spg_sql::ast::SelectStatement,
5524        overrides: &[String],
5525    ) -> Result<alloc::vec::Vec<(String, spg_storage::DataType)>, EngineError> {
5526        let mut probe = body.clone();
5527        probe.limit = Some(spg_sql::ast::LimitExpr::Literal(0));
5528        let QueryResult::Rows { mut columns, .. } =
5529            self.exec_select_cancel(&probe, crate::CancelToken::none())?
5530        else {
5531            return Err(EngineError::Unsupported(
5532                "view body must be a row-returning SELECT".into(),
5533            ));
5534        };
5535        for (i, ov) in overrides.iter().enumerate() {
5536            if let Some(c) = columns.get_mut(i) {
5537                c.name = ov.clone();
5538            }
5539        }
5540        Ok(columns.into_iter().map(|c| (c.name, c.ty)).collect())
5541    }
5542
5543    /// PG's CREATE OR REPLACE VIEW column rule: the new column list must be the
5544    /// old one, optionally with columns appended. Same names, same order, same
5545    /// types for every pre-existing position.
5546    fn check_view_replace_columns(
5547        &self,
5548        s: &spg_sql::ast::CreateViewStatement,
5549    ) -> Result<(), EngineError> {
5550        let old_def = self.active_catalog().view(&s.name).cloned();
5551        let Some(old_def) = old_def else {
5552            return Ok(());
5553        };
5554        let old_body = match spg_sql::parser::parse_statement(&old_def.body) {
5555            Ok(spg_sql::ast::Statement::Select(b)) => b,
5556            // A body we can no longer parse is not something to block a replace
5557            // on — let the replace proceed rather than wedge the view.
5558            _ => return Ok(()),
5559        };
5560        let old_cols = self.view_output_columns(&old_body, &old_def.columns)?;
5561        let new_cols = self.view_output_columns(&s.body, &s.columns)?;
5562        if new_cols.len() < old_cols.len() {
5563            return Err(EngineError::Unsupported(
5564                "cannot drop columns from view".into(),
5565            ));
5566        }
5567        for (old, new) in old_cols.iter().zip(new_cols.iter()) {
5568            if old.0 != new.0 {
5569                return Err(EngineError::Unsupported(alloc::format!(
5570                    "cannot change name of view column \"{}\" to \"{}\"",
5571                    old.0,
5572                    new.0
5573                )));
5574            }
5575            if old.1 != new.1 {
5576                return Err(EngineError::Unsupported(alloc::format!(
5577                    "cannot change data type of view column \"{}\" from {} to {}",
5578                    old.0,
5579                    crate::system_catalog::pg_data_type_text(old.1),
5580                    crate::system_catalog::pg_data_type_text(new.1),
5581                )));
5582            }
5583        }
5584        Ok(())
5585    }
5586
5587    /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM (…)` engine
5588    /// path. Registers the enum in the catalog with order-
5589    /// preserving labels. PG semantics: CREATE TYPE errors if the
5590    /// name is taken (no IF NOT EXISTS).
5591    pub(crate) fn exec_create_type(
5592        &mut self,
5593        s: spg_sql::ast::CreateTypeStatement,
5594    ) -> Result<QueryResult, EngineError> {
5595        // Name-collision check against tables / sequences / views /
5596        // materialized views.
5597        let cat = self.active_catalog();
5598        if cat.get(&s.name).is_some() {
5599            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5600                alloc::format!("type {:?} would shadow an existing table", s.name),
5601            )));
5602        }
5603        if cat.has_sequence(&s.name) {
5604            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5605                alloc::format!("type {:?} would shadow an existing sequence", s.name),
5606            )));
5607        }
5608        if cat.has_view(&s.name) {
5609            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5610                alloc::format!("type {:?} would shadow an existing view", s.name),
5611            )));
5612        }
5613        // v7.37.42-T2 ζ-B — pre-check collision with the
5614        // composite registry too, so creating ENUM with a name
5615        // already used by a composite (or vice versa) fails
5616        // uniformly regardless of which kind comes first.
5617        if cat.composite_types().contains_key(&s.name) {
5618            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5619                alloc::format!("type {:?} already exists", s.name),
5620            )));
5621        }
5622        if cat.enum_types().contains_key(&s.name) {
5623            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5624                alloc::format!("type {:?} already exists", s.name),
5625            )));
5626        }
5627        if cat.domain_types().contains_key(&s.name) {
5628            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5629                alloc::format!("type {:?} already exists", s.name),
5630            )));
5631        }
5632        // v7.37.42-T2 ζ-B — composite types now live in their own
5633        // catalog registry (composite_types), parallel to enum_types
5634        // / domain_types. ENUM stays in enum_types as before.
5635        match s.kind {
5636            spg_sql::ast::TypeKind::Enum { labels } => {
5637                if labels.is_empty() {
5638                    return Err(EngineError::Unsupported(
5639                        "CREATE TYPE … AS ENUM requires at least one label".into(),
5640                    ));
5641                }
5642                // Reject duplicate labels per PG.
5643                for i in 0..labels.len() {
5644                    for j in (i + 1)..labels.len() {
5645                        if labels[i] == labels[j] {
5646                            return Err(EngineError::Unsupported(alloc::format!(
5647                                "CREATE TYPE {:?}: duplicate ENUM label {:?}",
5648                                s.name,
5649                                labels[i]
5650                            )));
5651                        }
5652                    }
5653                }
5654                let def = spg_storage::EnumDef {
5655                    name: s.name.clone(),
5656                    labels,
5657                };
5658                self.active_catalog_mut()
5659                    .create_enum_type(def)
5660                    .map_err(EngineError::Storage)?;
5661            }
5662            spg_sql::ast::TypeKind::Composite {
5663                fields,
5664                field_user_types,
5665            } => {
5666                // v7.39 (round 769, F31 tranche 5 #140) — an attribute-less
5667                // composite is legal PG (`CREATE TYPE x AS ()`, measured); the
5668                // old engine-side guard doubled the parser's former refusal.
5669                // Reject duplicate field names per PG.
5670                for i in 0..fields.len() {
5671                    for j in (i + 1)..fields.len() {
5672                        if fields[i].0.eq_ignore_ascii_case(&fields[j].0) {
5673                            return Err(EngineError::Unsupported(alloc::format!(
5674                                "CREATE TYPE {:?}: duplicate composite field {:?}",
5675                                s.name,
5676                                fields[i].0
5677                            )));
5678                        }
5679                    }
5680                }
5681                // Resolve each field's ColumnTypeName → DataType.
5682                let resolved_fields = fields
5683                    .into_iter()
5684                    .map(|(fname, fty)| (fname, column_type_to_data_type(fty)))
5685                    .collect::<alloc::vec::Vec<_>>();
5686                // v7.39 (round 264) — a field naming another COMPOSITE keeps
5687                // that name; the engine resolves the inner record through it.
5688                let cat = self.active_catalog();
5689                let field_user_types: alloc::vec::Vec<Option<alloc::string::String>> =
5690                    field_user_types
5691                        .into_iter()
5692                        .map(|n| n.filter(|n| cat.composite_types().contains_key(n)))
5693                        .collect();
5694                let def = spg_storage::CompositeDef {
5695                    name: s.name.clone(),
5696                    fields: resolved_fields,
5697                    field_user_types,
5698                };
5699                self.active_catalog_mut()
5700                    .create_composite_type(def)
5701                    .map_err(EngineError::Storage)?;
5702            }
5703        }
5704        Ok(QueryResult::CommandOk {
5705            affected: 0,
5706            modified_catalog: self.catalog_change_is_committed(),
5707        })
5708    }
5709    /// v7.39 (round 260) — `ALTER DOMAIN`. Every form used to be
5710    /// swallowed by the parser's pg_dump no-op arm: success reported,
5711    /// nothing changed. Constraint names and the error wordings are PG's,
5712    /// probed live.
5713    pub(crate) fn exec_alter_domain(
5714        &mut self,
5715        name: &str,
5716        action: spg_sql::ast::AlterDomainAction,
5717    ) -> Result<QueryResult, EngineError> {
5718        use spg_sql::ast::AlterDomainAction as A;
5719        let not_found = || {
5720            EngineError::Storage(spg_storage::StorageError::Corrupt(alloc::format!(
5721                "type {name:?} does not exist"
5722            )))
5723        };
5724        if !self.active_catalog().domain_types().contains_key(name) {
5725            return Err(not_found());
5726        }
5727        match action {
5728            A::AddConstraint { name: cname, check } => {
5729                let dom = self
5730                    .active_catalog()
5731                    .domain_types()
5732                    .get(name)
5733                    .ok_or_else(not_found)?;
5734                // PG's auto-name for an unnamed ALTER-added check follows
5735                // the same `<domain>_check{n}` sequence as CREATE DOMAIN.
5736                let cname = match cname {
5737                    Some(c) => c,
5738                    None => {
5739                        let mut i = dom.checks.len();
5740                        loop {
5741                            let cand = if i == 0 {
5742                                alloc::format!("{name}_check")
5743                            } else {
5744                                alloc::format!("{name}_check{i}")
5745                            };
5746                            if !dom.checks.iter().any(|c| c.name == cand) {
5747                                break cand;
5748                            }
5749                            i += 1;
5750                        }
5751                    }
5752                };
5753                if dom.checks.iter().any(|c| c.name == cname) {
5754                    return Err(EngineError::Unsupported(alloc::format!(
5755                        "constraint \"{cname}\" for domain \"{name}\" already exists"
5756                    )));
5757                }
5758                let expr = alloc::format!("{check}");
5759                let mut def = dom.clone();
5760                def.checks
5761                    .push(spg_storage::DomainCheck { name: cname, expr });
5762                self.replace_domain(name, def)?;
5763            }
5764            A::DropConstraint {
5765                name: cname,
5766                if_exists,
5767            } => {
5768                let mut def = self
5769                    .active_catalog()
5770                    .domain_types()
5771                    .get(name)
5772                    .ok_or_else(not_found)?
5773                    .clone();
5774                let before = def.checks.len();
5775                def.checks.retain(|c| c.name != cname);
5776                if def.checks.len() == before {
5777                    if if_exists {
5778                        return Ok(QueryResult::CommandOk {
5779                            affected: 0,
5780                            modified_catalog: false,
5781                        });
5782                    }
5783                    return Err(EngineError::Unsupported(alloc::format!(
5784                        "constraint \"{cname}\" of domain \"{name}\" does not exist"
5785                    )));
5786                }
5787                self.replace_domain(name, def)?;
5788            }
5789            A::SetDefault(e) => {
5790                let mut def = self
5791                    .active_catalog()
5792                    .domain_types()
5793                    .get(name)
5794                    .ok_or_else(not_found)?
5795                    .clone();
5796                def.default = Some(alloc::format!("{e}"));
5797                self.replace_domain(name, def)?;
5798            }
5799            A::DropDefault => {
5800                let mut def = self
5801                    .active_catalog()
5802                    .domain_types()
5803                    .get(name)
5804                    .ok_or_else(not_found)?
5805                    .clone();
5806                def.default = None;
5807                self.replace_domain(name, def)?;
5808            }
5809            A::SetNotNull | A::DropNotNull => {
5810                // v7.39 (round 260) — SET NOT NULL must reject when an
5811                // existing column of this domain already holds NULLs (PG:
5812                // `column "v" of table "adt" contains null values`).
5813                if matches!(action, A::SetNotNull) {
5814                    let snap = self.current_snapshot();
5815                    let cat = self.active_catalog();
5816                    let mut offender: Option<(alloc::string::String, alloc::string::String)> = None;
5817                    'outer: for tname in cat.table_names() {
5818                        let Some(table) = cat.get(&tname) else {
5819                            continue;
5820                        };
5821                        let cols = table.schema().columns.clone();
5822                        let idxs: alloc::vec::Vec<usize> = cols
5823                            .iter()
5824                            .enumerate()
5825                            .filter(|(_, c)| c.user_domain_type.as_deref() == Some(name))
5826                            .map(|(i, _)| i)
5827                            .collect();
5828                        if idxs.is_empty() {
5829                            continue;
5830                        }
5831                        for (_, row) in table.scan_visible(&snap) {
5832                            for &i in &idxs {
5833                                if row.values.get(i).is_none_or(spg_storage::Value::is_null) {
5834                                    offender = Some((tname.clone(), cols[i].name.clone()));
5835                                    break 'outer;
5836                                }
5837                            }
5838                        }
5839                    }
5840                    if let Some((t, c)) = offender {
5841                        return Err(EngineError::Unsupported(alloc::format!(
5842                            "column \"{c}\" of table \"{t}\" contains null values"
5843                        )));
5844                    }
5845                }
5846                let mut def = self
5847                    .active_catalog()
5848                    .domain_types()
5849                    .get(name)
5850                    .ok_or_else(not_found)?
5851                    .clone();
5852                def.nullable = matches!(action, A::DropNotNull);
5853                self.replace_domain(name, def)?;
5854            }
5855            A::RenameTo(new_name) => {
5856                if self.active_catalog().domain_types().contains_key(&new_name) {
5857                    return Err(EngineError::Unsupported(alloc::format!(
5858                        "type {new_name:?} already exists"
5859                    )));
5860                }
5861                let mut def = self
5862                    .active_catalog()
5863                    .domain_types()
5864                    .get(name)
5865                    .ok_or_else(not_found)?
5866                    .clone();
5867                def.name = new_name.clone();
5868                self.active_catalog_mut().drop_domain_type(name);
5869                self.active_catalog_mut()
5870                    .create_domain_type(def)
5871                    .map_err(EngineError::Storage)?;
5872            }
5873        }
5874        Ok(QueryResult::CommandOk {
5875            affected: 0,
5876            modified_catalog: self.catalog_change_is_committed(),
5877        })
5878    }
5879
5880    /// v7.39 (round 260) — swap a domain definition in place.
5881    fn replace_domain(
5882        &mut self,
5883        name: &str,
5884        def: spg_storage::DomainDef,
5885    ) -> Result<(), EngineError> {
5886        self.active_catalog_mut().drop_domain_type(name);
5887        self.active_catalog_mut()
5888            .create_domain_type(def)
5889            .map_err(EngineError::Storage)
5890    }
5891
5892    /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base [DEFAULT
5893    /// expr] [NOT NULL] [CHECK (expr)]*` engine path. Stores the
5894    /// base type + Display-rendered CHECK / DEFAULT sources so
5895    /// INSERT/UPDATE on bound columns can re-eval the checks.
5896    pub(crate) fn exec_create_domain(
5897        &mut self,
5898        s: spg_sql::ast::CreateDomainStatement,
5899    ) -> Result<QueryResult, EngineError> {
5900        let cat = self.active_catalog();
5901        if cat.domain_types().contains_key(&s.name) {
5902            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5903                alloc::format!("domain {:?} already exists", s.name),
5904            )));
5905        }
5906        if cat.get(&s.name).is_some()
5907            || cat.has_sequence(&s.name)
5908            || cat.has_view(&s.name)
5909            || cat.enum_types().contains_key(&s.name)
5910        {
5911            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5912                alloc::format!("domain {:?} would shadow an existing object", s.name),
5913            )));
5914        }
5915        // v7.39 (round 259) — `CREATE DOMAIN child AS parent`: the parent
5916        // supplies the ultimate scalar type (the parser typed the unknown
5917        // name as Text), and its NAME is recorded so the check walk can
5918        // reach the parent's constraints — which an ALTER on the parent
5919        // must keep affecting, so the chain is walked at check time rather
5920        // than copied here (probed against PG).
5921        let mut base_domain: Option<alloc::string::String> = None;
5922        let mut base_type = column_type_to_data_type(s.base_type);
5923        if let Some(parent) = &s.base_domain {
5924            if let Some(pd) = cat.domain_types().get(parent) {
5925                base_type = pd.base_type;
5926                base_domain = Some(parent.clone());
5927            } else if !cat.enum_types().contains_key(parent) {
5928                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5929                    alloc::format!("type {parent:?} does not exist"),
5930                )));
5931            }
5932        }
5933        let default = s.default.as_ref().map(|e| alloc::format!("{e}"));
5934        // v7.39 (round 260) — PG names an unnamed domain CHECK
5935        // `<domain>_check`, then `_check1`, `_check2`, … (probed).
5936        let checks = s
5937            .checks
5938            .iter()
5939            .enumerate()
5940            .map(|(i, e)| spg_storage::DomainCheck {
5941                name: if i == 0 {
5942                    alloc::format!("{}_check", s.name)
5943                } else {
5944                    alloc::format!("{}_check{i}", s.name)
5945                },
5946                expr: alloc::format!("{e}"),
5947            })
5948            .collect::<Vec<_>>();
5949        let def = spg_storage::DomainDef {
5950            name: s.name.clone(),
5951            base_type,
5952            nullable: !s.not_null,
5953            default,
5954            checks,
5955            base_domain,
5956        };
5957        self.active_catalog_mut()
5958            .create_domain_type(def)
5959            .map_err(EngineError::Storage)?;
5960        Ok(QueryResult::CommandOk {
5961            affected: 0,
5962            modified_catalog: self.catalog_change_is_committed(),
5963        })
5964    }
5965
5966    /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] names`.
5967    pub(crate) fn exec_drop_domain(
5968        &mut self,
5969        names: &[String],
5970        if_exists: bool,
5971    ) -> Result<QueryResult, EngineError> {
5972        let mut removed = 0usize;
5973        for name in names {
5974            let was_present = self.active_catalog_mut().drop_domain_type(name);
5975            if was_present {
5976                removed += 1;
5977            } else if !if_exists {
5978                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
5979                    alloc::format!("domain {name:?} does not exist"),
5980                )));
5981            }
5982        }
5983        Ok(QueryResult::CommandOk {
5984            affected: removed,
5985            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
5986        })
5987    }
5988
5989    /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS] name`.
5990    /// Registers the schema in the catalog. Schema-qualified
5991    /// table references continue to strip the prefix at lookup
5992    /// time (prefix routing, not isolation — see project-next-
5993    /// docket for the v7.18+ real-isolation tracking).
5994    pub(crate) fn exec_create_schema(
5995        &mut self,
5996        name: String,
5997        if_not_exists: bool,
5998    ) -> Result<QueryResult, EngineError> {
5999        // v7.39 (read01 round 46) — PG's IF NOT EXISTS skip NOTICE.
6000        if if_not_exists && self.active_catalog().schema_exists(&name) {
6001            self.notice(alloc::format!("schema {name:?} already exists, skipping"));
6002        }
6003        self.active_catalog_mut()
6004            .create_schema(name, if_not_exists)
6005            .map_err(EngineError::Storage)?;
6006        Ok(QueryResult::CommandOk {
6007            affected: 0,
6008            modified_catalog: self.catalog_change_is_committed(),
6009        })
6010    }
6011
6012    /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] names`.
6013    /// Built-in schemas always reject the drop with a clear
6014    /// error.
6015    pub(crate) fn exec_drop_schema(
6016        &mut self,
6017        names: &[String],
6018        if_exists: bool,
6019    ) -> Result<QueryResult, EngineError> {
6020        let mut removed = 0usize;
6021        for name in names {
6022            let was_present = self
6023                .active_catalog_mut()
6024                .drop_schema(name)
6025                .map_err(EngineError::Storage)?;
6026            if was_present {
6027                removed += 1;
6028            } else if !if_exists {
6029                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6030                    alloc::format!("schema {name:?} does not exist"),
6031                )));
6032            } else {
6033                // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
6034                self.notice(alloc::format!("schema {name:?} does not exist, skipping"));
6035            }
6036        }
6037        Ok(QueryResult::CommandOk {
6038            affected: removed,
6039            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
6040        })
6041    }
6042
6043    /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] names`. Only
6044    /// ENUM types are catalogued today; other types silently
6045    /// no-op even outside IF EXISTS to mirror the prior
6046    /// "everything's text" lax stance.
6047    pub(crate) fn exec_drop_type(
6048        &mut self,
6049        names: &[String],
6050        if_exists: bool,
6051    ) -> Result<QueryResult, EngineError> {
6052        let mut removed = 0usize;
6053        for name in names {
6054            // v7.37.42-T2 ζ-B — DROP TYPE searches ENUM + COMPOSITE
6055            // registries (PG groups CREATE TYPE … AS ENUM and
6056            // CREATE TYPE … AS (…) under the same DROP TYPE
6057            // command).
6058            let cat = self.active_catalog_mut();
6059            let was_enum = cat.drop_enum_type(name);
6060            let was_composite = cat.drop_composite_type(name);
6061            if was_enum || was_composite {
6062                removed += 1;
6063            } else if !if_exists {
6064                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6065                    alloc::format!("type {name:?} does not exist"),
6066                )));
6067            } else {
6068                // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
6069                self.notice(alloc::format!("type {name:?} does not exist, skipping"));
6070            }
6071        }
6072        Ok(QueryResult::CommandOk {
6073            affected: removed,
6074            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
6075        })
6076    }
6077
6078    /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` engine path.
6079    /// Materialises the body at CREATE time (unless WITH NO DATA),
6080    /// stores the result as a regular `Table`, and registers the
6081    /// body source in the catalog so REFRESH can re-run it.
6082    pub(crate) fn exec_create_materialized_view(
6083        &mut self,
6084        s: spg_sql::ast::CreateMaterializedViewStatement,
6085    ) -> Result<QueryResult, EngineError> {
6086        // v7.39 (round 436) — `CREATE TEMPORARY TABLE x AS <select>` arrives
6087        // here (CTAS lowers to this node with `as_plain_table`). Same
6088        // treatment as the column-list form: build it under the session's
6089        // namespace prefix and remember it there.
6090        if s.temporary && s.as_plain_table {
6091            let logical = s.name.clone();
6092            let mut inner = s;
6093            inner.temporary = false;
6094            inner.name = self.session_temp_name(&logical);
6095            let result = self.exec_create_materialized_view(inner)?;
6096            self.temp_tables.insert(logical);
6097            self.refresh_temp_prefix();
6098            return Ok(result);
6099        }
6100        // v7.39 (round 151) — PG's matview wording differs from the
6101        // plain-view one (transformCreateTableAsStmt, analyze.c).
6102        if s.body.ctes.iter().any(|c| c.body.is_modifying()) {
6103            return Err(EngineError::Unsupported(
6104                "materialized views must not use data-modifying statements in WITH".into(),
6105            ));
6106        }
6107        // Name-collision check (table / view / sequence / mat-view).
6108        let cat = self.active_catalog();
6109        if cat.materialized_views().contains_key(&s.name) || cat.get(&s.name).is_some() {
6110            if s.if_not_exists {
6111                return Ok(QueryResult::CommandOk {
6112                    affected: 0,
6113                    modified_catalog: false,
6114                });
6115            }
6116            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6117                alloc::format!("materialized view {:?} already exists", s.name),
6118            )));
6119        }
6120        if cat.has_view(&s.name) {
6121            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6122                alloc::format!(
6123                    "materialized view {:?} would shadow an existing view",
6124                    s.name
6125                ),
6126            )));
6127        }
6128        if cat.has_sequence(&s.name) {
6129            return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6130                alloc::format!(
6131                    "materialized view {:?} would shadow an existing sequence",
6132                    s.name
6133                ),
6134            )));
6135        }
6136        // Render the body to canonical form for the registry.
6137        let body_repr = alloc::format!("{}", spg_sql::ast::Statement::Select(s.body.clone()));
6138        // Execute the body to learn the columns. With WITH DATA we
6139        // also materialise the rows; with WITH NO DATA we only need
6140        // the schema, so re-use a LIMIT 0 wrap to keep the column
6141        // inference path uniform without paying for the rows.
6142        let result = self.exec_select_cancel(&s.body, CancelToken::none())?;
6143        let (mut cols, rows) = match result {
6144            QueryResult::Rows { columns, rows } => (columns, rows),
6145            other => {
6146                return Err(EngineError::Unsupported(alloc::format!(
6147                    "CREATE MATERIALIZED VIEW body did not return rows: {other:?}"
6148                )));
6149            }
6150        };
6151        // Apply the column-rename list per PG semantics.
6152        if !s.columns.is_empty() {
6153            if s.columns.len() != cols.len() {
6154                return Err(EngineError::Unsupported(alloc::format!(
6155                    "CREATE MATERIALIZED VIEW {:?}: column list has {} names but body returns {}",
6156                    s.name,
6157                    s.columns.len(),
6158                    cols.len()
6159                )));
6160            }
6161            for (c, name) in cols.iter_mut().zip(s.columns.iter()) {
6162                c.name.clone_from(name);
6163            }
6164        }
6165        // Promote any synthetic-Text projections to their actual
6166        // observed types so the backing table accepts the rows.
6167        cols = infer_column_types(&cols, &rows);
6168        // v7.39.2 — `CREATE TABLE t AS SELECT 1 AS a, 2 AS a` built a
6169        // table with two columns named `a`, where both engines refuse.
6170        // Checked on the RESOLVED names rather than the AST, because
6171        // `SELECT *` does not carry them until the body has run — which
6172        // is also where PostgreSQL checks it (its target list, after
6173        // resolution). Before `create_table`, so a refusal leaves
6174        // nothing behind.
6175        if let Some(dup) = first_duplicate(cols.iter().map(|c| c.name.as_str()), self.speaks_mysql)
6176        {
6177            return Err(EngineError::Unsupported(duplicate_column_message(
6178                &dup,
6179                self.speaks_mysql,
6180            )));
6181        }
6182        let schema = spg_storage::TableSchema::new(s.name.clone(), cols);
6183        let cat = self.active_catalog_mut();
6184        cat.create_table(schema).map_err(EngineError::Storage)?;
6185        // v7.38.19 — the materialised row count is the statement's
6186        // answer, not a detail. PG tags CTAS and CREATE MATERIALIZED
6187        // VIEW `SELECT <n>`, and a driver reads that to learn how many
6188        // rows it wrote. Returning 0 here made every CTAS report writing
6189        // nothing while writing the right rows -- silent, and the wrong
6190        // half is the one a program acts on.
6191        let mut materialised = 0usize;
6192        if s.with_data {
6193            let table = cat
6194                .get_mut(&s.name)
6195                .expect("just-created materialized-view backing table must exist");
6196            for row in rows {
6197                table.insert(row).map_err(EngineError::Storage)?;
6198                materialised += 1;
6199            }
6200        }
6201        // v7.38 (read01 P6.49) — CTAS / SELECT INTO produce a plain table; only
6202        // a real MATERIALIZED VIEW gets a registry entry (and REFRESH support).
6203        if !s.as_plain_table {
6204            cat.register_materialized_view(s.name.clone(), body_repr);
6205            // v7.39 (round 737, S14/B3) — register for delta maintenance
6206            // when the body qualifies; the fan-out starts buffering from
6207            // the next statement on.
6208            if let Some(base) = matview_maintainable_base(&s.body) {
6209                self.matview_maintainable.insert(s.name.clone(), base);
6210            }
6211        }
6212        Ok(QueryResult::CommandOk {
6213            affected: materialised,
6214            modified_catalog: self.catalog_change_is_committed(),
6215        })
6216    }
6217
6218    /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
6219    /// [NO] DATA]`. Looks up the source, re-runs it, replaces the
6220    /// backing table's rows.
6221    pub(crate) fn exec_refresh_materialized_view(
6222        &mut self,
6223        name: &str,
6224        with_data: bool,
6225    ) -> Result<QueryResult, EngineError> {
6226        // v7.39 (round 699) — PG18 distinguishes the two ways this fails,
6227        // and SPG gave one sentence for both:
6228        //
6229        //   missing name        `relation "x" does not exist`
6230        //   exists, wrong kind  `"x" is not a materialized view`
6231        //
6232        // The second is the one that matters to a caller: it says the name
6233        // resolved and the OBJECT is not what the statement is for, which
6234        // is a different thing to go and check.
6235        //
6236        // Both were `StorageError::Corrupt`, the same wrapper round 698
6237        // found putting `corrupt on-disk format:` in front of a plain typo.
6238        // `Unsupported` carries no banner, and the wire's classifier reads
6239        // `relation "…" does not exist` for 42P01 already.
6240        let source = match self
6241            .active_catalog()
6242            .materialized_views()
6243            .get(name)
6244            .cloned()
6245        {
6246            Some(s) => s,
6247            None => {
6248                let exists = self.active_catalog().get(name).is_some();
6249                return Err(EngineError::Unsupported(if exists {
6250                    alloc::format!("\"{name}\" is not a materialized view")
6251                } else {
6252                    alloc::format!("relation \"{name}\" does not exist")
6253                }));
6254            }
6255        };
6256        let parsed = spg_sql::parser::parse_statement(&source).map_err(|e| {
6257            EngineError::Unsupported(alloc::format!(
6258                "materialized view {name:?} body re-parse failed: {e}"
6259            ))
6260        })?;
6261        let Statement::Select(body) = parsed else {
6262            return Err(EngineError::Unsupported(alloc::format!(
6263                "materialized view {name:?} body is not a SELECT (catalog corruption)"
6264            )));
6265        };
6266        // v7.39 (round 735, S14/B3) — the refresh watermark. When the
6267        // body's FULL dependency set is provable (plain stored tables
6268        // only — any CTE / union / subquery / expression source makes
6269        // the collector answer None) and no dependency's change
6270        // sequence moved since the last refresh, this REFRESH is an
6271        // O(1) no-op with an identical observable result. PG recomputes
6272        // unconditionally — this is the incremental-maintenance first
6273        // step its architecture doesn't have. WITH NO DATA never
6274        // no-ops (its contract is to EMPTY the view).
6275        let deps = if with_data {
6276            matview_dep_tables(&body)
6277        } else {
6278            None
6279        };
6280        if let Some(dep_tables) = &deps {
6281            let current: alloc::vec::Vec<(String, u64)> = dep_tables
6282                .iter()
6283                .map(|t| {
6284                    (
6285                        t.clone(),
6286                        self.table_change_seq.get(t.as_str()).copied().unwrap_or(0),
6287                    )
6288                })
6289                .collect();
6290            if self
6291                .matview_refresh_watermark
6292                .get(name)
6293                .is_some_and(|last| *last == current)
6294            {
6295                return Ok(QueryResult::CommandOk {
6296                    affected: 0,
6297                    modified_catalog: false,
6298                });
6299            }
6300            // v7.39 (round 737, S14/B3 knife 2) — INSERT-ONLY delta
6301            // application. The base changed; if this view is registered
6302            // maintainable, has a watermark (i.e. its buffer covers
6303            // everything since the last full refresh), did not
6304            // overflow, and every buffered change is an Insert, the new
6305            // rows run through the projection and APPEND — no truncate,
6306            // no rescan. Any delete / update / tombstone in the buffer
6307            // falls back to the full path this round (their row-map
6308            // machinery is the next knife). Either way the watermark
6309            // and buffer reset below.
6310            if with_data
6311                && self.matview_maintainable.contains_key(name)
6312                && self.matview_refresh_watermark.contains_key(name)
6313                && !self.matview_delta_overflow.contains(name)
6314                && self
6315                    .matview_delta_buf
6316                    .get(name)
6317                    .is_some_and(|b| !b.is_empty())
6318            {
6319                let buf = self.matview_delta_buf.remove(name).expect("checked above");
6320                // v7.39 (round 738) — ordered application: Insert /
6321                // Delete / Tombstone in ARRIVAL order (an insert later
6322                // deleted must land then leave). None = this buffer
6323                // cannot be applied (an Update, or no row map where one
6324                // is needed) -> the full path below.
6325                let outcome = self.apply_matview_delta_ordered(name, &body, &buf)?;
6326                if outcome.is_some() {
6327                    crate::MATVIEW_DELTA_APPLIED
6328                        .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
6329                } else {
6330                    crate::MATVIEW_DELTA_BAILED.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
6331                }
6332                if let Some(applied) = outcome {
6333                    let current: alloc::vec::Vec<(String, u64)> = dep_tables
6334                        .iter()
6335                        .map(|t| {
6336                            (
6337                                t.clone(),
6338                                self.table_change_seq.get(t.as_str()).copied().unwrap_or(0),
6339                            )
6340                        })
6341                        .collect();
6342                    self.matview_refresh_watermark
6343                        .insert(String::from(name), current);
6344                    return Ok(QueryResult::CommandOk {
6345                        affected: applied,
6346                        modified_catalog: self.catalog_change_is_committed(),
6347                    });
6348                }
6349            }
6350        }
6351        // Wipe the existing rows first (PG truncates the matview
6352        // and rebuilds; we approximate with an empty INSERT loop).
6353        {
6354            let cat = self.active_catalog_mut();
6355            let table = cat.get_mut(name).ok_or_else(|| {
6356                EngineError::Storage(spg_storage::StorageError::Corrupt(alloc::format!(
6357                    "materialized view {name:?} backing table missing"
6358                )))
6359            })?;
6360            table.truncate();
6361        }
6362        if !with_data {
6363            self.matview_refresh_watermark.remove(name);
6364            return Ok(QueryResult::CommandOk {
6365                affected: 0,
6366                modified_catalog: self.catalog_change_is_committed(),
6367            });
6368        }
6369        // v7.39 (round 738, S14/B3 knife 3) — a maintainable view's FULL
6370        // refresh scans the base table internally instead of running the
6371        // body SQL: same rows (single stored table, pure projection,
6372        // pure WHERE — that is what registration means), but each output
6373        // row's base RowId is in hand, which is the only place the
6374        // delete/tombstone row map can be built. Non-maintainable views
6375        // keep the SQL path and carry no map.
6376        let internal = if let Some(base) = matview_maintainable_base(&body) {
6377            let snap = self.current_snapshot();
6378            let t = self.active_catalog().get(&base).ok_or_else(|| {
6379                EngineError::Unsupported(alloc::format!(
6380                    "materialized view {name:?} base table {base:?} missing"
6381                ))
6382            })?;
6383            let base_cols = t.schema().columns.clone();
6384            let alias = body
6385                .from
6386                .as_ref()
6387                .and_then(|f| f.primary.alias.clone())
6388                .unwrap_or_else(|| base.clone());
6389            let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
6390            let mut pairs: alloc::vec::Vec<(u64, spg_storage::Row<'static>)> =
6391                alloc::vec::Vec::new();
6392            let t = self.active_catalog().get(&base).expect("checked above");
6393            for (i, row) in t.rows().iter().enumerate() {
6394                if !t.is_row_visible(i, &snap) {
6395                    continue;
6396                }
6397                if let Some(w) = &body.where_ {
6398                    let cond = eval::eval_expr(w, row, &ctx).map_err(EngineError::Eval)?;
6399                    if !crate::eval::predicate_is_true(&cond, "WHERE", ctx.mysql_dialect)? {
6400                        continue;
6401                    }
6402                }
6403                let mut vals = alloc::vec::Vec::with_capacity(body.items.len());
6404                for item in &body.items {
6405                    let spg_sql::ast::SelectItem::Expr { expr, .. } = item else {
6406                        unreachable!("maintainable admits Expr items only");
6407                    };
6408                    vals.push(eval::eval_expr(expr, row, &ctx).map_err(EngineError::Eval)?);
6409                }
6410                let rid = t
6411                    .rowids()
6412                    .get(i)
6413                    .copied()
6414                    .unwrap_or(spg_storage::row_header::RowId::UNASSIGNED);
6415                pairs.push((rid.0, spg_storage::Row::new(vals)));
6416            }
6417            Some(pairs)
6418        } else {
6419            None
6420        };
6421        if let Some(pairs) = internal {
6422            let cat = self.active_catalog_mut();
6423            let table = cat.get_mut(name).expect("backing table verified above");
6424            let mut map: alloc::collections::BTreeMap<u64, usize> =
6425                alloc::collections::BTreeMap::new();
6426            let affected = pairs.len();
6427            for (rid, row) in pairs {
6428                table.insert(row).map_err(EngineError::Storage)?;
6429                map.insert(rid, table.rows().len() - 1);
6430            }
6431            let expected = table.rows().len();
6432            self.matview_row_map
6433                .insert(String::from(name), (expected, map));
6434            if let Some(dep_tables) = deps {
6435                let current: alloc::vec::Vec<(String, u64)> = dep_tables
6436                    .iter()
6437                    .map(|t| {
6438                        (
6439                            t.clone(),
6440                            self.table_change_seq.get(t.as_str()).copied().unwrap_or(0),
6441                        )
6442                    })
6443                    .collect();
6444                self.matview_refresh_watermark
6445                    .insert(String::from(name), current);
6446            }
6447            self.matview_delta_buf.remove(name);
6448            self.matview_delta_overflow.remove(name);
6449            if let Some(base) = matview_maintainable_base(&body) {
6450                self.matview_maintainable.insert(String::from(name), base);
6451            }
6452            return Ok(QueryResult::CommandOk {
6453                affected,
6454                modified_catalog: self.catalog_change_is_committed(),
6455            });
6456        }
6457        self.matview_row_map.remove(name);
6458        let rows = match self.exec_select_cancel(&body, CancelToken::none())? {
6459            QueryResult::Rows { rows, .. } => rows,
6460            other => {
6461                return Err(EngineError::Unsupported(alloc::format!(
6462                    "REFRESH MATERIALIZED VIEW {name:?} body did not return rows: {other:?}"
6463                )));
6464            }
6465        };
6466        let cat = self.active_catalog_mut();
6467        let table = cat.get_mut(name).expect("backing table verified above");
6468        let affected = rows.len();
6469        for row in rows {
6470            table.insert(row).map_err(EngineError::Storage)?;
6471        }
6472        // v7.39 (round 735, S14/B3) — record what this full refresh saw.
6473        // Re-read the sequences AFTER the recompute: a write that landed
6474        // mid-refresh moves a seq past what we record only if it came
6475        // first (single-writer engine), so recording the pre-read values
6476        // could mask it; the post-read cannot.
6477        if let Some(dep_tables) = deps {
6478            let current: alloc::vec::Vec<(String, u64)> = dep_tables
6479                .iter()
6480                .map(|t| {
6481                    (
6482                        t.clone(),
6483                        self.table_change_seq.get(t.as_str()).copied().unwrap_or(0),
6484                    )
6485                })
6486                .collect();
6487            self.matview_refresh_watermark
6488                .insert(String::from(name), current);
6489        }
6490        // v7.39 (round 737) — a full refresh resets the delta machinery:
6491        // stale buffered changes are superseded, overflow clears, and
6492        // (re)registration keeps a view maintainable across restarts,
6493        // where CREATE never re-runs.
6494        self.matview_delta_buf.remove(name);
6495        self.matview_delta_overflow.remove(name);
6496        if let Some(base) = matview_maintainable_base(&body) {
6497            self.matview_maintainable.insert(String::from(name), base);
6498        } else {
6499            self.matview_maintainable.remove(name);
6500        }
6501        Ok(QueryResult::CommandOk {
6502            affected,
6503            modified_catalog: self.catalog_change_is_committed(),
6504        })
6505    }
6506
6507    /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
6508    /// names`. Drops the backing table + unregisters the source.
6509    pub(crate) fn exec_drop_materialized_view(
6510        &mut self,
6511        names: &[String],
6512        if_exists: bool,
6513    ) -> Result<QueryResult, EngineError> {
6514        let mut removed = 0usize;
6515        for name in names {
6516            let was_present = self
6517                .active_catalog_mut()
6518                .drop_materialized_view_source(name);
6519            if was_present {
6520                // Drop the backing table too.
6521                self.active_catalog_mut().drop_table(name);
6522                // v7.39 (round 737, S14/B3) — retire every maintenance
6523                // structure with the view.
6524                self.matview_maintainable.remove(name);
6525                self.matview_delta_buf.remove(name);
6526                self.matview_delta_overflow.remove(name);
6527                self.matview_refresh_watermark.remove(name);
6528                self.matview_row_map.remove(name);
6529                removed += 1;
6530            } else if !if_exists {
6531                return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6532                    alloc::format!("materialized view {name:?} does not exist"),
6533                )));
6534            }
6535        }
6536        Ok(QueryResult::CommandOk {
6537            affected: removed,
6538            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
6539        })
6540    }
6541
6542    /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]`.
6543    pub(crate) fn exec_drop_view(
6544        &mut self,
6545        names: &[String],
6546        if_exists: bool,
6547    ) -> Result<QueryResult, EngineError> {
6548        let mut removed = 0usize;
6549        for name in names {
6550            // v7.39 (round 469) — a bare DROP names the session's
6551            // temporary view first, the way `Catalog::drop_table` resolves
6552            // a temporary table.
6553            let key = self.active_catalog().view_key(name);
6554            let was_present = self.active_catalog_mut().drop_view(&key);
6555            if was_present && key != *name {
6556                self.temp_views.remove(name);
6557                self.refresh_temp_prefix();
6558            }
6559            if !was_present {
6560                if !if_exists {
6561                    // v7.39 (read01 round 89) — PG's 42P01 wording, without the
6562                    // "corrupt on-disk format:" prefix a Storage::Corrupt adds.
6563                    return Err(EngineError::Unsupported(alloc::format!(
6564                        "view \"{name}\" does not exist"
6565                    )));
6566                }
6567                // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
6568                self.notice(alloc::format!("view {name:?} does not exist, skipping"));
6569            }
6570            if was_present {
6571                removed += 1;
6572            }
6573        }
6574        Ok(QueryResult::CommandOk {
6575            affected: removed,
6576            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
6577        })
6578    }
6579
6580    /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]`.
6581    pub(crate) fn exec_drop_sequence(
6582        &mut self,
6583        names: &[String],
6584        if_exists: bool,
6585    ) -> Result<QueryResult, EngineError> {
6586        let mut removed = 0usize;
6587        for name in names {
6588            let key = self.active_catalog().sequence_key(name);
6589            let was_present = self.active_catalog_mut().drop_sequence(&key);
6590            if was_present && key != *name {
6591                self.temp_sequences.remove(name);
6592                self.refresh_temp_prefix();
6593            }
6594            if !was_present {
6595                if !if_exists {
6596                    return Err(EngineError::Storage(spg_storage::StorageError::Corrupt(
6597                        alloc::format!("sequence {name:?} does not exist"),
6598                    )));
6599                }
6600                // v7.39 (read01 round 46) — PG's IF EXISTS skip NOTICE.
6601                self.notice(alloc::format!("sequence {name:?} does not exist, skipping"));
6602            }
6603            if was_present {
6604                removed += 1;
6605            }
6606        }
6607        Ok(QueryResult::CommandOk {
6608            affected: removed,
6609            modified_catalog: removed > 0 && self.catalog_change_is_committed(),
6610        })
6611    }
6612}
6613
6614// ---- column-definition / DEFAULT / SET / enum helpers (lib.rs split 11) ----
6615
6616/// v7.9.21 — resolve a column's DEFAULT for INSERT-time
6617/// default-fill. Free fn (rather than `&self`) so callers
6618/// with an active `&mut Table` borrow can still use it.
6619/// Literal defaults take the cached path (`col.default`);
6620/// runtime defaults hit `clock_fn` at each call. mailrs G4.
6621/// v7.39 (read01 round 93) — truncate a generated identifier to PG's
6622/// NAMEDATALEN-1 (63) byte limit, on a UTF-8 char boundary so a
6623/// multi-byte name is never split mid-codepoint.
6624fn truncate_ident(name: &mut String) {
6625    const MAX: usize = 63;
6626    if name.len() <= MAX {
6627        return;
6628    }
6629    let mut cut = MAX;
6630    while cut > 0 && !name.is_char_boundary(cut) {
6631        cut -= 1;
6632    }
6633    name.truncate(cut);
6634}
6635
6636pub(crate) fn resolve_column_default_free(
6637    col: &ColumnSchema,
6638    clock_fn: Option<ClockFn>,
6639    // v7.39 (round 525) — the session, for a DEFAULT that names one.
6640    sess: Option<&crate::eval::DmlSession>,
6641) -> Result<Value<'static>, EngineError> {
6642    if let Some(rt) = &col.runtime_default {
6643        return eval_runtime_default_free(rt, col.ty, clock_fn, sess);
6644    }
6645    Ok(col.default.clone().unwrap_or(Value::Null))
6646}
6647
6648pub(crate) fn eval_runtime_default_free(
6649    rt: &str,
6650    ty: DataType,
6651    clock_fn: Option<ClockFn>,
6652    sess: Option<&crate::eval::DmlSession>,
6653) -> Result<Value<'static>, EngineError> {
6654    let s = rt.trim().to_ascii_lowercase();
6655    // v7.17.0 Phase 2.1 — also strip `(N)` precision suffix
6656    // so MySQL `CURRENT_TIMESTAMP(6)` resolves the same as
6657    // bare `CURRENT_TIMESTAMP`. SPG stores TIMESTAMP at fixed
6658    // microsecond resolution; the precision modifier is
6659    // parser-only.
6660    let with_no_parens = s.trim_end_matches("()");
6661    let canonical: &str = if let Some(open_idx) = with_no_parens.find('(') {
6662        if with_no_parens.ends_with(')') {
6663            &with_no_parens[..open_idx]
6664        } else {
6665            with_no_parens
6666        }
6667    } else {
6668        with_no_parens
6669    };
6670    let now_us = match clock_fn {
6671        Some(f) => f(),
6672        None => 0,
6673    };
6674    let v = match canonical {
6675        "now" | "current_timestamp" | "localtimestamp" => Value::Timestamp(now_us),
6676        "current_date" => Value::Date((now_us / 86_400_000_000) as i32),
6677        "current_time" | "localtime" => Value::Timestamp(now_us),
6678        // v7.17.0 — UUID generators in DEFAULT clauses. Required
6679        // for the canonical Django / Rails / Hibernate `id UUID
6680        // PRIMARY KEY DEFAULT gen_random_uuid()` pattern. Each
6681        // INSERT evaluates the function fresh; the per-row UUID
6682        // is the storage value, not a cached literal.
6683        "gen_random_uuid" | "uuid_generate_v4" => Value::Uuid(eval::gen_random_uuid_bytes()),
6684        // v7.39 (round 525) — anything else is EVALUATED, not refused.
6685        // PG takes any expression as a DEFAULT; the eight names above are
6686        // a fast path that skips a parse per row, and this was the whole
6687        // list SPG accepted — `DEFAULT current_setting('app.tenant')`,
6688        // `DEFAULT upper(…)`, `DEFAULT 2 * 3` all failed the INSERT.
6689        _ => {
6690            let expr = spg_sql::parser::parse_expression(rt).map_err(|e| {
6691                EngineError::Unsupported(alloc::format!(
6692                    "runtime DEFAULT expression {rt:?} does not parse: {e}"
6693                ))
6694            })?;
6695            let no_cols: [ColumnSchema; 0] = [];
6696            let mut ctx = eval::EvalContext::new(&no_cols, None);
6697            if let Some(sv) = sess {
6698                ctx = ctx.with_session(sv);
6699            }
6700            let row = spg_storage::Row::new(alloc::vec::Vec::new());
6701            let v = eval::eval_expr(&expr, &row, &ctx).map_err(|e| EngineError::Eval(e))?;
6702            return coerce_value(v, ty, "DEFAULT", 0);
6703        }
6704    };
6705    coerce_value(v, ty, "DEFAULT", 0)
6706}
6707
6708/// v7.9.21 — true when a DEFAULT expression needs INSERT-time
6709/// evaluation rather than being cacheable as a literal Value.
6710/// FunctionCall is the immediate case (`now()`,
6711/// `current_timestamp`). Literal expressions and simple sign-
6712/// flipped numerics still take the static-cache path.
6713/// v7.39 (RLS) — translate the parser's `PolicyCmd` to the storage one.
6714fn policy_cmd_to_storage(c: spg_sql::ast::PolicyCmd) -> spg_storage::PolicyCmd {
6715    use spg_sql::ast::PolicyCmd as A;
6716    use spg_storage::PolicyCmd as S;
6717    match c {
6718        A::All => S::All,
6719        A::Select => S::Select,
6720        A::Insert => S::Insert,
6721        A::Update => S::Update,
6722        A::Delete => S::Delete,
6723    }
6724}
6725
6726/// v7.38.19 — a DEFAULT that is a call to `nextval`, however it spells
6727/// its argument. `nextval('s')` and `nextval('s'::regclass)` are the
6728/// same column; `pg_dump` writes the second.
6729fn is_nextval_call(e: &Expr) -> bool {
6730    matches!(e, Expr::FunctionCall { name, args }
6731        if name.eq_ignore_ascii_case("nextval") && args.len() == 1)
6732}
6733
6734fn is_runtime_default_expr(expr: &Expr) -> bool {
6735    match expr {
6736        Expr::FunctionCall { .. } => true,
6737        Expr::Unary { expr, .. } => is_runtime_default_expr(expr),
6738        _ => false,
6739    }
6740}
6741
6742/// v7.38 (read01) — PG's canonical parenless deparse spelling for the SQL-
6743/// standard niladic keyword functions. The parser lowers `CURRENT_DATE` &c
6744/// to a synthetic `FunctionCall { name: "current_date", args: [] }`; PG's
6745/// `pg_get_expr` renders these as the bare uppercase keyword (not
6746/// `current_date()`), so a default that uses one must deparse the same way.
6747/// Returns `None` for a real function (`now()`) which keeps its call form.
6748fn pg_parenless_keyword(name: &str) -> Option<&'static str> {
6749    match name.to_ascii_lowercase().as_str() {
6750        "current_date" => Some("CURRENT_DATE"),
6751        "current_time" => Some("CURRENT_TIME"),
6752        "current_timestamp" => Some("CURRENT_TIMESTAMP"),
6753        "localtime" => Some("LOCALTIME"),
6754        "localtimestamp" => Some("LOCALTIMESTAMP"),
6755        "current_user" => Some("CURRENT_USER"),
6756        "session_user" => Some("SESSION_USER"),
6757        "current_role" => Some("CURRENT_ROLE"),
6758        "current_catalog" => Some("CURRENT_CATALOG"),
6759        _ => None,
6760    }
6761}
6762
6763/// v7.38 (read01) — deparse a column DEFAULT expression to the PG-compatible
6764/// source text cached on `ColumnSchema.default_text` (surfaced by
6765/// information_schema.columns.column_default / pg_attrdef / pg_get_expr).
6766///
6767/// SPG's `Expr` Display already matches PG's deparse for non-negative integer
6768/// / numeric / boolean literals, arithmetic (`(3 + 4)`), and ordinary function
6769/// calls (`now()`). This additionally matches PG for the shapes where Display
6770/// diverges: bare string literals (PG types them, `'hi'::text`), the parenless
6771/// SQL-standard keyword functions (`CURRENT_DATE`, not `current_date()`), and
6772/// negative numeric constants, which PG's `get_const_expr` folds into a typed
6773/// literal (`int DEFAULT -5` → `'-5'::integer`, `numeric DEFAULT -1.5` →
6774/// `'-1.5'::numeric`).
6775///
6776/// KNOWN Phase-2 residuals (fall through to Display, a valid but not
6777/// byte-identical-to-PG spelling — documented in the read01 checklist):
6778///   * integer literals wider than int4 (`bigint DEFAULT 5000000000` →
6779///     PG `'5000000000'::bigint`; SPG `5000000000`);
6780///   * string / numeric literals nested inside a larger expression, which PG
6781///     types per operand (`'hi' || 'there'` → PG `('hi'::text ||
6782///     'there'::text)`). Full parity needs PG's recursive `get_rule_expr`
6783///     constant-typing deparser.
6784fn deparse_default(expr: &Expr, col_ty: DataType) -> alloc::string::String {
6785    match expr {
6786        // Bare string literal → PG's typed-literal form `'…'::<coltype>`.
6787        // 7.38.1 S5.2 — the typed-literal cast must name the SQL type
6788        // (`text[]`), not information_schema's category word (`ARRAY`):
6789        // pg_dump copies this text into the dumped DEFAULT, and
6790        // `'{}'::ARRAY` parses nowhere — not even back into SPG.
6791        Expr::Literal(Literal::String(s)) => alloc::format!(
6792            "'{}'::{}",
6793            s.replace('\'', "''"),
6794            crate::conversions::pg_type_name_for_error(col_ty)
6795        ),
6796        // r1054 — an ALREADY-typed string literal re-parses as a Cast
6797        // node, and the generic Display arm below rendered it
6798        // `('dflt')::text` where the first pass wrote `'dflt'::text`:
6799        // two producers of default_text, two spellings, and the dump
6800        // round-trip stopped being a fixed point on exactly that line.
6801        // Same normalized shape as the bare-literal arm (PG stores a
6802        // default through the assignment cast and reports the column's
6803        // type, so re-normalizing to `col_ty` matches PG here too).
6804        Expr::Cast { expr: inner, .. }
6805            if matches!(inner.as_ref(), Expr::Literal(Literal::String(_))) =>
6806        {
6807            let Expr::Literal(Literal::String(s)) = inner.as_ref() else {
6808                unreachable!("guarded by matches!")
6809            };
6810            alloc::format!(
6811                "'{}'::{}",
6812                s.replace('\'', "''"),
6813                crate::conversions::pg_type_name_for_error(col_ty)
6814            )
6815        }
6816        // v7.38.19 — a call renders its arguments the way PostgreSQL
6817        // prints them, which for a typed string literal is
6818        // `'zs'::regclass` and not `('zs')::regclass`.
6819        //
6820        // The generic Display arm below parenthesises a Cast, so
6821        // `nextval('zs'::regclass)` — what `pg_dump` writes for a serial
6822        // column, and what a schema-diff tool compares — read back as
6823        // `nextval(('zs')::regclass)`. It re-parses here and the dump
6824        // round-trip is a fixed point, so this never broke anything of
6825        // ours; it broke the comparison with theirs, which is the bar.
6826        //
6827        // r1054 fixed the same spelling for a default that IS a cast.
6828        // This is the same fix one level in.
6829        // Narrow on purpose: only a call that CARRIES such an argument
6830        // is re-rendered. Taking every call broke `CURRENT_DATE`, which
6831        // the parser lowers to a zero-argument `current_date` whose
6832        // Display prints the keyword — this arm printed the lowering.
6833        // The existing default-text test caught it in the same minute.
6834        Expr::FunctionCall { name, args }
6835            if args.iter().any(|a| {
6836                matches!(a, Expr::Cast { expr: inner, .. }
6837                    if matches!(inner.as_ref(), Expr::Literal(Literal::String(_))))
6838            }) =>
6839        {
6840            let rendered: Vec<alloc::string::String> = args
6841                .iter()
6842                .map(|a| match a {
6843                    Expr::Cast {
6844                        expr: inner,
6845                        target,
6846                    } if matches!(inner.as_ref(), Expr::Literal(Literal::String(_))) => {
6847                        let Expr::Literal(Literal::String(lit)) = inner.as_ref() else {
6848                            unreachable!("guarded by matches!")
6849                        };
6850                        alloc::format!("'{}'::{target}", lit.replace('\'', "''"))
6851                    }
6852                    other => alloc::format!("{other}"),
6853                })
6854                .collect();
6855            alloc::format!("{name}({})", rendered.join(", "))
6856        }
6857        // Boolean literal → PG's lowercase `true` / `false` (SPG's Literal
6858        // Display emits uppercase `TRUE`).
6859        Expr::Literal(Literal::Bool(b)) => {
6860            alloc::string::String::from(if *b { "true" } else { "false" })
6861        }
6862        // Negative numeric constant: PG folds `- <lit>` into a typed Const.
6863        // The cast type is the *literal's* natural type (integer / numeric),
6864        // not the column type.
6865        Expr::Unary {
6866            op: spg_sql::ast::UnOp::Neg,
6867            expr: inner,
6868        } => match inner.as_ref() {
6869            Expr::Literal(Literal::Integer(n)) => alloc::format!("'-{n}'::integer"),
6870            Expr::Literal(Literal::Float(_) | Literal::NumericBig(_) | Literal::Numeric { .. }) => {
6871                alloc::format!("'-{inner}'::numeric")
6872            }
6873            _ => alloc::format!("{expr}"),
6874        },
6875        // Parenless SQL-standard keyword functions → bare uppercase keyword.
6876        Expr::FunctionCall { name, args } if args.is_empty() => {
6877            if let Some(kw) = pg_parenless_keyword(name) {
6878                alloc::string::String::from(kw)
6879            } else {
6880                alloc::format!("{expr}")
6881            }
6882        }
6883        _ => alloc::format!("{expr}"),
6884    }
6885}
6886
6887/// v7.39 (RLS) — deparse a policy `USING` / `WITH CHECK` qual to PG-compatible
6888/// text for pg_policy / pg_policies / pg_dump. SPG's `Expr` Display already
6889/// matches PG for column comparisons and operators; this recursively rewrites
6890/// the niladic SQL-standard keyword functions a policy qual commonly uses
6891/// (`current_user` → `CURRENT_USER`, &c) which Display would render as
6892/// `current_user()`. The stored form re-parses identically, so enforcement is
6893/// unaffected. (String-literal `::text` typing is the shared default_text
6894/// Phase-2 residual and is left to Display.)
6895pub(crate) fn deparse_policy_qual(e: &Expr) -> alloc::string::String {
6896    match e {
6897        Expr::FunctionCall { name, args } if args.is_empty() => pg_parenless_keyword(name)
6898            .map_or_else(|| alloc::format!("{e}"), alloc::string::String::from),
6899        Expr::Binary { lhs, op, rhs } => alloc::format!(
6900            "({} {op} {})",
6901            deparse_policy_qual(lhs),
6902            deparse_policy_qual(rhs)
6903        ),
6904        Expr::Unary { op, expr } => {
6905            use spg_sql::ast::UnOp;
6906            let inner = deparse_policy_qual(expr);
6907            match op {
6908                UnOp::Not => alloc::format!("(NOT {inner})"),
6909                UnOp::Neg => alloc::format!("(-{inner})"),
6910                UnOp::Plus => alloc::format!("(+{inner})"),
6911                UnOp::BitNot => alloc::format!("(~{inner})"),
6912            }
6913        }
6914        Expr::Cast { expr, target } => {
6915            alloc::format!("({}::{target})", deparse_policy_qual(expr))
6916        }
6917        Expr::IsNull { expr, negated } => {
6918            let inner = deparse_policy_qual(expr);
6919            if *negated {
6920                alloc::format!("({inner} IS NOT NULL)")
6921            } else {
6922                alloc::format!("({inner} IS NULL)")
6923            }
6924        }
6925        Expr::Like {
6926            expr,
6927            pattern,
6928            negated,
6929            case_insensitive,
6930        } => {
6931            let op = match (negated, case_insensitive) {
6932                (false, false) => "LIKE",
6933                (true, false) => "NOT LIKE",
6934                (false, true) => "ILIKE",
6935                (true, true) => "NOT ILIKE",
6936            };
6937            alloc::format!(
6938                "({} {op} {})",
6939                deparse_policy_qual(expr),
6940                deparse_policy_qual(pattern)
6941            )
6942        }
6943        Expr::FunctionCall { name, args } => {
6944            let rendered: alloc::vec::Vec<_> = args.iter().map(deparse_policy_qual).collect();
6945            alloc::format!("{name}({})", rendered.join(", "))
6946        }
6947        _ => alloc::format!("{e}"),
6948    }
6949}
6950
6951/// v7.17.0 Phase 1.4 — INSERT/UPDATE-time enum label check. When
6952/// `col_idx` has a registered label list, the cell value must be
6953/// NULL or one of the labels (case-sensitive per PG).
6954/// v7.17.0 Phase 3.P0-37 — validate + canonicalise a MySQL inline
6955/// SET cell. For non-SET columns this is a no-op pass-through.
6956///
6957/// Semantics:
6958///   * NULL preserved.
6959///   * Empty string → `''` (zero flags).
6960///   * Otherwise split on ',', trim each token, validate every
6961///     token against the column's variant list (error on miss),
6962///     de-dup, then re-emit in DEFINITION order joined by ','.
6963pub(crate) fn canonicalize_set_value(
6964    lookup: &alloc::collections::BTreeMap<usize, Vec<String>>,
6965    col_idx: usize,
6966    col_name: &str,
6967    value: Value<'static>,
6968) -> Result<Value<'static>, EngineError> {
6969    let Some(variants) = lookup.get(&col_idx) else {
6970        return Ok(value);
6971    };
6972    match value {
6973        Value::Null => Ok(Value::Null),
6974        Value::Text(s) => {
6975            if s.is_empty() {
6976                return Ok(Value::text(alloc::string::String::new()));
6977            }
6978            // Collect a presence-set of variant indices to keep
6979            // definition order + handle de-dup in one pass.
6980            let mut present = alloc::vec![false; variants.len()];
6981            for raw in s.split(',') {
6982                let tok = raw.trim();
6983                if tok.is_empty() {
6984                    continue;
6985                }
6986                let idx = variants.iter().position(|v| v == tok).ok_or_else(|| {
6987                    EngineError::Unsupported(alloc::format!(
6988                        "column {col_name:?}: invalid SET token {tok:?}; \
6989                         allowed: {variants:?}"
6990                    ))
6991                })?;
6992                present[idx] = true;
6993            }
6994            // Re-emit in definition order.
6995            let mut out = alloc::string::String::new();
6996            let mut first = true;
6997            for (i, keep) in present.iter().enumerate() {
6998                if !keep {
6999                    continue;
7000                }
7001                if !first {
7002                    out.push(',');
7003                }
7004                first = false;
7005                out.push_str(&variants[i]);
7006            }
7007            Ok(Value::text(out))
7008        }
7009        other => Err(EngineError::Unsupported(alloc::format!(
7010            "column {col_name:?}: SET-typed column expects TEXT, got {}",
7011            crate::conversions::pg_type_name_for_error_opt(other.data_type())
7012        ))),
7013    }
7014}
7015
7016pub(crate) fn enforce_enum_label(
7017    lookup: &alloc::collections::BTreeMap<usize, Vec<String>>,
7018    col_idx: usize,
7019    col_name: &str,
7020    value: &Value,
7021) -> Result<(), EngineError> {
7022    if let Some(labels) = lookup.get(&col_idx) {
7023        match value {
7024            Value::Null => Ok(()),
7025            Value::Text(s) => {
7026                if labels.iter().any(|l| l == s) {
7027                    Ok(())
7028                } else {
7029                    Err(EngineError::Unsupported(alloc::format!(
7030                        "column {col_name:?}: invalid enum label {s:?}; allowed: {labels:?}"
7031                    )))
7032                }
7033            }
7034            other => Err(EngineError::Unsupported(alloc::format!(
7035                "column {col_name:?}: enum-typed column expects TEXT, got {}",
7036                crate::conversions::pg_type_name_for_error_opt(other.data_type())
7037            ))),
7038        }
7039    } else {
7040        Ok(())
7041    }
7042}
7043
7044fn column_def_to_schema(c: ColumnDef, mysql: bool) -> Result<ColumnSchema, EngineError> {
7045    let ty = column_type_to_data_type(c.ty);
7046    let mut schema = ColumnSchema::new(c.name.clone(), ty, c.nullable);
7047    // user_type_ref is the raw ident the parser couldn't resolve
7048    // to a built-in; classification into enum vs domain happens
7049    // at exec_create_table where we have catalog access. We
7050    // park it temporarily as user_enum_type and the engine
7051    // promotes domain bindings to user_domain_type before the
7052    // table is stored.
7053    if let Some(name) = c.user_type_ref {
7054        schema.user_enum_type = Some(name);
7055    }
7056    // v7.17.0 Phase 2.1 — render the ON UPDATE expression to
7057    // canonical text (the engine re-parses at UPDATE time).
7058    if let Some(expr) = c.on_update_runtime {
7059        schema.on_update_runtime = Some(alloc::format!("{expr}"));
7060    }
7061    // v7.17.0 Phase 2.5 — bridge the AST `Collation` enum to the
7062    // storage one. Same variants, different crates (spg-storage
7063    // owns no dep on spg-sql).
7064    // v7.39 (round 370, M4 P4a) — under the MySQL dialect a TEXT column
7065    // with NO explicit `COLLATE` takes the folding default collation
7066    // (utf8mb4_uca1400_ai_ci), so it stores CaseInsensitive and the
7067    // read/write paths fold it. An explicit `COLLATE utf8mb4_bin` keeps
7068    // Binary (byte-wise) — both resolve to AST `Binary`, so the explicit
7069    // flag is what tells them apart.
7070    let is_text_col = matches!(
7071        ty,
7072        spg_storage::DataType::Text
7073            | spg_storage::DataType::Varchar(_)
7074            | spg_storage::DataType::Char(_)
7075    );
7076    // v7.39 (round 676) — carry the collation NAME as written, which
7077    // `Collation` below cannot: it folds C / POSIX / en_US / default into
7078    // one value. `pg_attribute.attcollation` reads this to answer 950 for a
7079    // column declared `COLLATE "C"` instead of the type's default 100.
7080    schema.collation_name = c.collation_name.clone();
7081    schema.collation = if mysql && is_text_col && !c.collation_explicit {
7082        spg_storage::Collation::CaseInsensitive
7083    } else {
7084        match c.collation {
7085            spg_sql::ast::Collation::Binary => spg_storage::Collation::Binary,
7086            spg_sql::ast::Collation::CaseInsensitive => spg_storage::Collation::CaseInsensitive,
7087        }
7088    };
7089    // v7.17.0 Phase 4.4 — MySQL `UNSIGNED` flag propagates to
7090    // storage so engine INSERT / UPDATE can range-check.
7091    schema.is_unsigned = c.is_unsigned;
7092    // v7.39 (round 386, type-fidelity epic P1) — declared TINYINT /
7093    // MEDIUMINT width, lost when the type collapsed to SmallInt / Int.
7094    // Drives the epic-P2 write-path range check.
7095    schema.mysql_int_width = c.mysql_int_width.map(|w| match w {
7096        spg_sql::ast::MysqlIntWidth::Tiny => spg_storage::MysqlIntWidth::Tiny,
7097        spg_sql::ast::MysqlIntWidth::Medium => spg_storage::MysqlIntWidth::Medium,
7098        spg_sql::ast::MysqlIntWidth::Small => spg_storage::MysqlIntWidth::Small,
7099        spg_sql::ast::MysqlIntWidth::Int => spg_storage::MysqlIntWidth::Int,
7100        spg_sql::ast::MysqlIntWidth::Big => spg_storage::MysqlIntWidth::Big,
7101    });
7102    // v7.39 (round 424, type-fidelity epic) — declared fractional-seconds
7103    // precision of a MySQL temporal column. Drives write-path truncation
7104    // and render padding; None keeps PG's full-microsecond behaviour.
7105    schema.mysql_fsp = c.mysql_fsp;
7106    schema.mysql_declared_timestamp = c.mysql_declared_timestamp;
7107    schema.mysql_float_md = c.mysql_float_md;
7108    // v7.39 (round 389, type-fidelity epic P4a) — a "real" SMALLINT /
7109    // INT UNSIGNED holds a range its signed storage tag cannot (65535 /
7110    // 4294967295), so widen the storage one step and record the declared
7111    // width for the range check + dump rendering. The `is_none()` guard
7112    // skips TINYINT UNSIGNED (i16 already holds 0..255) and MEDIUMINT
7113    // UNSIGNED (i32 already holds 0..16777215) — they keep their tag.
7114    if schema.is_unsigned && schema.mysql_int_width.is_none() {
7115        match schema.ty {
7116            spg_storage::DataType::SmallInt => {
7117                schema.ty = spg_storage::DataType::Int;
7118                schema.mysql_int_width = Some(spg_storage::MysqlIntWidth::Small);
7119            }
7120            spg_storage::DataType::Int => {
7121                schema.ty = spg_storage::DataType::BigInt;
7122                schema.mysql_int_width = Some(spg_storage::MysqlIntWidth::Int);
7123            }
7124            // v7.39 (round 471, epic P4b) — BIGINT UNSIGNED reaches
7125            // 18446744073709551615, which i64 cannot hold at all: SPG used
7126            // to REFUSE anything past 2^63-1 with `expected BIGINT, got
7127            // NUMERIC(0)`, so a MariaDB table with a real u64 in it could
7128            // not be loaded. Numeric is i128-backed with scale 0 and
7129            // already compares, orders, indexes and renders as an exact
7130            // integer; the width marker keeps the declared type for
7131            // SHOW CREATE and information_schema.
7132            spg_storage::DataType::BigInt => {
7133                schema.ty = spg_storage::DataType::Numeric {
7134                    precision: 20,
7135                    scale: 0,
7136                };
7137                schema.mysql_int_width = Some(spg_storage::MysqlIntWidth::Big);
7138            }
7139            _ => {}
7140        }
7141    }
7142    // v7.17.0 Phase 3.P0-36 — MySQL inline ENUM variant list.
7143    // INSERT validation lives in coerce_value (Text → Text path
7144    // with the column's variant list as the accept-set).
7145    schema.inline_enum_variants = c.inline_enum_variants;
7146    // v7.17.0 Phase 3.P0-37 — MySQL inline SET variant list.
7147    // INSERT canonicalisation (de-dup + sort by definition order)
7148    // lives in the exec_insert path next to the ENUM check.
7149    schema.inline_set_variants = c.inline_set_variants;
7150    // v7.37.7(sentori Epic 3 P1)— stored generated-column
7151    // expression. Carry the Display-form source to storage; the
7152    // engine re-parses and re-evaluates on every INSERT / UPDATE.
7153    if let Some(gen_expr) = c.generated_stored_expr {
7154        schema.generated_stored_expr = Some(alloc::format!("{gen_expr}"));
7155    }
7156    // v7.38 (read01) — GENERATED ALWAYS AS IDENTITY marker. The engine
7157    // rejects an explicit non-DEFAULT INSERT value for such a column
7158    // unless the statement carries OVERRIDING SYSTEM VALUE.
7159    schema.identity_always = c.identity_always;
7160    if let Some(default_expr) = c.default {
7161        // v7.38 (read01) — cache the PG-compatible source text of the DEFAULT
7162        // expression for catalog introspection, independent of the
7163        // literal/runtime split below (which loses the source spelling).
7164        schema.default_text = Some(deparse_default(&default_expr, ty));
7165        // v7.9.21 — distinguish literal defaults (evaluated once
7166        // at CREATE TABLE) from expression defaults (deferred to
7167        // INSERT). Function calls (`now()`, `current_timestamp`
7168        // — see v7.9.20 keyword promotion) take the runtime path.
7169        // Literals continue to cache. mailrs G4.
7170        // v7.38.19 — a `nextval(…)` DEFAULT is the column being
7171        // NUMBERED, not an expression to re-evaluate per row.
7172        //
7173        // Advancing a sequence needs a mutable catalog, and the context a
7174        // runtime DEFAULT is evaluated in does not hold one -- so this
7175        // stored the call as text and every INSERT that left the column
7176        // to its default answered `nextval() requires a sequence
7177        // resolver (read-only context)`. PostgreSQL 18.4 inserts.
7178        //
7179        // The OTHER spelling of the same column has worked since v7.22:
7180        // `ALTER TABLE … SET DEFAULT nextval(…)` lowers to the
7181        // auto-increment marker, because that is what `pg_dump` emits
7182        // for a serial column and imports were losing their numbering.
7183        // Two spellings of one column definition disagreed about whether
7184        // the column worked at all. This is the same lowering, reached
7185        // from the other side.
7186        if is_nextval_call(&default_expr) {
7187            if !matches!(ty, DataType::SmallInt | DataType::Int | DataType::BigInt) {
7188                return Err(EngineError::Unsupported(alloc::format!(
7189                    "auto-increment applies to integer columns only ({:?} is {ty:?})",
7190                    c.name
7191                )));
7192            }
7193            schema.auto_increment = true;
7194        } else if is_runtime_default_expr(&default_expr) {
7195            let display = alloc::format!("{default_expr}");
7196            schema = schema.with_runtime_default(display);
7197        } else {
7198            let raw = literal_expr_to_value(default_expr)?;
7199            // v7.39 (round 259) — a column whose type is a user type is
7200            // still typed with the parser's Text placeholder here; the
7201            // real type only arrives when the domain binding is resolved
7202            // (exec_create_table). Coercing now made `w wd DEFAULT 7`
7203            // fail outright — a hard error on valid SQL — so the domain
7204            // case keeps the raw value and is coerced there instead.
7205            let coerced = if schema.user_enum_type.is_some() {
7206                raw
7207            } else {
7208                coerce_value(raw, ty, &c.name, 0)?
7209            };
7210            schema = schema.with_default(coerced);
7211        }
7212    }
7213    if c.auto_increment {
7214        // AUTO_INCREMENT only makes sense on integer-shaped columns.
7215        if !matches!(ty, DataType::SmallInt | DataType::Int | DataType::BigInt) {
7216            return Err(EngineError::Unsupported(alloc::format!(
7217                "AUTO_INCREMENT requires an integer column type, got {ty:?}"
7218            )));
7219        }
7220        schema = schema.with_auto_increment();
7221    }
7222    Ok(schema)
7223}
7224
7225/// v7.12.4 — render a function arg list into the
7226/// canonical form the storage layer caches as
7227/// [`spg_storage::FunctionDef::args_repr`]. The catalogue uses
7228/// this string for both display + as a coarse signature key
7229/// for the (deferred) overload resolution v7.12.5+ adds.
7230fn render_function_args(args: &[spg_sql::ast::FunctionArg]) -> alloc::string::String {
7231    use core::fmt::Write;
7232    let mut out = alloc::string::String::from("(");
7233    for (i, a) in args.iter().enumerate() {
7234        if i > 0 {
7235            out.push_str(", ");
7236        }
7237        match a.mode {
7238            spg_sql::ast::FunctionArgMode::In => {}
7239            spg_sql::ast::FunctionArgMode::Out => out.push_str("OUT "),
7240            spg_sql::ast::FunctionArgMode::InOut => out.push_str("INOUT "),
7241        }
7242        if let Some(n) = &a.name {
7243            out.push_str(n);
7244            out.push(' ');
7245        }
7246        match &a.ty {
7247            spg_sql::ast::FunctionArgType::Typed(t) => {
7248                let _ = write!(out, "{t}");
7249            }
7250            spg_sql::ast::FunctionArgType::Raw(s) => out.push_str(s),
7251        }
7252    }
7253    out.push(')');
7254    out
7255}
7256
7257/// v7.39 (read01 round 48) — is `name` already taken by a constraint on this
7258/// table? Checks the stored names of foreign keys, uniqueness constraints and
7259/// CHECKs. Constraints written before FILE_VERSION 60 have no stored name, so
7260/// they can't collide here — they are still reachable by their synthesised
7261/// name through `resolve_constraint`.
7262fn constraint_name_taken(table: &spg_storage::Table, name: &str) -> bool {
7263    let sch = table.schema();
7264    sch.foreign_keys
7265        .iter()
7266        .any(|f| f.name.as_deref() == Some(name))
7267        || sch
7268            .uniqueness_constraints
7269            .iter()
7270            .any(|u| u.name.as_deref() == Some(name))
7271        || sch.checks.iter().any(|c| c.name.as_deref() == Some(name))
7272}
7273
7274/// v7.39 (read01 round 58) — lowercase hex, for the synthetic credential a
7275/// passwordless `CREATE ROLE` gets (it can't log in, but the record must not
7276/// carry an empty password).
7277fn hex_of(bytes: &[u8]) -> alloc::string::String {
7278    use core::fmt::Write as _;
7279    let mut s = alloc::string::String::with_capacity(bytes.len() * 2);
7280    for b in bytes {
7281        let _ = write!(s, "{b:02x}");
7282    }
7283    s
7284}
7285
7286/// v7.39 (round 282) — render one argument type the way PG's NOTICE does.
7287///
7288/// PG's grammar has two productions for a type name: the SQL-standard
7289/// KEYWORDS (`int`, `character varying`, `double precision`, …) become a
7290/// `SystemTypeName`, which deparses schema-qualified with the internal
7291/// name — `pg_catalog.int4`; anything else is an ordinary identifier and
7292/// survives verbatim. So `int` prints as `pg_catalog.int4` while the
7293/// equally valid `int4` prints as `int4`, and `date` — not a type keyword
7294/// in that production — prints as `date`. Every entry below was read off
7295/// live PG 18.4 rather than inferred from the list's shape.
7296fn pg_signature_type_name(raw: &str) -> alloc::string::String {
7297    let mut norm = alloc::string::String::new();
7298    for word in raw.split_whitespace() {
7299        if !norm.is_empty() {
7300            norm.push(' ');
7301        }
7302        norm.push_str(&word.to_ascii_lowercase());
7303    }
7304    let internal = match norm.as_str() {
7305        "int" | "integer" => "int4",
7306        "smallint" => "int2",
7307        "bigint" => "int8",
7308        "real" => "float4",
7309        "float" | "double precision" => "float8",
7310        "decimal" | "dec" | "numeric" => "numeric",
7311        "boolean" => "bool",
7312        "varchar" | "character varying" => "varchar",
7313        "char" | "character" => "bpchar",
7314        "time" | "time without time zone" => "time",
7315        "time with time zone" => "timetz",
7316        "timestamp" | "timestamp without time zone" => "timestamp",
7317        "timestamp with time zone" => "timestamptz",
7318        "interval" => "interval",
7319        "bit" => "bit",
7320        "bit varying" => "varbit",
7321        _ => return raw.into(),
7322    };
7323    alloc::format!("pg_catalog.{internal}")
7324}
7325
7326/// v7.39 (round 735, S14/B3) — the FULL set of stored tables a
7327/// materialized-view body reads, or `None` when that set cannot be
7328/// PROVEN (CTEs, unions, subqueries anywhere, any non-table FROM
7329/// source, a join whose ON carries a subquery…). `None` means "always
7330/// refresh fully" — the conservative direction; an under-collected set
7331/// here would be a WRONG no-op serving stale data, so every uncertain
7332/// shape bails.
7333impl Engine {
7334    /// v7.39 (round 737, S14/B3 knife 2) — run buffered INSERTs through
7335    /// the view's projection and append the survivors. The body is a
7336    /// registered-maintainable single-table pure projection, so each new
7337    /// base row maps to at most one view row: eval the WHERE (absent =
7338    /// keep), then each item, against the base row.
7339    /// v7.39 (round 738) — apply buffered changes in ARRIVAL order.
7340    /// `Ok(None)` = this buffer cannot be applied incrementally (an
7341    /// Update change; or a delete/tombstone with no valid row map) —
7342    /// the caller takes the full path. Inserts run the projection and
7343    /// append; deletes and tombstones resolve base RowIds through the
7344    /// row map and remove the view rows, keeping the map's positions
7345    /// and expected length exact after every step.
7346    fn apply_matview_delta_ordered(
7347        &mut self,
7348        name: &str,
7349        body: &spg_sql::ast::SelectStatement,
7350        buf: &[spg_storage::RowChange],
7351    ) -> Result<Option<usize>, EngineError> {
7352        use spg_sql::ast::SelectItem;
7353        let needs_map = buf
7354            .iter()
7355            .any(|c| !matches!(c, spg_storage::RowChange::Insert { .. }));
7356        if needs_map {
7357            let Some((expected, _)) = self.matview_row_map.get(name) else {
7358                return Ok(None);
7359            };
7360            let live = self
7361                .active_catalog()
7362                .get(name)
7363                .map(|t| t.rows().len())
7364                .unwrap_or(usize::MAX);
7365            if live != *expected {
7366                // A vacuum (or anything else) moved the backing rows.
7367                self.matview_row_map.remove(name);
7368                return Ok(None);
7369            }
7370        }
7371        let base = self
7372            .matview_maintainable
7373            .get(name)
7374            .cloned()
7375            .expect("caller checked registration");
7376        let base_cols = self
7377            .active_catalog()
7378            .get(&base)
7379            .ok_or_else(|| {
7380                EngineError::Unsupported(alloc::format!(
7381                    "materialized view {name:?} base table {base:?} missing"
7382                ))
7383            })?
7384            .schema()
7385            .columns
7386            .clone();
7387        let alias = body
7388            .from
7389            .as_ref()
7390            .and_then(|f| f.primary.alias.clone())
7391            .unwrap_or_else(|| base.clone());
7392        let mut applied = 0usize;
7393        for ch in buf {
7394            match ch {
7395                spg_storage::RowChange::Insert { row, rowid, .. } => {
7396                    let keep = if let Some(w) = &body.where_ {
7397                        let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
7398                        let cond = eval::eval_expr(w, row, &ctx).map_err(EngineError::Eval)?;
7399                        crate::eval::predicate_is_true(&cond, "WHERE", ctx.mysql_dialect)?
7400                    } else {
7401                        true
7402                    };
7403                    if !keep {
7404                        continue;
7405                    }
7406                    let mut vals = alloc::vec::Vec::with_capacity(body.items.len());
7407                    {
7408                        let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
7409                        for item in &body.items {
7410                            let SelectItem::Expr { expr, .. } = item else {
7411                                unreachable!("registration admits Expr items only");
7412                            };
7413                            vals.push(eval::eval_expr(expr, row, &ctx).map_err(EngineError::Eval)?);
7414                        }
7415                    }
7416                    let cat = self.active_catalog_mut();
7417                    let table = cat.get_mut(name).ok_or_else(|| {
7418                        EngineError::Storage(spg_storage::StorageError::Corrupt(alloc::format!(
7419                            "materialized view {name:?} backing table missing"
7420                        )))
7421                    })?;
7422                    table
7423                        .insert(spg_storage::Row::new(vals))
7424                        .map_err(EngineError::Storage)?;
7425                    let new_pos = table.rows().len() - 1;
7426                    if let Some((expected, map)) = self.matview_row_map.get_mut(name) {
7427                        map.insert(rowid.0, new_pos);
7428                        *expected += 1;
7429                    }
7430                    applied += 1;
7431                }
7432                spg_storage::RowChange::Delete { rowids, .. }
7433                | spg_storage::RowChange::Tombstone { rowids, .. } => {
7434                    // v7.39 (round 740) — TOMBSTONE the view row, never
7435                    // physically remove it. delete_rows on a mid-table
7436                    // position is O(table) in the persistent vec, and
7437                    // every surviving map entry would need shifting —
7438                    // measured 70 ms for THREE deletes over a 250k-row
7439                    // view. A tombstone is O(1), keeps every physical
7440                    // position (the map needs no shift and `expected`
7441                    // means what it says), and the view's readers
7442                    // already gate on MVCC visibility like any table.
7443                    // Vacuumed/compacted views change their length and
7444                    // the expected-length check catches it -> full.
7445                    for rid in rowids {
7446                        let Some((_, map)) = self.matview_row_map.get_mut(name) else {
7447                            unreachable!("needs_map gated above");
7448                        };
7449                        let Some(pos) = map.remove(&rid.0) else {
7450                            // A base row the WHERE filtered out — the
7451                            // view never held it; nothing to remove.
7452                            continue;
7453                        };
7454                        let v = self.writer_version_for_current_stmt();
7455                        let cat = self.active_catalog_mut();
7456                        let table = cat.get_mut(name).ok_or_else(|| {
7457                            EngineError::Storage(spg_storage::StorageError::Corrupt(
7458                                alloc::format!("materialized view {name:?} backing table missing"),
7459                            ))
7460                        })?;
7461                        let _ = table.mark_row_deleted(pos, v);
7462                        applied += 1;
7463                    }
7464                }
7465                // v7.39 (round 739) — the Update arm: four quadrants of
7466                // (was the OLD row in the view?) x (does the NEW row
7467                // pass the WHERE?). In-place replacement keeps the map
7468                // untouched; a row leaving the view removes + shifts; a
7469                // row entering appends + records.
7470                spg_storage::RowChange::Update { new_row, rowid, .. } => {
7471                    let keep = if let Some(w) = &body.where_ {
7472                        let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
7473                        let r = spg_storage::Row::new(new_row.clone());
7474                        let cond = eval::eval_expr(w, &r, &ctx).map_err(EngineError::Eval)?;
7475                        crate::eval::predicate_is_true(&cond, "WHERE", ctx.mysql_dialect)?
7476                    } else {
7477                        true
7478                    };
7479                    let old_pos = self
7480                        .matview_row_map
7481                        .get(name)
7482                        .and_then(|(_, m)| m.get(&rowid.0).copied());
7483                    match (old_pos, keep) {
7484                        (Some(pos), true) => {
7485                            let mut vals = alloc::vec::Vec::with_capacity(body.items.len());
7486                            {
7487                                let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
7488                                let r = spg_storage::Row::new(new_row.clone());
7489                                for item in &body.items {
7490                                    let SelectItem::Expr { expr, .. } = item else {
7491                                        unreachable!("registration admits Expr items only");
7492                                    };
7493                                    vals.push(
7494                                        eval::eval_expr(expr, &r, &ctx)
7495                                            .map_err(EngineError::Eval)?,
7496                                    );
7497                                }
7498                            }
7499                            let cat = self.active_catalog_mut();
7500                            let table = cat.get_mut(name).ok_or_else(|| {
7501                                EngineError::Storage(spg_storage::StorageError::Corrupt(
7502                                    alloc::format!(
7503                                        "materialized view {name:?} backing table missing"
7504                                    ),
7505                                ))
7506                            })?;
7507                            table.update_row(pos, vals).map_err(EngineError::Storage)?;
7508                            applied += 1;
7509                        }
7510                        (Some(pos), false) => {
7511                            let (_, map) = self
7512                                .matview_row_map
7513                                .get_mut(name)
7514                                .expect("needs_map gated above");
7515                            map.remove(&rowid.0);
7516                            let v = self.writer_version_for_current_stmt();
7517                            let cat = self.active_catalog_mut();
7518                            let table = cat.get_mut(name).ok_or_else(|| {
7519                                EngineError::Storage(spg_storage::StorageError::Corrupt(
7520                                    alloc::format!(
7521                                        "materialized view {name:?} backing table missing"
7522                                    ),
7523                                ))
7524                            })?;
7525                            let _ = table.mark_row_deleted(pos, v);
7526                            applied += 1;
7527                        }
7528                        (None, true) => {
7529                            let mut vals = alloc::vec::Vec::with_capacity(body.items.len());
7530                            {
7531                                let ctx = self.ev_ctx(&base_cols, Some(alias.as_str()));
7532                                let r = spg_storage::Row::new(new_row.clone());
7533                                for item in &body.items {
7534                                    let SelectItem::Expr { expr, .. } = item else {
7535                                        unreachable!("registration admits Expr items only");
7536                                    };
7537                                    vals.push(
7538                                        eval::eval_expr(expr, &r, &ctx)
7539                                            .map_err(EngineError::Eval)?,
7540                                    );
7541                                }
7542                            }
7543                            let cat = self.active_catalog_mut();
7544                            let table = cat.get_mut(name).ok_or_else(|| {
7545                                EngineError::Storage(spg_storage::StorageError::Corrupt(
7546                                    alloc::format!(
7547                                        "materialized view {name:?} backing table missing"
7548                                    ),
7549                                ))
7550                            })?;
7551                            table
7552                                .insert(spg_storage::Row::new(vals))
7553                                .map_err(EngineError::Storage)?;
7554                            let new_pos = table.rows().len() - 1;
7555                            let (expected, map) = self
7556                                .matview_row_map
7557                                .get_mut(name)
7558                                .expect("needs_map gated above");
7559                            map.insert(rowid.0, new_pos);
7560                            *expected += 1;
7561                            applied += 1;
7562                        }
7563                        (None, false) => {}
7564                    }
7565                }
7566            }
7567        }
7568        Ok(Some(applied))
7569    }
7570}
7571
7572/// v7.39 (round 737, S14/B3 knife 2) — the base table of a
7573/// DELTA-MAINTAINABLE view body, or None. Strictly narrower than
7574/// `matview_dep_tables`: ONE stored table, pure projection items, a
7575/// pure WHERE, and none of the shapes whose delta is not row-local
7576/// (aggregates / GROUP BY / DISTINCT [ON] / ORDER / LIMIT / OFFSET /
7577/// windows / SRFs — plus everything the dep collector already bails
7578/// on). Anything outside refreshes fully, as today.
7579fn matview_maintainable_base(stmt: &spg_sql::ast::SelectStatement) -> Option<String> {
7580    use spg_sql::ast::SelectItem;
7581    let deps = matview_dep_tables(stmt)?;
7582    if deps.len() != 1 {
7583        return None;
7584    }
7585    if stmt.distinct
7586        || !stmt.distinct_on.is_empty()
7587        || stmt.group_by.is_some()
7588        || stmt.group_by_all
7589        || stmt.having.is_some()
7590        || !stmt.order_by.is_empty()
7591        || stmt.limit.is_some()
7592        || stmt.offset.is_some()
7593        || !stmt.window_check_exprs.is_empty()
7594        || crate::aggregate::uses_aggregate(stmt)
7595        || crate::window::select_has_window(stmt)
7596    {
7597        return None;
7598    }
7599    for item in &stmt.items {
7600        let SelectItem::Expr { expr, .. } = item else {
7601            return None;
7602        };
7603        if !crate::eval::fully_compilable(expr) || crate::select::expr_contains_builtin_srf(expr) {
7604            return None;
7605        }
7606    }
7607    if let Some(w) = &stmt.where_
7608        && !crate::eval::fully_compilable(w)
7609    {
7610        return None;
7611    }
7612    deps.into_iter().next()
7613}
7614
7615fn matview_dep_tables(
7616    stmt: &spg_sql::ast::SelectStatement,
7617) -> Option<alloc::collections::BTreeSet<String>> {
7618    use spg_sql::ast::SelectItem;
7619    if !stmt.ctes.is_empty() || !stmt.unions.is_empty() {
7620        return None;
7621    }
7622    let from = stmt.from.as_ref()?;
7623    let mut out = alloc::collections::BTreeSet::new();
7624    let mut take = |t: &spg_sql::ast::TableRef| -> bool {
7625        if t.name.is_empty()
7626            || t.lateral_subquery.is_some()
7627            || t.unnest_expr.is_some()
7628            || t.generate_series_args.is_some()
7629            || t.as_of_segment.is_some()
7630            || t.jsonb_each_text_arg.is_some()
7631            || t.table_fn_call.is_some()
7632            || t.rows_from.is_some()
7633            || t.json_table.is_some()
7634        {
7635            return false;
7636        }
7637        out.insert(t.name.to_ascii_lowercase());
7638        true
7639    };
7640    if !take(&from.primary) {
7641        return None;
7642    }
7643    for j in &from.joins {
7644        if !take(&j.table) {
7645            return None;
7646        }
7647        if j.on.as_ref().is_some_and(crate::expr_has_subquery) {
7648            return None;
7649        }
7650    }
7651    let any_sub = stmt.items.iter().any(|i| match i {
7652        SelectItem::Expr { expr, .. } => crate::expr_has_subquery(expr),
7653        _ => false,
7654    }) || stmt.where_.as_ref().is_some_and(crate::expr_has_subquery)
7655        || stmt
7656            .group_by
7657            .as_ref()
7658            .is_some_and(|gs| gs.iter().any(crate::expr_has_subquery))
7659        || stmt.having.as_ref().is_some_and(crate::expr_has_subquery)
7660        || stmt
7661            .order_by
7662            .iter()
7663            .any(|o| crate::expr_has_subquery(&o.expr));
7664    if any_sub {
7665        return None;
7666    }
7667    Some(out)
7668}