Skip to main content

spg_engine/
ddl.rs

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