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