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