Skip to main content

spg_sql/
ast.rs

1//! AST for the PG-dialect subset SPG accepts in v0.2.
2//!
3//! `Display` is implemented so that for any AST `a` produced by [`crate::parser`],
4//! re-parsing `format!("{a}")` yields a structurally equal AST. Binary and
5//! unary operators always emit parentheses to remove any precedence
6//! ambiguity — round-trip safety wins over prettiness.
7
8use alloc::boxed::Box;
9use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12use core::fmt;
13
14#[derive(Debug, Clone, PartialEq)]
15#[allow(clippy::large_enum_variant)] // Statement::Select dominates; Boxing would touch every match site
16pub enum Statement {
17    /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
18    /// [CASCADE | RESTRICT]`. Engine removes the matching tables
19    /// (each one) from the catalog; IF EXISTS makes the drop
20    /// idempotent. CASCADE / RESTRICT trailers parsed silently
21    /// (SPG always cascades index drops on table drop).
22    DropTable {
23        names: Vec<String>,
24        if_exists: bool,
25    },
26    /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
27    /// matching index across whichever table holds it.
28    DropIndex {
29        name: String,
30        if_exists: bool,
31    },
32    /// v7.14.0 — empty / comment-only statement. The lexer strips
33    /// `--` line comments and `/* … */` block comments (including
34    /// the MySQL conditional `/*!NNNNN … */` form) before the
35    /// parser ever sees them; a SQL chunk that contains nothing
36    /// else lands here. Engine returns CommandOk no-op so
37    /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
38    /// wrapped in conditional comments, etc.) load cleanly.
39    Empty,
40    Select(SelectStatement),
41    CreateTable(CreateTableStatement),
42    /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
43    /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
44    /// no-op so PG dumps that include extension declarations
45    /// (notably `pgvector`) load against SPG without splitting
46    /// init scripts. mailrs migration follow-up F3.
47    CreateExtension(String),
48    /// v7.9.27 → v7.16.2 — PG `DO $$ … $$ [LANGUAGE plpgsql];`
49    /// block. The body is now CAPTURED as a [`PlPgSqlBlock`] and
50    /// the engine executes it at top level (mailrs round-10
51    /// A.2). Pre-v7.16.2 the parser discarded the body and the
52    /// engine returned CommandOk — a SEV-1 silent no-op that
53    /// turned mailrs's `DO BEGIN IF EXISTS … THEN ALTER … END
54    /// $$` idempotent migrations into invisible no-ops.
55    DoBlock(PlPgSqlBlock),
56    CreateIndex(CreateIndexStatement),
57    Insert(InsertStatement),
58    /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
59    Update(UpdateStatement),
60    /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
61    Delete(DeleteStatement),
62    /// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ `MERGE` statement.
63    /// `MERGE INTO target [alias] USING source [alias] ON cond
64    /// WHEN MATCHED [AND cond] THEN { UPDATE SET … | DELETE | DO NOTHING }
65    /// WHEN NOT MATCHED [AND cond] THEN { INSERT (cols) VALUES (vals) | DO NOTHING }
66    /// [WHEN …]`. SPG v7.17 supports table-based source (subquery
67    /// source is a follow-up); BY SOURCE / BY TARGET and RETURNING
68    /// are also follow-ups.
69    Merge(MergeStatement),
70    Begin,
71    Commit,
72    Rollback,
73    /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
74    /// stack so a later `ROLLBACK TO <name>` can undo just the work
75    /// since this point.
76    Savepoint(String),
77    /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
78    /// named savepoint and discard later savepoints. Does not end the
79    /// transaction.
80    RollbackToSavepoint(String),
81    /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
82    /// rolling back. Keeps the work done since then.
83    ReleaseSavepoint(String),
84    /// `SHOW TABLES` — return the list of tables in the catalog.
85    ShowTables,
86    /// v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES` /
87    /// `SHOW SCHEMAS`. SPG is single-database; the executor
88    /// returns the canonical MySQL set so the mysql / MariaDB
89    /// client populates its database selector.
90    ShowDatabases,
91    /// v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE TABLE <t>`
92    /// returns a 2-column row `(Table, "Create Table")` carrying
93    /// the synthesized DDL. mysqldump emits this for every
94    /// table at scrape time.
95    ShowCreateTable(String),
96    /// v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES FROM <t>`
97    /// (also `SHOW INDEX`, `SHOW KEYS`).
98    ShowIndexes(String),
99    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS`.
100    ShowStatus,
101    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW VARIABLES`.
102    ShowVariables,
103    /// v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
104    ShowProcesslist,
105    /// `SHOW COLUMNS FROM <table>` — return one row per column with
106    /// its declared name / type / nullability.
107    ShowColumns(String),
108    /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
109    /// Role is optional; defaults to `readonly` when omitted.
110    CreateUser(CreateUserStatement),
111    /// `DROP USER 'name'` (v4.1).
112    DropUser(String),
113    /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
114    ShowUsers,
115    /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
116    /// single-column text table describing the rewritten plan tree
117    /// for `inner`. `analyze` triggers an actual exec to attach
118    /// observed row counts and elapsed micros to each node.
119    Explain(ExplainStatement),
120    /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
121    /// Synchronous rebuild of an NSW index. With the optional
122    /// encoding clause, every stored cell at the indexed column is
123    /// also re-encoded through `coerce_value` before the new graph
124    /// builds.
125    AlterIndex(AlterIndexStatement),
126    /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
127    /// The only setting in v6.7.2 is `hot_tier_bytes`, which
128    /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
129    /// for the named table.
130    AlterTable(AlterTableStatement),
131    /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
132    /// The catalog row lives in `spg_publications`. Publisher-side
133    /// WAL filtering arrives in v6.1.5.
134    CreatePublication(CreatePublicationStatement),
135    /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
136    /// no-op when the publication does not exist.
137    DropPublication(String),
138    /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
139    /// publication ordered by name with `(name, scope_summary,
140    /// table_count)` columns. The scope summary is the human-
141    /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
142    /// TABLES EXCEPT …`; `table_count` is `NULL` for the
143    /// `AllTables` scope and the table-list length otherwise.
144    ShowPublications,
145    /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
146    /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
147    /// in `spg_subscriptions`; when the subscription is
148    /// `enabled = true` (default) the server spawns a
149    /// background worker that connects to `conn` and drains the
150    /// requested publication(s) into the local engine.
151    CreateSubscription(CreateSubscriptionStatement),
152    /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
153    /// PUBLICATION, silent no-op when absent. Stops the
154    /// associated worker thread before removing the row.
155    DropSubscription(String),
156    /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
157    /// subscription ordered by name with `(name, conn_str,
158    /// publications, enabled, last_received_pos)`.
159    ShowSubscriptions,
160    /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
161    /// Blocks until the local server's apply position reaches
162    /// `<pos>` or `<ms>` elapses. Server-layer command: the
163    /// engine refuses it (`EngineError::Unsupported`) since
164    /// `lag_state` lives in `spg-server`'s `ServerState`.
165    WaitForWalPosition {
166        pos: u64,
167        /// `None` → wait forever; `Some(ms)` → return after `ms`
168        /// milliseconds even if the target isn't reached.
169        timeout_ms: Option<u64>,
170    },
171    /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
172    /// table; `ANALYZE <name>` re-stats just one. Populates
173    /// `spg_statistic` with per-column null_frac + n_distinct +
174    /// 100-bucket equi-depth histogram.
175    Analyze(Option<String>),
176    /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
177    /// BTree-cold indices and merges small cold-tier segments
178    /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
179    /// 4 MiB) into a single larger segment per (table, index).
180    /// `WHERE` predicate filtering on which tables to compact is
181    /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
182    /// v6.7.3 only supports the bare form.
183    CompactColdSegments,
184    /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
185    /// parameter on the engine; v7.12.1 honours
186    /// `default_text_search_config` (consumed by `to_tsvector` /
187    /// `plainto_tsquery` family when called without an explicit
188    /// config arg). All other names are accepted as a no-op so PG
189    /// dumps with `SET client_encoding`, `SET search_path` etc.
190    /// load cleanly.
191    SetParameter {
192        name: String,
193        value: SetValue,
194    },
195    /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
196    /// multi-assignment (mysqldump preamble uses
197    /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
198    /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
199    /// source order. Pairs whose LHS is a MySQL session/user
200    /// variable (`@VAR` / `@@VAR`) are recorded with the raw
201    /// name so the engine can ignore them; pairs whose LHS is
202    /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
203    /// go through the regular `set_session_param` path.
204    SetParameterList(Vec<(String, SetValue)>),
205    /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
206    /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
207    /// silently accepted). PG-standard surface for picking an
208    /// isolation level. Engine tracks the value on
209    /// `Engine::current_isolation_level()`; actual MVCC / SSI
210    /// semantics implementation lands separately. PG itself maps
211    /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
212    /// effectively every level reads as READ COMMITTED in v7.37.8.
213    SetTransaction {
214        isolation: IsolationLevel,
215    },
216    /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
217    /// with the parameter's current value as TEXT. Today the only
218    /// recognised param is `transaction_isolation`; further
219    /// surfaces (`search_path`, `application_name`, …) land as the
220    /// session-parameter inventory grows.
221    ShowParameter(String),
222    /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
223    /// to its default. No-op for parameters SPG does not track.
224    ResetParameter(Option<String>),
225    /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
226    /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
227    /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
228    /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
229    /// languages parse but error at exec time with a clear
230    /// unsupported message.
231    CreateFunction(CreateFunctionStatement),
232    /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
233    /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
234    /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
235    /// triggers and column-list / WHEN clauses are out of scope
236    /// for v7.12.4.
237    CreateTrigger(CreateTriggerStatement),
238    /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
239    /// no-op when missing if `IF EXISTS` is set.
240    DropTrigger {
241        name: String,
242        table: String,
243        if_exists: bool,
244    },
245    /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
246    /// DROP TRIGGER but global (no table scope).
247    DropFunction {
248        name: String,
249        if_exists: bool,
250    },
251    /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
252    /// [AS data_type]
253    /// [INCREMENT [BY] n]
254    /// [MINVALUE n | NO MINVALUE]
255    /// [MAXVALUE n | NO MAXVALUE]
256    /// [START [WITH] n]
257    /// [CACHE n]
258    /// [[NO] CYCLE]
259    /// [OWNED BY {table.col | NONE}]`.
260    /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
261    /// emits + nextval/currval/setval downstream all work.
262    CreateSequence(CreateSequenceStatement),
263    /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
264    /// the same option grammar as CREATE SEQUENCE, plus
265    /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
266    AlterSequence(AlterSequenceStatement),
267    /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
268    /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
269    /// silently (no FK on sequences).
270    DropSequence {
271        names: Vec<String>,
272        if_exists: bool,
273    },
274    /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
275    /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
276    /// silent-no-op VIEW story from the v7.17 customer-readiness
277    /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
278    /// so any downstream `SELECT FROM v` errored with table-not-
279    /// found. The view body is stored verbatim; SELECT FROM <v>
280    /// rewrites at exec-time by prepending the view body as a
281    /// synthetic CTE.
282    CreateView(CreateViewStatement),
283    /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
284    /// [CASCADE | RESTRICT]`. Removes the matching view from the
285    /// catalog; CASCADE/RESTRICT parsed silently.
286    DropView {
287        names: Vec<String>,
288        if_exists: bool,
289    },
290    /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
291    /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
292    /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
293    /// model: the materialised result lives as a regular table
294    /// with the matching name + a parallel
295    /// `materialized_views` registry mapping name → body source
296    /// (used by REFRESH).
297    CreateMaterializedView(CreateMaterializedViewStatement),
298    /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
299    /// [NO] DATA]`. Re-runs the stored body and replaces the
300    /// cached rows. `WITH NO DATA` truncates without re-running.
301    RefreshMaterializedView {
302        name: String,
303        with_data: bool,
304    },
305    /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
306    /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
307    /// backing table and the source registry entry.
308    DropMaterializedView {
309        names: Vec<String>,
310        if_exists: bool,
311    },
312    /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
313    /// …)`. Closes the silent-no-op CREATE TYPE story so PG
314    /// dumps that declare enum types load with real constraints
315    /// instead of becoming free-form TEXT. Future kinds
316    /// (composite / range / domain) extend the inner `kind`
317    /// enum.
318    CreateType(CreateTypeStatement),
319    /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
320    /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
321    /// from the catalog.
322    DropType {
323        names: Vec<String>,
324        if_exists: bool,
325    },
326    /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
327    /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
328    /// A DOMAIN is a named CHECK-constrained alias over a built-
329    /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
330    /// every column declared with the domain. Closes the
331    /// silent-no-op CREATE DOMAIN story so PG dumps that ship
332    /// validated identifier types (email, positive_int, …) keep
333    /// their guarantees.
334    CreateDomain(CreateDomainStatement),
335    /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
336    /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
337    /// domain from the catalog.
338    DropDomain {
339        names: Vec<String>,
340        if_exists: bool,
341    },
342    /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
343    /// name [AUTHORIZATION user]`. SPG is single-database;
344    /// schemas are tracked as a namespace registry so pg_dump
345    /// multi-schema declarations land cleanly and `SELECT *
346    /// FROM information_schema.schemata` returns real entries.
347    /// Schema-qualified `schema.table` references still strip
348    /// the prefix at lookup time per PG (schemas are not
349    /// isolation boundaries in v7.17 — see project-next-docket
350    /// for the v7.18+ isolation tracking).
351    CreateSchema {
352        name: String,
353        if_not_exists: bool,
354    },
355    /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
356    /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
357    /// from the registry; built-in `public` / `pg_catalog` /
358    /// `information_schema` cannot be dropped.
359    DropSchema {
360        names: Vec<String>,
361        if_exists: bool,
362    },
363}
364
365/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
366#[derive(Debug, Clone, PartialEq)]
367pub struct CreateDomainStatement {
368    pub name: String,
369    /// Base type for the domain (one of the built-in
370    /// `ColumnTypeName` variants). User-defined enum / domain
371    /// bases are deferred to Phase 1.5b.
372    pub base_type: ColumnTypeName,
373    /// Optional `DEFAULT <expr>`. Resolved at engine-side
374    /// CREATE TABLE time when a column is bound to this domain.
375    pub default: Option<Expr>,
376    /// `NOT NULL` from the domain definition. Engine ORs this
377    /// with the column-level nullability so the strictest of the
378    /// two wins (i.e. the column is non-nullable if either side
379    /// says so).
380    pub not_null: bool,
381    /// Zero-or-more `CHECK (expr)` predicates. Each one is
382    /// enforced as part of the column's CHECK list at INSERT /
383    /// UPDATE time, with `VALUE` substituted for the column's
384    /// current cell value.
385    pub checks: Vec<Expr>,
386}
387
388/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
389#[derive(Debug, Clone, PartialEq, Eq)]
390pub struct CreateTypeStatement {
391    pub name: String,
392    pub kind: TypeKind,
393}
394
395/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
396/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
397/// and later (COMPOSITE, RANGE) can land without an AST shape
398/// migration.
399///
400/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
401/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
402/// stores the field list in the catalog so PG dumps that emit
403/// `CREATE TYPE … AS (…)` don't error out; using a composite type
404/// as a column type lands in Phase 2 (Value::Composite encoding +
405/// ROW() literal + field-access syntax).
406#[derive(Debug, Clone, PartialEq, Eq)]
407pub enum TypeKind {
408    /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
409    /// labels are ordered).
410    Enum { labels: Vec<String> },
411    /// `AS (field_name field_type, …)`. Order matters; PG
412    /// composite literals are positional.
413    Composite {
414        fields: Vec<(String, ColumnTypeName)>,
415    },
416}
417
418/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
419/// a string literal, an identifier (often a config name), an
420/// integer/float, or the bare `DEFAULT` keyword.
421#[derive(Debug, Clone, PartialEq)]
422pub enum SetValue {
423    String(String),
424    Ident(String),
425    Number(String),
426    Default,
427}
428
429/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
430/// at parse time and tracks the selected value on the engine. The
431/// actual semantic differentiation (REPEATABLE READ snapshot,
432/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
433/// today every level reads as effective READ COMMITTED (which is
434/// also how PG treats READ UNCOMMITTED — it silently upgrades to
435/// READ COMMITTED). Default = `ReadCommitted`.
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
437pub enum IsolationLevel {
438    ReadUncommitted,
439    ReadCommitted,
440    RepeatableRead,
441    Serializable,
442}
443
444impl IsolationLevel {
445    /// Canonical PG-style display name, as `SHOW transaction_isolation`
446    /// would return it (`"read committed"`, `"repeatable read"`,
447    /// `"serializable"`). `READ UNCOMMITTED` maps to `"read committed"`
448    /// per the documented PG behaviour.
449    pub fn as_pg_str(self) -> &'static str {
450        match self {
451            Self::ReadUncommitted | Self::ReadCommitted => "read committed",
452            Self::RepeatableRead => "repeatable read",
453            Self::Serializable => "serializable",
454        }
455    }
456}
457
458impl core::fmt::Display for IsolationLevel {
459    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
460        f.write_str(self.as_pg_str())
461    }
462}
463
464impl Default for IsolationLevel {
465    fn default() -> Self {
466        Self::ReadCommitted
467    }
468}
469
470/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
471/// single fixed-shape DDL; the WITH-clause options PG supports
472/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
473/// scope for v6.1.4 — `enabled` defaults to true and there are
474/// no other knobs to set in v6.1.x.
475#[derive(Debug, Clone, PartialEq, Eq)]
476pub struct CreateSubscriptionStatement {
477    pub name: String,
478    /// Connection string in PG keyword=value form (e.g.
479    /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
480    /// `host` and `port` fields; the rest is reserved for
481    /// future v6.1.x options.
482    pub conn_str: String,
483    /// One or more publications on the remote side. Order is
484    /// preserved verbatim from the DDL; the worker requests them
485    /// in this order. v6.1.4 records the list; v6.1.5
486    /// publisher-side filtering enforces it.
487    pub publications: Vec<String>,
488}
489
490/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
491#[derive(Debug, Clone, PartialEq, Eq)]
492pub struct CreateSequenceStatement {
493    pub name: String,
494    pub if_not_exists: bool,
495    pub temporary: bool,
496    /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
497    pub data_type: Option<SequenceDataType>,
498    pub options: SequenceOptions,
499}
500
501/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum SequenceDataType {
504    SmallInt,
505    Int,
506    BigInt,
507}
508
509/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
510/// All fields are optional. `min_value`/`max_value` carry
511/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
512#[derive(Debug, Clone, Default, PartialEq, Eq)]
513pub struct SequenceOptions {
514    pub increment: Option<i64>,
515    pub min_value: Option<SeqBound>,
516    pub max_value: Option<SeqBound>,
517    pub start: Option<i64>,
518    /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
519    /// RESTART, `Some(Some(n))` = RESTART WITH n.
520    pub restart: Option<Option<i64>>,
521    pub cache: Option<i64>,
522    pub cycle: Option<bool>,
523    pub owned_by: Option<SequenceOwnedBy>,
524}
525
526/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum SeqBound {
529    Value(i64),
530    NoBound,
531}
532
533/// v7.17.0 — `OWNED BY {table.col | NONE}`.
534#[derive(Debug, Clone, PartialEq, Eq)]
535pub enum SequenceOwnedBy {
536    None,
537    Column { table: String, column: String },
538}
539
540/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
541#[derive(Debug, Clone, PartialEq)]
542pub struct CreateMaterializedViewStatement {
543    pub name: String,
544    pub if_not_exists: bool,
545    /// Optional `(col, col, …)` rename list. Applies to the
546    /// backing table at CREATE / REFRESH time.
547    pub columns: Vec<String>,
548    /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
549    /// the cached rows.
550    pub body: SelectStatement,
551    /// `WITH DATA` (default) = materialise the rows at CREATE
552    /// time. `WITH NO DATA` = create an empty backing table;
553    /// callers must REFRESH before SELECT returns rows.
554    pub with_data: bool,
555}
556
557/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
558#[derive(Debug, Clone, PartialEq)]
559pub struct CreateViewStatement {
560    pub name: String,
561    pub or_replace: bool,
562    pub if_not_exists: bool,
563    pub temporary: bool,
564    /// Optional `(col, col, …)` rename list. When non-empty,
565    /// these override the body's projected column names per-
566    /// position at SELECT-from-view time.
567    pub columns: Vec<String>,
568    /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
569    /// time to materialise the view as a synthetic CTE.
570    pub body: SelectStatement,
571}
572
573/// v7.17.0 — `ALTER SEQUENCE` AST node.
574#[derive(Debug, Clone, PartialEq, Eq)]
575pub struct AlterSequenceStatement {
576    pub name: String,
577    pub if_exists: bool,
578    pub options: SequenceOptions,
579}
580
581/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
582/// the [`PublicationScope`] shape. v6.1.2 only accepted
583/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
584/// variants by flipping the parser gate (no AST migration).
585#[derive(Debug, Clone, PartialEq, Eq)]
586pub struct CreatePublicationStatement {
587    pub name: String,
588    pub scope: PublicationScope,
589}
590
591/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
592/// flips the parser gate for the `ForTables` / `AllTablesExcept`
593/// variants — the on-disk shape, snapshot serialisation, and the
594/// AST round-trip Display path were already in place in v6.1.2
595/// so this is a parser-only widening.
596#[derive(Debug, Clone, PartialEq, Eq)]
597pub enum PublicationScope {
598    AllTables,
599    ForTables(Vec<String>),
600    AllTablesExcept(Vec<String>),
601}
602
603#[derive(Debug, Clone, PartialEq, Eq)]
604pub struct AlterIndexStatement {
605    pub name: String,
606    pub target: AlterIndexTarget,
607}
608
609#[derive(Debug, Clone, PartialEq, Eq)]
610pub enum AlterIndexTarget {
611    /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
612    /// rebuilds the existing graph in place without touching the
613    /// column encoding; `Some(enc)` re-encodes every cell first.
614    Rebuild { encoding: Option<VecEncoding> },
615    /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
616    /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
617    /// uses it to make the migration idempotent (re-running on a
618    /// DB where the rename already happened is a no-op rather
619    /// than an error).
620    Rename { new: String, if_exists: bool },
621}
622
623/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
624/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
625/// can add more SET subjects without changing the dispatch shape.
626#[derive(Debug, Clone, PartialEq)]
627pub struct AlterTableStatement {
628    pub name: String,
629    /// v7.13.2 — mailrs round-6 S1. One or more subactions
630    /// separated by commas in the source SQL. PG-semantic apply
631    /// is sequential; engine bails on first error (no
632    /// transactional rollback of completed subactions in v7.13).
633    /// Single-subaction shape stays a 1-element vec.
634    pub targets: Vec<AlterTableTarget>,
635}
636
637#[derive(Debug, Clone, PartialEq)]
638#[allow(clippy::large_enum_variant)]
639pub enum AlterTableTarget {
640    /// Per-table hot-tier byte budget override. The freezer
641    /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
642    SetHotTierBytes(u64),
643    /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
644    /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
645    /// Engine validates existing rows against the new constraint
646    /// before installing it.
647    AddForeignKey(ForeignKeyConstraint),
648    /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
649    /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
650    /// no-op when no FK with that name exists; otherwise raises.
651    DropForeignKey { name: String, if_exists: bool },
652    /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
653    /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
654    /// (20 migrate-*.sql hits). Engine appends the column to the
655    /// schema and back-fills every existing row with the DEFAULT
656    /// (or NULL when no DEFAULT and the column is nullable).
657    AddColumn {
658        column: ColumnDef,
659        if_not_exists: bool,
660    },
661    /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
662    /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
663    /// existing row's column value by evaluating the optional
664    /// USING expression (default `col::<ty>`) and re-coercing
665    /// against the new column type.
666    AlterColumnType {
667        column: String,
668        new_type: ColumnTypeName,
669        using: Option<Expr>,
670    },
671    /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
672    /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
673    /// every row's value at that position is removed; any index
674    /// on the column is dropped. `if_exists` makes the drop a
675    /// no-op when the column is missing. `cascade` removes
676    /// dependents (FKs referencing the column, partial indexes
677    /// whose predicate names the column); without it, the engine
678    /// rejects when dependents exist.
679    DropColumn {
680        column: String,
681        if_exists: bool,
682        cascade: bool,
683    },
684    /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
685    /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
686    /// CONSTRAINT name CHECK (expr)` — table-level constraints
687    /// installed post-CREATE-TABLE. pg_dump emits PKs as a
688    /// separate ALTER TABLE statement, so this surface lets the
689    /// dump load straight through.
690    AddTableConstraint(TableConstraint),
691    /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
692    /// Renames the column in the schema and propagates the rename
693    /// to every stored source string that references it as a
694    /// (potentially-qualified) column identifier: CHECK predicates,
695    /// partial-index predicates, runtime DEFAULT expressions, and
696    /// triggers' `UPDATE OF` column lists. Function bodies and
697    /// trigger bodies are NOT auto-rewritten — they're loose
698    /// source text and may contain references SPG can't statically
699    /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
700    /// the column even if dependents exist; users renaming a
701    /// column referenced by a function body update the function
702    /// body separately.
703    RenameColumn { old: String, new: String },
704    /// v7.22 (round-13 T2) — mark a column auto-incrementing.
705    /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
706    /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
707    /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
708    /// (identity); both lower to this. SPG's auto-increment is
709    /// max+1-scan based, so the dump's `setval(…)` calls stay
710    /// no-ops without losing the sequence position.
711    SetColumnAutoIncrement {
712        column: String,
713        /// The implicit sequence pg_dump names for an identity
714        /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
715        /// nextval target for a serial default. The engine creates
716        /// it if absent so the dump's later `setval(s, …)` lands.
717        seq_name: Option<String>,
718    },
719    /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
720    /// table itself (mailrs round-10 A.5 carve-out — mailrs's
721    /// migrate-042 uses it). The engine moves the table entry
722    /// in the catalog under the new name; child catalog state
723    /// (FKs pointing at this table, triggers watching this
724    /// table) tracks the rename through the storage layer.
725    RenameTable { new: String },
726    /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
727    /// { ALL | <name> }`. Toggles whether row-level triggers
728    /// fire on subsequent INSERT/UPDATE/DELETE on the table.
729    /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
730    /// ENABLE epilogue around every table's data block so the
731    /// rows already-computed in prod don't get re-rewritten
732    /// (and so trigger-driven side effects like
733    /// audit/queueing don't re-fire during a bulk reload).
734    /// `which == TriggerSelector::All` toggles every trigger
735    /// on the table; `Named(name)` toggles one trigger. The
736    /// engine persists the disabled state on `TriggerDef.enabled`
737    /// (catalog FILE_VERSION 25+) and the row-write paths skip
738    /// the trigger when `!enabled`.
739    SetTriggerEnabled {
740        which: TriggerSelector,
741        enabled: bool,
742    },
743}
744
745/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
746/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
747/// modifiers; v7.16.1 ships the two shapes pg_dump actually
748/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
749/// shouldn't surface from a dump.
750#[derive(Debug, Clone, PartialEq, Eq)]
751pub enum TriggerSelector {
752    /// Every trigger on the table.
753    All,
754    /// A specific trigger by name.
755    Named(String),
756}
757
758#[derive(Debug, Clone, PartialEq)]
759pub struct ExplainStatement {
760    pub analyze: bool,
761    pub inner: Box<SelectStatement>,
762    /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
763    /// advisor pass: after the regular plan tree, the engine
764    /// emits one suggestion line per column referenced in the
765    /// query's WHERE / JOIN that has no covering index on the
766    /// owning table.
767    pub suggest: bool,
768    /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
769    /// `elapsed=…us` annotations from the Total line (and any
770    /// future cost-bearing lines). PG-standard option used by
771    /// regression suites and diff-friendly EXPLAIN output. When
772    /// `true`, takes precedence over the per-session
773    /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
774    pub costs_off: bool,
775}
776
777#[derive(Debug, Clone, PartialEq, Eq)]
778pub struct CreateUserStatement {
779    pub name: String,
780    pub password: String,
781    /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
782    /// the parser; the engine validates against `Role::parse` so a
783    /// typo lands as a runtime error with a clear message rather than
784    /// a parse failure.
785    pub role: String,
786}
787
788/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
789/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
790/// (the row-level trigger body the CREATE TRIGGER below references).
791/// Non-trigger user-defined functions parse but error at execution
792/// time with a clear unsupported message; that surface lands in
793/// v7.12.5+.
794#[derive(Debug, Clone, PartialEq)]
795pub struct CreateFunctionStatement {
796    pub name: String,
797    /// `OR REPLACE` was present; an existing function with the
798    /// same name is overwritten instead of erroring.
799    pub or_replace: bool,
800    /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
801    /// list `()` (sufficient for trigger functions). Other shapes
802    /// parse and store the args but the executor refuses to call
803    /// them.
804    pub args: Vec<FunctionArg>,
805    /// `RETURNS <type>` — `trigger` is the supported shape for
806    /// v7.12.4; arbitrary return types parse to
807    /// [`FunctionReturn::Other`].
808    pub returns: FunctionReturn,
809    /// `LANGUAGE <lang>` clause. PG accepts the clause on either
810    /// side of `AS $$...$$`; the parser canonicalises to one slot.
811    /// `plpgsql` and `sql` are the two interesting values.
812    pub language: String,
813    /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
814    /// a structured AST; non-trigger / non-plpgsql bodies stay as
815    /// the raw source text so the v7.12.5+ executor can pick them
816    /// up without a parser rev.
817    pub body: FunctionBody,
818}
819
820/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
821#[derive(Debug, Clone, PartialEq)]
822pub struct FunctionArg {
823    /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
824    /// (the default); `OUT` / `INOUT` parse but the executor
825    /// refuses them.
826    pub mode: FunctionArgMode,
827    /// Optional arg name. Trigger functions traditionally don't
828    /// name their args (they read NEW/OLD instead), so `None` is
829    /// the common case.
830    pub name: Option<String>,
831    /// Declared type, normalised to the SPG `DataType` mapping
832    /// where one exists. Unknown / extension types parse as a
833    /// raw string under [`FunctionArgType::Raw`].
834    pub ty: FunctionArgType,
835}
836
837#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838pub enum FunctionArgMode {
839    In,
840    Out,
841    InOut,
842}
843
844#[derive(Debug, Clone, PartialEq)]
845pub enum FunctionArgType {
846    Typed(ColumnTypeName),
847    /// Unknown / extension types — kept as the parser-side raw
848    /// identifier so error messages can name them precisely.
849    Raw(String),
850}
851
852#[derive(Debug, Clone, PartialEq)]
853pub enum FunctionReturn {
854    /// `RETURNS TRIGGER` — the row-level trigger function shape.
855    /// v7.12.4 ships exactly this for execution.
856    Trigger,
857    /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
858    /// the function is unused (since v7.12.4 doesn't ship scalar
859    /// function invocation).
860    Void,
861    /// `RETURNS <type>` for any concrete data type. Reserved for
862    /// v7.12.5+'s scalar UDF surface.
863    Type(ColumnTypeName),
864    /// `RETURNS <ident>` for types SPG doesn't know — extension
865    /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
866    Other(String),
867}
868
869#[derive(Debug, Clone, PartialEq)]
870pub enum FunctionBody {
871    /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
872    /// trigger-function executor walks this directly without
873    /// re-parsing.
874    PlPgSql(PlPgSqlBlock),
875    /// Raw source text — parser couldn't (or didn't try to)
876    /// structure-parse the body. Used for `LANGUAGE sql`
877    /// functions and any PL/pgSQL body that contains v7.12.5+
878    /// features the v7.12.4 parser doesn't yet recognise. The
879    /// executor returns an unsupported error when invoked.
880    Raw(String),
881}
882
883/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
884/// from assignment + return to a real-PL/pgSQL surface:
885/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
886/// control flow, `RAISE` diagnostics, and embedded SQL
887/// statements that execute through the regular engine path.
888/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
889/// which mailrs's trigger doesn't need but other PG customers
890/// may; deferred to a future minor release.
891#[derive(Debug, Clone, PartialEq)]
892pub struct PlPgSqlBlock {
893    /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
894    /// preceding `BEGIN`. Empty when the body opens directly with
895    /// `BEGIN`. Declarations execute in order; each may reference
896    /// earlier-declared locals in its init expression.
897    pub declarations: Vec<PlPgSqlDeclare>,
898    pub statements: Vec<PlPgSqlStmt>,
899}
900
901/// v7.12.6 — single `DECLARE` entry: variable name + declared
902/// type + optional initialiser. Variables default to SQL NULL
903/// when no init is given (matches PG).
904#[derive(Debug, Clone, PartialEq)]
905pub struct PlPgSqlDeclare {
906    pub name: String,
907    /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
908    /// knows it; raw text otherwise).
909    pub ty: FunctionArgType,
910    pub default: Option<Expr>,
911}
912
913#[derive(Debug, Clone, PartialEq)]
914pub enum PlPgSqlStmt {
915    /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
916    /// for clarity in error reporting (PG also forbids it) — the
917    /// executor errors with a clear "OLD is read-only" message.
918    Assign { target: AssignTarget, value: Expr },
919    /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
920    /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
921    /// the SELECT statement with the INTO clause stripped; the
922    /// engine runs it via `Engine::execute`, takes the first
923    /// row's first column, and assigns to the local variable
924    /// in the DECLARE scope. Single-column / single-row
925    /// queries only at v7.16.2; multi-target (`INTO a, b`) is
926    /// a v7.16.x follow-up.
927    SelectInto {
928        var: String,
929        body: Box<SelectStatement>,
930    },
931    /// `RETURN <target>;` — trigger functions canonically return
932    /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
933    /// expression for forward compatibility with scalar UDFs.
934    Return(ReturnTarget),
935    /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
936    /// [ELSE body] END IF;`. Branches are tried in order; first
937    /// truthy condition wins; the optional ELSE runs when no
938    /// condition matched.
939    If {
940        branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
941        else_branch: Vec<PlPgSqlStmt>,
942    },
943    /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
944    /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
945    /// (logging — observable side effect only) or `EXCEPTION`
946    /// (aborts the trigger and propagates as an error). v7.12.6
947    /// supports the basic format-string substitution PG uses
948    /// (`%` placeholders consumed positionally).
949    Raise {
950        level: RaiseLevel,
951        message: String,
952        args: Vec<Expr>,
953    },
954    /// v7.12.6 — embedded SQL statement inside the trigger body
955    /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
956    /// NEW.col / OLD.col references inside the embedded
957    /// statement's expression tree are substituted with the
958    /// current trigger context before the engine re-executes the
959    /// statement. Recursion depth into nested triggers is
960    /// bounded by the engine's existing trigger-fire guard.
961    EmbeddedSql(Box<Statement>),
962}
963
964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
965pub enum RaiseLevel {
966    /// `RAISE NOTICE` — diagnostic message, observable in the
967    /// server log. Does not affect the trigger's outcome.
968    Notice,
969    /// `RAISE WARNING` — like NOTICE, slightly louder severity.
970    Warning,
971    /// `RAISE INFO` — like NOTICE, slightly quieter.
972    Info,
973    /// `RAISE LOG` — like NOTICE, lower priority.
974    Log,
975    /// `RAISE DEBUG` — like NOTICE, lowest priority.
976    Debug,
977    /// `RAISE EXCEPTION` — aborts the trigger function with the
978    /// given message, propagating up to the caller as a query-
979    /// level error.
980    Exception,
981}
982
983#[derive(Debug, Clone, PartialEq)]
984pub enum AssignTarget {
985    NewColumn(String),
986    OldColumn(String),
987    /// Reserved for v7.12.5 DECLARE'd local variables.
988    Local(String),
989}
990
991#[derive(Debug, Clone, PartialEq)]
992pub enum ReturnTarget {
993    /// `RETURN NEW;` — for BEFORE triggers, this is the row that
994    /// actually gets written (possibly with NEW.col mutations
995    /// applied). For AFTER triggers, the return value is ignored.
996    New,
997    /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
998    /// the delete proceed; for BEFORE UPDATE / INSERT it's
999    /// equivalent to dropping the write.
1000    Old,
1001    /// `RETURN NULL;` — for BEFORE triggers, skips the write
1002    /// entirely. For AFTER, the return value is ignored.
1003    Null,
1004    /// `RETURN <expr>;` — non-row return shape; reserved for the
1005    /// scalar UDF surface in v7.12.5+. Executor errors when used
1006    /// inside a trigger function.
1007    Expr(Expr),
1008}
1009
1010/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
1011/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
1012/// but the executor refuses them. `WHEN (cond)` clauses are out
1013/// of scope; the trigger function can short-circuit on a leading
1014/// IF inside its body once v7.12.5 lands IF.
1015#[derive(Debug, Clone, PartialEq)]
1016pub struct CreateTriggerStatement {
1017    pub name: String,
1018    pub or_replace: bool,
1019    pub timing: TriggerTiming,
1020    /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
1021    /// three entries in order.
1022    pub events: Vec<TriggerEvent>,
1023    pub table: String,
1024    /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
1025    /// only `Row`; `Statement` parses but the executor refuses.
1026    pub for_each: TriggerForEach,
1027    /// Name of the function to invoke. v7.12.4 requires the
1028    /// function to be `CREATE FUNCTION`'d earlier; forward
1029    /// references (PG accepts) are deferred to v7.12.5.
1030    pub function: String,
1031    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
1032    /// (mailrs round-5 G7). Non-empty only when the events list
1033    /// contains UPDATE and the user wrote the column-list filter.
1034    /// PG fires the trigger only when at least one of these
1035    /// columns appears in the SET clause; SPG conservatively
1036    /// fires on any UPDATE matching the listed columns or
1037    /// rewriting them at the row level. Empty vec = no filter
1038    /// (fire on every UPDATE).
1039    pub update_columns: Vec<String>,
1040}
1041
1042#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1043pub enum TriggerTiming {
1044    /// Fires before the row is written; the trigger function's
1045    /// return value (NEW or NULL) decides the row content and
1046    /// whether the write proceeds at all.
1047    Before,
1048    /// Fires after the row is written; the return value is
1049    /// ignored.
1050    After,
1051    /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
1052    /// v7.12.4 (SPG has no updatable-view surface).
1053    InsteadOf,
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1057pub enum TriggerEvent {
1058    Insert,
1059    Update,
1060    Delete,
1061    /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
1062    /// so the trigger never fires.
1063    Truncate,
1064}
1065
1066#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1067pub enum TriggerForEach {
1068    Row,
1069    Statement,
1070}
1071
1072#[derive(Debug, Clone, PartialEq)]
1073pub struct CreateIndexStatement {
1074    pub name: String,
1075    pub table: String,
1076    pub column: String,
1077    /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
1078    /// graph for vector kNN); unspecified is the default B-tree index.
1079    pub method: IndexMethod,
1080    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
1081    /// index name already exists, instead of raising `DuplicateIndex`.
1082    pub if_not_exists: bool,
1083    /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
1084    /// non-key columns the planner should treat as "covered" by
1085    /// this index when checking whether a query can run as an
1086    /// index-only scan. Empty when no `INCLUDE` clause was given.
1087    pub included_columns: Vec<String>,
1088    /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
1089    /// for which `<expr>` evaluates truthy enter the index;
1090    /// queries whose `WHERE` clause's canonical Display form
1091    /// matches this expression's Display form can be served by the
1092    /// partial index. Stored as a parsed `Expr` so the engine
1093    /// re-uses the existing evaluation path; storage persists the
1094    /// Display form on the catalog snapshot.
1095    pub partial_predicate: Option<Expr>,
1096    /// v6.8.2 — expression-based index. When `Some(expr)`, the
1097    /// index key is the result of `expr` evaluated on each row
1098    /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
1099    /// field still names the *primary* column the expression
1100    /// touches so existing planner shortcuts that resolve a
1101    /// column position stay valid. `None` = plain
1102    /// column-reference index (the legacy shape).
1103    pub expression: Option<Expr>,
1104    /// v7.9.14 — extra column names after the leading column in a
1105    /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
1106    /// planner today still only uses the leading column for index
1107    /// seeks; the extras are tracked verbatim so the same DDL
1108    /// round-trips through WAL replay + catalog snapshot, and so
1109    /// the engine can emit a clear warning at INDEX CREATE time
1110    /// that only the leading column is currently honoured.
1111    /// Composite BTree index keys land in v7.10.
1112    pub extra_columns: Vec<String>,
1113    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
1114    /// enforces uniqueness on the indexed key (combined with the
1115    /// `partial_predicate` filter — only rows where the predicate
1116    /// evaluates truthy enter the uniqueness check). Standard SQL
1117    /// and PG's canonical way to express conditional uniqueness.
1118    /// mailrs K1.
1119    pub is_unique: bool,
1120    /// v7.15.0 — operator class on the leading column, when the
1121    /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
1122    /// Lower-cased. Most opclasses are still informational; the
1123    /// engine routes on `gin_trgm_ops` specifically to build a
1124    /// trigram-shingle GIN over a TEXT column, and otherwise
1125    /// keeps the current "accepted and discarded" behaviour for
1126    /// pg_dump compatibility.
1127    pub opclass: Option<String>,
1128}
1129
1130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1131pub enum IndexMethod {
1132    /// Default — B-tree over `IndexKey`. Used for equality / range
1133    /// lookups on scalar columns.
1134    BTree,
1135    /// `USING hnsw` — NSW graph for kNN over a vector column.
1136    Hnsw,
1137    /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
1138    /// metadata that records (min_key, max_key) for each page in a
1139    /// cold-tier segment, on the indexed column. The optimizer
1140    /// can use these summaries to skip pages whose range does NOT
1141    /// overlap a query's WHERE predicate. BRIN indexes carry no
1142    /// in-memory data — the summaries live in the segment v2
1143    /// envelope's sidecar. Created via the standard
1144    /// `CREATE INDEX … USING brin (col)` syntax.
1145    Brin,
1146    /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
1147    /// column. Posting lists map `lexeme word` → row locators; the
1148    /// planner uses them to narrow `WHERE col @@ tsquery` to the
1149    /// candidate rows whose vectors contain a matching term, then
1150    /// re-evaluates the full `@@` semantics on each candidate.
1151    /// Replaces the v7.9.26b `USING gin` → BTree fallback that
1152    /// silently degraded to a full scan at query time.
1153    Gin,
1154}
1155
1156#[derive(Debug, Clone, PartialEq)]
1157pub struct CreateTableStatement {
1158    pub name: String,
1159    pub columns: Vec<ColumnDef>,
1160    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
1161    /// table name already exists, instead of raising `DuplicateTable`.
1162    pub if_not_exists: bool,
1163    /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
1164    /// constraints. Column-level `REFERENCES` (single-column inline
1165    /// form) is normalised into this vec at parse time so the engine
1166    /// sees one uniform list.
1167    pub foreign_keys: Vec<ForeignKeyConstraint>,
1168    /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
1169    /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
1170    /// Engine resolves each into a BTree index named after the
1171    /// constraint's leading column at CREATE TABLE time; INSERT
1172    /// path enforces composite uniqueness via row scan on the
1173    /// leading column index.
1174    pub table_constraints: Vec<TableConstraint>,
1175    /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
1176    /// (key_col)` declarative partition-parent suffix. `Some` ⇒
1177    /// the engine creates a parent table whose own rows stay
1178    /// empty and routes INSERT/SELECT through children. Mutually
1179    /// exclusive with `partition_of` (parser enforces).
1180    pub partition_by: Option<PartitionBySpec>,
1181    /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
1182    /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
1183    /// the table inherits its column list from `parent` (the
1184    /// parser rejects an explicit column list when this is set);
1185    /// engine routes child rows back to the parent at INSERT.
1186    pub partition_of: Option<PartitionOfSpec>,
1187}
1188
1189/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
1190/// v7.37.6-B only RANGE is recognised; the enum keeps space for
1191/// future LIST / HASH without breaking the public AST shape.
1192#[derive(Debug, Clone, PartialEq)]
1193pub struct PartitionBySpec {
1194    pub kind: PartitionKindAst,
1195    /// One or more ident references into the parent's column list.
1196    /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
1197    /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
1198    /// shape PG-compatible.
1199    pub key_columns: Vec<String>,
1200}
1201
1202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1203pub enum PartitionKindAst {
1204    Range,
1205}
1206
1207/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
1208/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
1209/// or the catch-all `DEFAULT` partition.
1210#[derive(Debug, Clone, PartialEq)]
1211pub struct PartitionOfSpec {
1212    pub parent_name: String,
1213    pub bounds: PartitionOfBoundsAst,
1214}
1215
1216#[derive(Debug, Clone, PartialEq)]
1217pub enum PartitionOfBoundsAst {
1218    /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
1219    /// (lits include vector bodies), so we box both bounds to keep
1220    /// the variant size in line with `Default` for clippy and to
1221    /// minimise per-statement footprint when the partition shape
1222    /// isn't in use.
1223    Range {
1224        lower: Box<Expr>,
1225        upper: Box<Expr>,
1226    },
1227    Default,
1228}
1229
1230/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
1231/// column list. Either a composite PRIMARY KEY or a UNIQUE
1232/// (single- or multi-column).
1233#[derive(Debug, Clone, PartialEq)]
1234pub enum TableConstraint {
1235    /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
1236    /// referenced column. Engine builds a BTree index named
1237    /// `<table>_pkey` and enforces composite uniqueness on INSERT.
1238    PrimaryKey {
1239        name: Option<String>,
1240        columns: Vec<String>,
1241    },
1242    /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
1243    /// named `<table>_<leading_col>_key` (single-column) or
1244    /// `<table>_<leading_col>_<…>_key` (composite) and enforces
1245    /// uniqueness on INSERT.
1246    Unique {
1247        name: Option<String>,
1248        columns: Vec<String>,
1249        /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
1250        /// G10). PG 15+ flips the NULL handling so any number of
1251        /// NULL rows collide on the constraint. Default is
1252        /// `false` (NULLS DISTINCT, standard SQL behaviour).
1253        nulls_not_distinct: bool,
1254    },
1255    /// v7.13.0 — `CHECK (<expr>)` table-level constraint
1256    /// (mailrs round-5 G3). Column-level inline CHECKs fold into
1257    /// this same variant at parse time. Engine evaluates the
1258    /// predicate against each INSERT/UPDATE candidate row; a
1259    /// false / NULL result rejects the mutation.
1260    Check { name: Option<String>, expr: Expr },
1261    /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
1262    /// non-unique secondary-index declaration inline in CREATE
1263    /// TABLE. Engine builds a BTree index on the leading column
1264    /// (composite columns parse but only the leading column is
1265    /// honoured at v7.15 — matches the existing
1266    /// `CreateIndexStatement::extra_columns` semantics). Useful
1267    /// for `mysql/blog`-style schemas that lean on routine
1268    /// secondary indexes for ORM lookups.
1269    Index {
1270        name: Option<String>,
1271        columns: Vec<String>,
1272    },
1273    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
1274    /// (cols)` inline declaration. Pre-v7.17 the parser
1275    /// silently dropped these so MyISAM-imported FULLTEXT
1276    /// indexes vanished; v7.17 routes them through the
1277    /// existing tsvector-GIN engine path so MATCH AGAINST
1278    /// queries get a real inverted index instead of falling
1279    /// back to a full scan. Multi-column FULLTEXT KEYs build
1280    /// one GIN per column at v7.17 (per-column posting lists);
1281    /// the leading column drives query planning.
1282    FulltextIndex {
1283        name: Option<String>,
1284        columns: Vec<String>,
1285    },
1286}
1287
1288#[derive(Debug, Clone, PartialEq)]
1289#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
1290pub struct ColumnDef {
1291    pub name: String,
1292    pub ty: ColumnTypeName,
1293    pub nullable: bool,
1294    /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
1295    /// evaluates this once (with an empty row) and caches the resulting
1296    /// `Value` on the column schema.
1297    pub default: Option<Expr>,
1298    /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
1299    /// per such column and fills the slot when INSERT leaves it
1300    /// unbound (omitted from a column-list INSERT or explicitly NULL).
1301    pub auto_increment: bool,
1302    /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
1303    /// migration follow-up F1. Implies `NOT NULL`. Engine creates
1304    /// an implicit BTree index named `<table>_pkey` over this
1305    /// column at CREATE TABLE time, satisfying the parent-side
1306    /// index requirement for any FOREIGN KEY pointing at it.
1307    pub is_primary_key: bool,
1308    /// v7.13.0 — inline `UNIQUE` column constraint
1309    /// (mailrs round-5 G2). The CREATE TABLE handler folds this
1310    /// into a single-column `TableConstraint::Unique` so the
1311    /// engine path stays uniform with table-level UNIQUE.
1312    pub is_unique: bool,
1313    /// v7.13.0 — inline `CHECK (<expr>)` column constraint
1314    /// (mailrs round-5 G3). Stored alongside the column so the
1315    /// CREATE TABLE handler can fold these into table-level
1316    /// CHECK constraints. Multiple inline CHECKs on the same
1317    /// column are concatenated with AND at the table level.
1318    pub check: Option<Expr>,
1319    /// v7.17.0 Phase 1.4 — user-defined type reference. When the
1320    /// parser sees an unknown column-type ident (anything not in
1321    /// the built-in `parse_column_type_name` table), it sets
1322    /// `ty = ColumnTypeName::Text` and records the original name
1323    /// here. The engine resolves at CREATE TABLE time: if a
1324    /// catalog enum/domain with this name exists, the column is
1325    /// bound to it (label-checked on INSERT for enums; CHECK-
1326    /// constrained for domains); otherwise the CREATE TABLE
1327    /// errors with "unknown type".
1328    pub user_type_ref: Option<String>,
1329    /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
1330    /// CURRENT_TIMESTAMP` column attribute. When set, an
1331    /// UPDATE that does NOT explicitly bind this column
1332    /// overrides the new value with `now()` (engine clock).
1333    /// Pre-v7.17 SPG silently accepted the syntax and never
1334    /// fired the override — `updated_at` columns from mysqldump
1335    /// stayed pinned at their initial DEFAULT forever, an
1336    /// audit Tier-S silent-failure. Generalised as a stored
1337    /// expression source so future shapes (`ON UPDATE
1338    /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
1339    /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
1340    pub on_update_runtime: Option<Expr>,
1341    /// v7.17.0 Phase 2.5 — text collation derived from the
1342    /// post-fix `COLLATE <name>` clause (and / or the table-level
1343    /// `COLLATE=<name>` for MySQL dumps that don't repeat it
1344    /// per column). Pre-2.5 SPG accepted the clause and
1345    /// discarded the name, leaving every column byte-compared
1346    /// — a Tier-S silent failure when the customer expected
1347    /// `_ci` / `case_insensitive` semantics. Parser normalises
1348    /// the raw collation name into the variants in `Collation`.
1349    /// Default `Binary` preserves the legacy compare path.
1350    pub collation: Collation,
1351    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
1352    /// 4.4 SPG accepted and discarded the keyword, leaving
1353    /// negative values silently accepted on a column the
1354    /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
1355    /// rejects negative INSERT / UPDATE values on UNSIGNED int
1356    /// columns. SPG widening to `u64`-shaped storage is out of
1357    /// v7.17 scope; the upper bound remains the signed-type max
1358    /// (i64::MAX for BIGINT UNSIGNED), which still strictly
1359    /// exceeds what every mailrs / Rails app actually uses.
1360    pub is_unsigned: bool,
1361    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
1362    /// value list captured at parse time. When `Some`, the parser
1363    /// recognised `ENUM(...)` in the type slot; the engine
1364    /// validates INSERT cells against this list at
1365    /// column_def_to_schema time and persists the variants on
1366    /// `ColumnSchema.inline_enum_variants`. None for all
1367    /// non-ENUM columns.
1368    pub inline_enum_variants: Option<Vec<String>>,
1369    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
1370    /// value list. Distinct from ENUM (subset semantics rather
1371    /// than pick-one). None for all non-SET columns.
1372    pub inline_set_variants: Option<Vec<String>>,
1373    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
1374    /// STORED` computed-column source. When `Some`, the engine
1375    /// stores the Display-form of the parsed expression on
1376    /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
1377    /// and re-evaluates the expression against every INSERT /
1378    /// UPDATE candidate row, overwriting whatever the caller
1379    /// supplied for this column. Boxed to keep `ColumnDef` from
1380    /// blowing past the `large_enum_variant` clippy ceiling
1381    /// (`Expr` widens with vector literals).
1382    pub generated_stored_expr: Option<Box<Expr>>,
1383}
1384
1385/// v7.17.0 Phase 2.5 — text collation classification surfaced
1386/// from the SQL parser. Mirrors `spg_storage::Collation`; the
1387/// engine bridges between the two at CREATE TABLE time.
1388///
1389/// Recognised collation-name patterns (case-insensitive):
1390///   * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase`         → CaseInsensitive
1391///   * Everything else (`C`, `POSIX`, `default`,
1392///     `pg_catalog.default`, `*_cs`, `*_bin`, unknown names)   → Binary
1393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1394pub enum Collation {
1395    Binary,
1396    CaseInsensitive,
1397}
1398
1399#[allow(clippy::derivable_impls)]
1400impl Default for Collation {
1401    fn default() -> Self {
1402        Self::Binary
1403    }
1404}
1405
1406impl Collation {
1407    /// Classify a `COLLATE <name>` ident into one of the supported
1408    /// variants. Empty / unknown names fall back to `Binary` —
1409    /// matches the pre-2.5 silent-accept behaviour for snapshots
1410    /// that load through but don't actually depend on the
1411    /// collation semantics.
1412    #[must_use]
1413    pub fn from_collation_name(name: &str) -> Self {
1414        let lc = name.trim().to_ascii_lowercase();
1415        // Strip any quotes / schema-qualifier the parser left on
1416        // (e.g. `pg_catalog.default`).
1417        let bare = lc
1418            .trim_matches(|c: char| c == '"' || c == '\'')
1419            .rsplit('.')
1420            .next()
1421            .unwrap_or("");
1422        if bare.is_empty() {
1423            return Self::Binary;
1424        }
1425        if bare == "case_insensitive" || bare == "nocase" {
1426            return Self::CaseInsensitive;
1427        }
1428        // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
1429        // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
1430        if bare.ends_with("_ci") {
1431            return Self::CaseInsensitive;
1432        }
1433        Self::Binary
1434    }
1435}
1436
1437/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
1438/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
1439/// parse into this shape — the column-level form has a single-entry
1440/// `columns` / `parent_columns`.
1441#[derive(Debug, Clone, PartialEq)]
1442pub struct ForeignKeyConstraint {
1443    /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
1444    /// today but parses + stores it so a future ALTER TABLE DROP
1445    /// CONSTRAINT can target by name (v7.6.8).
1446    pub name: Option<String>,
1447    /// Local columns participating in the FK (≥ 1).
1448    pub columns: Vec<String>,
1449    /// Referenced parent table.
1450    pub parent_table: String,
1451    /// Referenced parent columns. Must have the same arity as
1452    /// `columns`; engine validates parent has a PK / UNIQUE index
1453    /// on exactly this column set (v7.6.1).
1454    pub parent_columns: Vec<String>,
1455    /// `ON DELETE` action. Defaults to `Restrict` if absent.
1456    pub on_delete: FkAction,
1457    /// `ON UPDATE` action. Defaults to `Restrict` if absent.
1458    pub on_update: FkAction,
1459}
1460
1461/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
1462#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1463pub enum FkAction {
1464    /// Reject the parent mutation if any child row references it.
1465    /// SQL spec default; SPG default when no clause is given.
1466    Restrict,
1467    /// Recursively propagate the parent's delete / update to the
1468    /// child rows. Same TX.
1469    Cascade,
1470    /// Set the child FK column(s) to NULL. Requires the FK columns
1471    /// to be NULL-able.
1472    SetNull,
1473    /// Set the child FK column(s) to their declared DEFAULT.
1474    /// Requires the child column(s) to have DEFAULT.
1475    SetDefault,
1476    /// SQL spec `NO ACTION` (deferred check). SPG treats this as
1477    /// `Restrict` because the single-writer model has no deferred
1478    /// constraint window; the keyword is accepted for compatibility.
1479    NoAction,
1480}
1481
1482/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
1483/// optional `USING <encoding>` clause; omitting it keeps the
1484/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
1485/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
1486/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
1487/// binary16 (2× compression, ~3 decimal digits of precision).
1488#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1489pub enum VecEncoding {
1490    /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
1491    /// uncompressed `vector` type wire / storage layout.
1492    #[default]
1493    F32,
1494    /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
1495    /// `spg_storage::quantize::Sq8Vector` for the math + recall
1496    /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
1497    /// dim ≥ 32).
1498    Sq8,
1499    /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
1500    /// per-element. DDL keyword `HALF` (pgvector convention).
1501    /// Bit-exact dequantise to f32 at the storage layer; no
1502    /// rerank pass needed for kNN search.
1503    F16,
1504}
1505
1506impl fmt::Display for VecEncoding {
1507    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1508        match self {
1509            Self::F32 => f.write_str("F32"),
1510            Self::Sq8 => f.write_str("SQ8"),
1511            // pgvector convention: DDL keyword is `HALF`, not `F16`.
1512            Self::F16 => f.write_str("HALF"),
1513        }
1514    }
1515}
1516
1517/// SQL-level type names. The mapping to the storage runtime's `DataType`
1518/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
1519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1520pub enum ColumnTypeName {
1521    SmallInt,
1522    Int,
1523    BigInt,
1524    Float,
1525    Text,
1526    /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
1527    Varchar(u32),
1528    /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
1529    Char(u32),
1530    Bool,
1531    /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
1532    /// `USING <encoding>` clause; omitting it surfaces as
1533    /// `encoding = VecEncoding::F32` (the pre-v6 default).
1534    Vector {
1535        dim: u32,
1536        encoding: VecEncoding,
1537    },
1538    /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
1539    /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
1540    Numeric(u8, u8),
1541    /// `DATE` — calendar day, no time-of-day component.
1542    Date,
1543    /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
1544    /// precision.
1545    Timestamp,
1546    /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
1547    /// stores all timestamps as UTC microseconds-since-epoch and
1548    /// does not carry per-row offset (PG's internal representation
1549    /// is the same — TZ is a display convention). The distinction
1550    /// from `TIMESTAMP` exists for the PG-wire layer to advertise
1551    /// OID 1184 so sqlx-style clients decode into
1552    /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
1553    Timestamptz,
1554    /// v4.9 `JSON` — text-backed JSON document. No parse-time
1555    /// validation; the engine round-trips the literal verbatim.
1556    /// PG OID 114 on the wire.
1557    Json,
1558    /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
1559    /// PG OID 3802 on the wire so sqlx-style binary-typed clients
1560    /// decode without a custom type registration.
1561    Jsonb,
1562    /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
1563    /// Literal forms (decoded by the engine at coercion time):
1564    ///   - PG hex form: `'\xDEADBEEF'`
1565    ///   - Escape form: `'foo\\000bar'` (backslash octal triples)
1566    Bytes,
1567    /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
1568    /// OID 1009. Literal forms accepted by the parser:
1569    ///   - `ARRAY['a', 'b', NULL]`
1570    ///   - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
1571    ///     form at coerce time)
1572    TextArray,
1573    /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
1574    /// 1007. Same literal forms as TEXT[] (substituting integer
1575    /// elements).
1576    IntArray,
1577    /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
1578    /// OID 1016.
1579    BigIntArray,
1580    /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
1581    /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
1582    /// external form). G-CRIT-3.
1583    TsVector,
1584    /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
1585    /// wire OID 3615.
1586    TsQuery,
1587    /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
1588    /// Literal input accepts canonical hyphenated, unhyphenated,
1589    /// uppercase, and `{...}`-braced forms; display normalises to
1590    /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
1591    /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
1592    /// gen_random_uuid()`.
1593    Uuid,
1594    /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
1595    /// microseconds since 00:00:00. PG wire OID 1083. Literal
1596    /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
1597    /// (6-digit microsecond precision). Display normalises to
1598    /// the canonical `HH:MM:SS[.ffffff]`.
1599    Time,
1600    /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
1601    /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
1602    /// PG OID; advertised as INT4 on the wire. Display always
1603    /// 4 digits zero-padded.
1604    Year,
1605    /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
1606    /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
1607    /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
1608    /// Offset range: ±14 hours.
1609    TimeTz,
1610    /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
1611    /// (locale-independent storage). Wire OID 790. Literal input
1612    /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
1613    /// major units), optional leading `-`. Display: en_US locale.
1614    Money,
1615    /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
1616    /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
1617    /// — the engine bridges to `DataType::Range(RangeKind)`.
1618    Range(RangeKindAst),
1619    /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
1620    /// `text => text` map with NULL value support.
1621    Hstore,
1622    /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
1623    IntArray2D,
1624    BigIntArray2D,
1625    TextArray2D,
1626    /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
1627    /// three-field {months, days, micros} struct (PG-byte-equal),
1628    /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
1629    /// β-P2 `INTERVAL` was runtime-only — literal in expression
1630    /// position but rejected at CREATE TABLE.
1631    Interval,
1632    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
1633    /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
1634    /// PG external form quotes each non-NULL element because
1635    /// interval text contains spaces / colons
1636    /// (`{"1 day","24:00:00",NULL}`).
1637    IntervalArray,
1638    /// v7.37.5 γ — full PG array-of-scalar family. Each variant
1639    /// mirrors a scalar `ColumnTypeName` that already existed.
1640    BoolArray,
1641    SmallIntArray,
1642    FloatArray,
1643    NumericArray,
1644    DateArray,
1645    TimestampArray,
1646    TimestamptzArray,
1647    UuidArray,
1648    JsonArray,
1649    JsonbArray,
1650    BytesArray,
1651    VarcharArray,
1652    CharArray,
1653    /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
1654    /// as `Range(RangeKindAst)` — one column type variant covers
1655    /// all six builtin multiranges, kind pins the element type.
1656    /// Wire OIDs in pgwire.
1657    Multirange(RangeKindAst),
1658    /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
1659    /// one to a PG type: point/lseg/path/box/polygon/line/circle.
1660    /// Wire OIDs in pgwire.
1661    Point,
1662    Lseg,
1663    Path,
1664    PgBox,
1665    Polygon,
1666    Line,
1667    Circle,
1668    /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
1669    Inet,
1670    Cidr,
1671    Macaddr,
1672    Macaddr8,
1673    Bit,
1674    BitVarying,
1675    Xml,
1676    Char1,
1677    MoneyArray,
1678}
1679
1680/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
1681/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
1682/// crate doesn't depend on storage. Bridged at engine boundary.
1683#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
1684pub enum RangeKindAst {
1685    Int4,
1686    Int8,
1687    Num,
1688    Ts,
1689    TsTz,
1690    Date,
1691}
1692
1693impl fmt::Display for ColumnTypeName {
1694    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1695        match self {
1696            Self::SmallInt => f.write_str("SMALLINT"),
1697            Self::Int => f.write_str("INT"),
1698            Self::BigInt => f.write_str("BIGINT"),
1699            Self::Float => f.write_str("FLOAT"),
1700            Self::Text => f.write_str("TEXT"),
1701            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
1702            Self::Char(n) => write!(f, "CHAR({n})"),
1703            Self::Bool => f.write_str("BOOL"),
1704            Self::Vector { dim, encoding } => match encoding {
1705                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
1706                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
1707                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
1708            },
1709            Self::Json => f.write_str("JSON"),
1710            Self::Jsonb => f.write_str("JSONB"),
1711            Self::Bytes => f.write_str("BYTEA"),
1712            Self::TextArray => f.write_str("TEXT[]"),
1713            Self::IntArray => f.write_str("INT[]"),
1714            Self::BigIntArray => f.write_str("BIGINT[]"),
1715            Self::TsVector => f.write_str("TSVECTOR"),
1716            Self::TsQuery => f.write_str("TSQUERY"),
1717            Self::Uuid => f.write_str("UUID"),
1718            Self::Numeric(p, s) => {
1719                if *s == 0 {
1720                    write!(f, "NUMERIC({p})")
1721                } else {
1722                    write!(f, "NUMERIC({p}, {s})")
1723                }
1724            }
1725            Self::Date => f.write_str("DATE"),
1726            Self::Timestamp => f.write_str("TIMESTAMP"),
1727            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
1728            Self::Time => f.write_str("TIME"),
1729            Self::Year => f.write_str("YEAR"),
1730            Self::TimeTz => f.write_str("TIMETZ"),
1731            Self::Money => f.write_str("MONEY"),
1732            Self::Range(k) => f.write_str(match k {
1733                RangeKindAst::Int4 => "INT4RANGE",
1734                RangeKindAst::Int8 => "INT8RANGE",
1735                RangeKindAst::Num => "NUMRANGE",
1736                RangeKindAst::Ts => "TSRANGE",
1737                RangeKindAst::TsTz => "TSTZRANGE",
1738                RangeKindAst::Date => "DATERANGE",
1739            }),
1740            Self::Hstore => f.write_str("HSTORE"),
1741            Self::Interval => f.write_str("INTERVAL"),
1742            Self::IntervalArray => f.write_str("INTERVAL[]"),
1743            Self::BoolArray => f.write_str("BOOL[]"),
1744            Self::SmallIntArray => f.write_str("SMALLINT[]"),
1745            Self::FloatArray => f.write_str("FLOAT[]"),
1746            Self::NumericArray => f.write_str("NUMERIC[]"),
1747            Self::DateArray => f.write_str("DATE[]"),
1748            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
1749            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
1750            Self::UuidArray => f.write_str("UUID[]"),
1751            Self::JsonArray => f.write_str("JSON[]"),
1752            Self::JsonbArray => f.write_str("JSONB[]"),
1753            Self::BytesArray => f.write_str("BYTEA[]"),
1754            Self::VarcharArray => f.write_str("VARCHAR[]"),
1755            Self::CharArray => f.write_str("CHAR[]"),
1756            Self::Multirange(k) => f.write_str(match k {
1757                RangeKindAst::Int4 => "INT4MULTIRANGE",
1758                RangeKindAst::Int8 => "INT8MULTIRANGE",
1759                RangeKindAst::Num => "NUMMULTIRANGE",
1760                RangeKindAst::Ts => "TSMULTIRANGE",
1761                RangeKindAst::TsTz => "TSTZMULTIRANGE",
1762                RangeKindAst::Date => "DATEMULTIRANGE",
1763            }),
1764            Self::Point => f.write_str("POINT"),
1765            Self::Lseg => f.write_str("LSEG"),
1766            Self::Path => f.write_str("PATH"),
1767            Self::PgBox => f.write_str("BOX"),
1768            Self::Polygon => f.write_str("POLYGON"),
1769            Self::Line => f.write_str("LINE"),
1770            Self::Circle => f.write_str("CIRCLE"),
1771            Self::Inet => f.write_str("INET"),
1772            Self::Cidr => f.write_str("CIDR"),
1773            Self::Macaddr => f.write_str("MACADDR"),
1774            Self::Macaddr8 => f.write_str("MACADDR8"),
1775            Self::Bit => f.write_str("BIT"),
1776            Self::BitVarying => f.write_str("VARBIT"),
1777            Self::Xml => f.write_str("XML"),
1778            Self::Char1 => f.write_str("\"char\""),
1779            Self::MoneyArray => f.write_str("MONEY[]"),
1780            Self::IntArray2D => f.write_str("INT[][]"),
1781            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
1782            Self::TextArray2D => f.write_str("TEXT[][]"),
1783        }
1784    }
1785}
1786
1787/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
1788/// engine evaluates `expr` per matched row in the table's row order
1789/// and rewrites cells in place. Indexed columns are dropped + re-
1790/// inserted into the affected B-tree on each row change.
1791#[derive(Debug, Clone, PartialEq)]
1792pub struct UpdateStatement {
1793    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
1794    /// level UPDATE. Empty for a plain UPDATE.
1795    pub ctes: Vec<Cte>,
1796    pub table: String,
1797    pub assignments: Vec<(String, Expr)>,
1798    pub where_: Option<Expr>,
1799    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
1800    /// clause (legacy CommandComplete path). Some = engine
1801    /// evaluates the projection over each mutated row and
1802    /// streams the result as a Rows QueryResult.
1803    pub returning: Option<Vec<SelectItem>>,
1804}
1805
1806/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
1807/// from the active catalog and prunes them from every index.
1808#[derive(Debug, Clone, PartialEq)]
1809pub struct DeleteStatement {
1810    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
1811    /// level DELETE. Empty for a plain DELETE.
1812    pub ctes: Vec<Cte>,
1813    pub table: String,
1814    pub where_: Option<Expr>,
1815    /// v7.9.4 — `RETURNING <projection>`.
1816    pub returning: Option<Vec<SelectItem>>,
1817}
1818
1819/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
1820/// One WHEN clause fires per source row depending on whether the
1821/// `on` condition matched any target row(s); the executor walks
1822/// `clauses` in declaration order and fires the first whose
1823/// `matched` kind and optional `condition` are both satisfied.
1824#[derive(Debug, Clone, PartialEq)]
1825pub struct MergeStatement {
1826    pub target: String,
1827    pub target_alias: Option<String>,
1828    pub source: String,
1829    pub source_alias: Option<String>,
1830    pub on: Expr,
1831    pub clauses: Vec<MergeWhenClause>,
1832}
1833
1834#[derive(Debug, Clone, PartialEq)]
1835pub struct MergeWhenClause {
1836    pub matched: MergeMatched,
1837    /// Optional `AND <expr>` filter — when present, the clause
1838    /// only fires for the source rows whose match-pair satisfies
1839    /// the predicate.
1840    pub condition: Option<Expr>,
1841    pub action: MergeAction,
1842}
1843
1844#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1845pub enum MergeMatched {
1846    Matched,
1847    NotMatched,
1848}
1849
1850#[derive(Debug, Clone, PartialEq)]
1851pub enum MergeAction {
1852    /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
1853    /// explicit column list (the bare `INSERT VALUES (vals)`
1854    /// shape lands later).
1855    Insert {
1856        columns: Vec<String>,
1857        values: Vec<Expr>,
1858    },
1859    /// `UPDATE SET col = expr [, …]` — applied to every matched
1860    /// target row for the firing source row.
1861    Update { assignments: Vec<(String, Expr)> },
1862    /// `DELETE` — drop every matched target row.
1863    Delete,
1864    /// `DO NOTHING` — explicit no-op (the SQL standard accepts
1865    /// the clause and SPG mirrors so a customer-side MERGE that
1866    /// uses it for branch-control doesn't error).
1867    DoNothing,
1868}
1869
1870#[derive(Debug, Clone, PartialEq)]
1871pub struct InsertStatement {
1872    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
1873    /// level INSERT (writable CTE outer body). Empty for a plain
1874    /// INSERT. PG semantics: each CTE materialises before the
1875    /// outer INSERT runs, sharing the same transaction.
1876    pub ctes: Vec<Cte>,
1877    pub table: String,
1878    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
1879    /// `None`, every tuple is positional and must match the table arity.
1880    /// When `Some`, the engine maps each tuple slot to the named column and
1881    /// fills the rest with NULL (must be nullable).
1882    pub columns: Option<Vec<String>>,
1883    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
1884    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
1885    /// `select_source` is `Some` (the engine builds rows from the
1886    /// inner SELECT result set instead).
1887    pub rows: Vec<Vec<Expr>>,
1888    /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
1889    /// round-5 G4). When present, `rows` is empty and the engine
1890    /// materialises the SELECT result, coerces each output tuple to
1891    /// the target column types, and inserts as a single batch.
1892    pub select_source: Option<Box<SelectStatement>>,
1893    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
1894    /// upsert clause. None = legacy INSERT (conflict raises a
1895    /// DuplicateKey error). mailrs migration blocker #2.
1896    pub on_conflict: Option<OnConflictClause>,
1897    /// v7.9.4 — `RETURNING <projection>`.
1898    pub returning: Option<Vec<SelectItem>>,
1899}
1900
1901/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
1902#[derive(Debug, Clone, PartialEq)]
1903pub struct OnConflictClause {
1904    /// Local columns that identify the conflict (must match a
1905    /// UNIQUE / PRIMARY KEY index on the target table). Empty
1906    /// list means the user wrote `ON CONFLICT DO …` without a
1907    /// target — engine picks the table's first BTree index by
1908    /// convention.
1909    pub target_columns: Vec<String>,
1910    /// The action on conflict.
1911    pub action: OnConflictAction,
1912}
1913
1914/// v7.9.7 — action on conflict.
1915#[derive(Debug, Clone, PartialEq)]
1916pub enum OnConflictAction {
1917    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
1918    /// silently skips conflicting ones.
1919    Nothing,
1920    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
1921    /// may reference `EXCLUDED.col` to read the incoming row's
1922    /// value (engine wires `EXCLUDED` as a virtual table).
1923    Update {
1924        assignments: Vec<(String, Expr)>,
1925        where_: Option<Expr>,
1926    },
1927}
1928
1929#[derive(Debug, Clone, PartialEq, Default)]
1930pub struct SelectStatement {
1931    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
1932    /// expressions, materialised once at query start before the
1933    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
1934    /// only — no `WITH RECURSIVE` for v4.x.
1935    pub ctes: Vec<Cte>,
1936    pub distinct: bool,
1937    pub items: Vec<SelectItem>,
1938    pub from: Option<FromClause>,
1939    pub where_: Option<Expr>,
1940    pub group_by: Option<Vec<Expr>>,
1941    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
1942    /// expands `group_by` to every non-aggregate SELECT-list item
1943    /// before the executor runs. Mutually exclusive with an
1944    /// explicit `group_by` list (the parser sets exactly one).
1945    pub group_by_all: bool,
1946    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
1947    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
1948    /// aggregate executor resolves them through the same synthetic
1949    /// schema used for the SELECT items.
1950    pub having: Option<Expr>,
1951    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
1952    /// itself a `SelectStatement` with `order_by = None` and `limit =
1953    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
1954    /// top of the chain).
1955    pub unions: Vec<(UnionKind, SelectStatement)>,
1956    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
1957    /// Keys are matched left-to-right: first key decides, ties break
1958    /// to the second, etc.
1959    pub order_by: Vec<OrderBy>,
1960    /// `LIMIT <n>` — bound on row output. `n` is an integer
1961    /// literal **or** (v7.9.24) a placeholder `$N` resolved
1962    /// against the prepared-statement Bind values. mailrs
1963    /// migration follow-up H2.
1964    pub limit: Option<LimitExpr>,
1965    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
1966    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
1967    pub offset: Option<LimitExpr>,
1968    /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
1969    /// (SQL:2008). When true and an ORDER BY is present, the
1970    /// executor extends past the LIMIT-truncated tail to include
1971    /// every row whose ORDER BY key equals the last-kept row's
1972    /// key. Requires an ORDER BY; the executor errors otherwise
1973    /// (matching PG's `WITH TIES` rule). The parser was already
1974    /// accepting `WITH TIES` since Phase 5.1; this field captures
1975    /// the choice so the executor can act on it.
1976    pub limit_with_ties: bool,
1977}
1978
1979/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
1980/// time or a placeholder `$N` resolved during extended-query
1981/// Bind. mailrs migration follow-up H2.
1982#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1983pub enum LimitExpr {
1984    /// `LIMIT 10` — value known at parse time.
1985    Literal(u32),
1986    /// `LIMIT $N` — the 1-based parameter index, resolved against
1987    /// the bind values when the prepared statement executes.
1988    Placeholder(u16),
1989}
1990
1991impl fmt::Display for LimitExpr {
1992    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1993        match self {
1994            Self::Literal(n) => write!(f, "{n}"),
1995            Self::Placeholder(n) => write!(f, "${n}"),
1996        }
1997    }
1998}
1999
2000impl LimitExpr {
2001    /// Convenience for the simple-query path where no placeholders
2002    /// can possibly exist. Returns the literal value or `None` if
2003    /// this is a placeholder (caller must surface as Unsupported).
2004    pub fn as_literal(self) -> Option<u32> {
2005        match self {
2006            Self::Literal(n) => Some(n),
2007            Self::Placeholder(_) => None,
2008        }
2009    }
2010}
2011
2012/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
2013/// the engine's `substitute_placeholders` pass these are
2014/// always Literal; in the simple-query path a Placeholder
2015/// shape returns None (executor surfaces as
2016/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
2017impl SelectStatement {
2018    #[must_use]
2019    pub fn limit_literal(&self) -> Option<u32> {
2020        self.limit.and_then(LimitExpr::as_literal)
2021    }
2022    #[must_use]
2023    pub fn offset_literal(&self) -> Option<u32> {
2024        self.offset.and_then(LimitExpr::as_literal)
2025    }
2026}
2027
2028#[derive(Debug, Clone, PartialEq)]
2029pub struct Cte {
2030    pub name: String,
2031    /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
2032    /// classical case) or a data-modifying statement
2033    /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
2034    /// CTE semantics. The modifying body's RETURNING projection
2035    /// becomes the materialised CTE table the outer query can
2036    /// reference; the modifying statement runs once before the
2037    /// outer query, within the same transaction.
2038    pub body: CteBody,
2039    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
2040    /// RECURSIVE keyword. Applies to every CTE in the clause per
2041    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
2042    /// allowed; the engine just runs it once.
2043    pub recursive: bool,
2044    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
2045    /// non-empty, these override the body's output column names
2046    /// position-by-position; the engine errors out if the count
2047    /// doesn't match the body's projection width.
2048    pub column_overrides: Vec<String>,
2049}
2050
2051/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
2052/// (Insert / Update / Delete with optional RETURNING). The
2053/// data-modifying variants must carry a RETURNING projection for the
2054/// outer query to reference the CTE alias by; an empty RETURNING is
2055/// only valid if no outer reference materialises (rare — typically
2056/// caught at planning).
2057#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
2058#[derive(Debug, Clone, PartialEq)]
2059pub enum CteBody {
2060    Select(SelectStatement),
2061    Insert(Box<InsertStatement>),
2062    Update(Box<UpdateStatement>),
2063    Delete(Box<DeleteStatement>),
2064}
2065
2066impl CteBody {
2067    /// Convenience accessor used by classical (read-only) CTE
2068    /// callsites that still expect a SELECT body. Returns None for
2069    /// data-modifying CTEs; callers must explicitly route those
2070    /// through `exec_with_ctes`'s modifying branch.
2071    #[must_use]
2072    pub fn as_select(&self) -> Option<&SelectStatement> {
2073        match self {
2074            Self::Select(s) => Some(s),
2075            _ => None,
2076        }
2077    }
2078
2079    #[must_use]
2080    pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
2081        match self {
2082            Self::Select(s) => Some(s),
2083            _ => None,
2084        }
2085    }
2086
2087    #[must_use]
2088    pub fn is_modifying(&self) -> bool {
2089        !matches!(self, Self::Select(_))
2090    }
2091}
2092
2093#[derive(Debug, Clone, PartialEq)]
2094pub struct OrderBy {
2095    pub expr: Expr,
2096    /// `false` = ASC (default), `true` = DESC.
2097    pub desc: bool,
2098    /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
2099    /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
2100    /// NULLS FIRST for DESC); the engine resolves the effective
2101    /// value via `nulls_first.unwrap_or(desc)`.
2102    pub nulls_first: Option<bool>,
2103}
2104
2105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2106pub enum UnionKind {
2107    /// `UNION` — dedupes the combined set.
2108    Distinct,
2109    /// `UNION ALL` — concatenates without dedup.
2110    All,
2111}
2112
2113#[derive(Debug, Clone, PartialEq)]
2114pub enum SelectItem {
2115    Wildcard,
2116    Expr { expr: Expr, alias: Option<String> },
2117}
2118
2119#[derive(Debug, Clone, PartialEq)]
2120pub struct TableRef {
2121    pub name: String,
2122    pub alias: Option<String>,
2123    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
2124    /// When `Some(id)`, the scan restricts to rows that live in
2125    /// segment `<id>` only — useful for forensic inspection of a
2126    /// specific freezer-emitted segment without exposing the hot
2127    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
2128    /// is STABILITY carve-out for v6.10 — needs the freezer to
2129    /// stamp each segment with a wall-clock at creation time.
2130    pub as_of_segment: Option<u32>,
2131    /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
2132    /// source. When `Some`, `name` is the alias (defaulting to
2133    /// `"unnest"` when no `AS` is given) and the engine builds a
2134    /// synthetic single-column table by evaluating the expression
2135    /// once at SELECT entry. Each TEXT[] element becomes one row;
2136    /// NULL elements become NULL cells. v7.11 supported
2137    /// uncorrelated UNNEST only as the FROM primary; v7.13.2
2138    /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
2139    /// position (cross-join with regular tables).
2140    pub unnest_expr: Option<Box<Expr>>,
2141    /// v7.13.2 — mailrs round-6 S5. PG-standard
2142    /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
2143    /// when non-empty, the first entry overrides the projected
2144    /// column name for the unnested column. Empty = fall back to
2145    /// the table alias (pre-v7.13.2 behaviour).
2146    pub unnest_column_aliases: Vec<String>,
2147    /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
2148    /// [, step])` set-returning source. When `Some`, the engine
2149    /// materialises a single-column virtual table by stepping
2150    /// `start` to `stop` inclusive. Args are the literal arg list
2151    /// (2 for default-step, 3 for explicit-step). Supports:
2152    ///   * SmallInt / Int / BigInt with integer step (default = 1)
2153    ///   * Timestamp with INTERVAL step (PG date-range pattern)
2154    /// Mutually exclusive with `unnest_expr` — both populate the
2155    /// same downstream dispatch slot. `name` defaults to
2156    /// `"generate_series"` when no alias is provided.
2157    pub generate_series_args: Option<Vec<Expr>>,
2158    /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
2159    /// table. When `Some`, the TableRef is a parenthesised SELECT
2160    /// that may reference columns from the preceding FROM items
2161    /// (correlated derived table). The executor materialises the
2162    /// subquery per left-row, substituting outer-column references
2163    /// against the current join row's values before running the
2164    /// inner SELECT, then cross-joins the result back.
2165    /// Mutually exclusive with `name` / `unnest_expr` /
2166    /// `generate_series_args`.
2167    pub lateral_subquery: Option<Box<SelectStatement>>,
2168    /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
2169    /// function as a FROM item. PG semantics: for each key/value
2170    /// pair in the JSONB object argument, emit one (key TEXT,
2171    /// value TEXT) row. When prefixed by `LATERAL` and joined via
2172    /// `CROSS JOIN LATERAL`, the argument may reference columns
2173    /// from a preceding FROM item, in which case the executor
2174    /// evaluates `<expr>` per outer row.
2175    /// Mutually exclusive with `unnest_expr` / `generate_series_args`
2176    /// / `lateral_subquery`. The optional `LATERAL` keyword does not
2177    /// require a separate flag — the executor evaluates per-row
2178    /// whenever the join sits in a JoinKind context.
2179    pub jsonb_each_text_arg: Option<Box<Expr>>,
2180}
2181
2182/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
2183/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
2184/// joins evaluate left-associatively in nested-loop order.
2185#[derive(Debug, Clone, PartialEq)]
2186pub struct FromClause {
2187    pub primary: TableRef,
2188    pub joins: Vec<FromJoin>,
2189}
2190
2191#[derive(Debug, Clone, PartialEq)]
2192pub struct FromJoin {
2193    pub kind: JoinKind,
2194    pub table: TableRef,
2195    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
2196    pub on: Option<Expr>,
2197}
2198
2199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2200pub enum JoinKind {
2201    Inner,
2202    Left,
2203    Cross,
2204}
2205
2206#[derive(Debug, Clone, PartialEq)]
2207pub enum Expr {
2208    Literal(Literal),
2209    Column(ColumnName),
2210    /// v6.1.1 — `$N` parameter placeholder for the extended query
2211    /// protocol. The number is 1-based per PostgreSQL convention.
2212    /// Evaluation looks up `params[N-1]` from the prepared-statement
2213    /// bind buffer; out-of-range indices raise a runtime error
2214    /// (same shape as a column-not-found miss).
2215    Placeholder(u16),
2216    Binary {
2217        lhs: Box<Expr>,
2218        op: BinOp,
2219        rhs: Box<Expr>,
2220    },
2221    Unary {
2222        op: UnOp,
2223        expr: Box<Expr>,
2224    },
2225    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
2226    /// TEXT, BOOL targets; engine coerces at evaluation time.
2227    Cast {
2228        expr: Box<Expr>,
2229        target: CastTarget,
2230    },
2231    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
2232    IsNull {
2233        expr: Box<Expr>,
2234        negated: bool,
2235    },
2236    /// Function call `name(args...)`. v1.4 supports a small built-in set
2237    /// (length, upper, lower, abs, coalesce); unknown names error at eval
2238    /// time so the parser stays open for v1.5 aggregates.
2239    FunctionCall {
2240        name: String,
2241        args: Vec<Expr>,
2242    },
2243    /// v7.24 (mailrs round-16 A) — an aggregate call with an
2244    /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
2245    /// Wraps the plain [`Expr::FunctionCall`] so every existing
2246    /// FunctionCall consumer stays untouched; only the aggregate
2247    /// executor (and the expression walkers) know the wrapper.
2248    /// Non-aggregate evaluation contexts reject it at eval time.
2249    AggregateOrdered {
2250        call: Box<Expr>,
2251        order_by: Vec<OrderBy>,
2252        /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
2253        /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
2254        /// aggregate modifier so plain FunctionCall stays untouched.
2255        distinct: bool,
2256        /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
2257        /// Only the rows where `cond` is true contribute to this
2258        /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
2259        /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
2260        /// END)`, which is faithful for NULL-ignoring aggregates but
2261        /// WRONG for `array_agg` (it would collect a NULL per excluded
2262        /// row). The executor instead skips excluded rows before
2263        /// accumulation, which is correct for every aggregate.
2264        filter: Option<Box<Expr>>,
2265    },
2266    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
2267    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
2268    /// the next char (so `\%` matches a literal `%`).
2269    Like {
2270        expr: Box<Expr>,
2271        pattern: Box<Expr>,
2272        negated: bool,
2273        /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
2274        /// match. PG folds both operands.
2275        case_insensitive: bool,
2276    },
2277    /// v4.12 window function call: `name(args) OVER (PARTITION BY
2278    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
2279    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
2280    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
2281    /// unordered windows and "from start of partition through
2282    /// current row" for ordered windows — no explicit ROWS /
2283    /// RANGE clause in v4.12 MVP.
2284    WindowFunction {
2285        name: String,
2286        args: Vec<Expr>,
2287        partition_by: Vec<Expr>,
2288        /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
2289        /// (None = PG default, same contract as [`OrderBy`]).
2290        order_by: Vec<(
2291            Expr,
2292            bool,         /* desc */
2293            Option<bool>, /* nulls_first */
2294        )>,
2295        /// v4.20 explicit frame. `None` means "use the default":
2296        /// whole-partition when unordered, running aggregate from
2297        /// partition start through current row when ordered.
2298        frame: Option<WindowFrame>,
2299        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
2300        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
2301        /// `Respect` (PG / ANSI default — NULLs participate). Other
2302        /// window functions ignore this flag.
2303        null_treatment: NullTreatment,
2304    },
2305    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
2306    /// position. Must return exactly one row × one column at eval
2307    /// time; the engine errors out otherwise. Uncorrelated only —
2308    /// the inner SELECT cannot reference outer columns.
2309    ScalarSubquery(Box<SelectStatement>),
2310    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
2311    /// projection is ignored; only row-count matters.
2312    Exists {
2313        subquery: Box<SelectStatement>,
2314        negated: bool,
2315    },
2316    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
2317    /// project exactly one column; membership is tested by Eq
2318    /// against each row's value (NULL handling follows ANSI:
2319    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
2320    InSubquery {
2321        expr: Box<Expr>,
2322        subquery: Box<SelectStatement>,
2323        negated: bool,
2324    },
2325    /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
2326    /// list. Both the parser's literal-list path and the engine's
2327    /// IN-subquery materialisation used to desugar into a left-deep
2328    /// OR-Eq chain, so expression depth scaled with the element count
2329    /// — a 24k-row subquery result overflowed the 2 MiB worker stack
2330    /// (recursive eval AND recursive Box drop) and aborted embedding
2331    /// host processes. The flat node keeps depth constant: eval is an
2332    /// iterative scan with PG three-valued logic, drop is a Vec drop.
2333    InList {
2334        expr: Box<Expr>,
2335        list: Vec<Expr>,
2336        negated: bool,
2337    },
2338    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
2339    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
2340    /// because the `FROM` keyword is what separates the two halves,
2341    /// not a comma.
2342    Extract {
2343        field: ExtractField,
2344        source: Box<Expr>,
2345    },
2346    /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
2347    /// element is evaluated independently; NULLs are allowed.
2348    /// v7.10 supports only single-dimension TEXT[] semantically;
2349    /// non-text elements coerce at engine evaluation time when
2350    /// the surrounding context (column type / cast) makes the
2351    /// target clear.
2352    Array(Vec<Expr>),
2353    /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
2354    /// engine returns NULL for out-of-range indices.
2355    ArraySubscript {
2356        target: Box<Expr>,
2357        index: Box<Expr>,
2358    },
2359    /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
2360    /// operator is the comparison binary op (Eq / Ne / Lt / …);
2361    /// the engine desugars: `ANY` returns true if any element
2362    /// satisfies; `ALL` returns true only if every element does.
2363    /// NULL handling follows PG's three-valued logic.
2364    AnyAll {
2365        expr: Box<Expr>,
2366        op: BinOp,
2367        array: Box<Expr>,
2368        /// `true` = ANY, `false` = ALL.
2369        is_any: bool,
2370    },
2371    /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
2372    /// (searched form, `operand` is None) and
2373    /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
2374    /// `operand` is the lead expression compared against each
2375    /// branch's match). Each `(when_expr, then_expr)` branch
2376    /// stays as written; engine short-circuits on the first match.
2377    /// `else_branch` is `None` when no ELSE; evaluates to NULL.
2378    /// mailrs round-5 G9.
2379    Case {
2380        operand: Option<Box<Expr>>,
2381        branches: Vec<(Expr, Expr)>,
2382        else_branch: Option<Box<Expr>>,
2383    },
2384}
2385
2386/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
2387/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
2388/// in the offset walk. `Ignore` causes the function to skip NULL
2389/// values in the argument expression, returning the next non-NULL.
2390#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2391pub enum NullTreatment {
2392    #[default]
2393    Respect,
2394    Ignore,
2395}
2396
2397/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
2398/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
2399/// where end implicitly = CURRENT ROW.
2400#[derive(Debug, Clone, PartialEq, Eq)]
2401pub struct WindowFrame {
2402    pub kind: FrameKind,
2403    pub start: FrameBound,
2404    pub end: Option<FrameBound>,
2405}
2406
2407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2408pub enum FrameKind {
2409    Rows,
2410    Range,
2411}
2412
2413#[derive(Debug, Clone, PartialEq, Eq)]
2414pub enum FrameBound {
2415    UnboundedPreceding,
2416    OffsetPreceding(u64),
2417    CurrentRow,
2418    OffsetFollowing(u64),
2419    UnboundedFollowing,
2420}
2421
2422impl fmt::Display for FrameBound {
2423    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2424        match self {
2425            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
2426            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
2427            Self::CurrentRow => f.write_str("CURRENT ROW"),
2428            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
2429            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
2430        }
2431    }
2432}
2433
2434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2435pub enum ExtractField {
2436    Year,
2437    Month,
2438    Day,
2439    Hour,
2440    Minute,
2441    Second,
2442    Microsecond,
2443    /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
2444    /// SPG keeps the integer convention — truncated seconds).
2445    Epoch,
2446}
2447
2448impl fmt::Display for ExtractField {
2449    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2450        f.write_str(match self {
2451            Self::Year => "YEAR",
2452            Self::Month => "MONTH",
2453            Self::Day => "DAY",
2454            Self::Hour => "HOUR",
2455            Self::Minute => "MINUTE",
2456            Self::Second => "SECOND",
2457            Self::Microsecond => "MICROSECOND",
2458            Self::Epoch => "EPOCH",
2459        })
2460    }
2461}
2462
2463#[derive(Debug, Clone, PartialEq, Eq)]
2464pub enum CastTarget {
2465    Int,
2466    BigInt,
2467    Float,
2468    Text,
2469    Bool,
2470    Vector,
2471    Date,
2472    Timestamp,
2473    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
2474    /// H3a. Engine reuses the existing runtime-interval / timestamp
2475    /// paths (parse the text input, return the matching Value).
2476    Interval,
2477    Timestamptz,
2478    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
2479    /// types (v7.9.0); the cast just routes Text→Json with the
2480    /// requested OID for the wire layer.
2481    Json,
2482    Jsonb,
2483    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
2484    /// compatibility; engine surfaces as Unsupported with a
2485    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
2486    RegType,
2487    RegClass,
2488    /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
2489    /// the PG external array form `{a,b,NULL}`.
2490    TextArray,
2491    /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
2492    /// `{1,2,3}` or widens a `TextArray` whose elements are
2493    /// integer-shaped.
2494    IntArray,
2495    BigIntArray,
2496    /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
2497    /// external form text representation. Used by pg_dump output
2498    /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
2499    TsVector,
2500    TsQuery,
2501    /// v7.17.0 — `::uuid`. Decodes the LHS Text via
2502    /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
2503    /// unhyphenated, uppercase, and brace-wrapped forms); malformed
2504    /// input is a SQL error.
2505    Uuid,
2506    /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
2507    /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
2508    /// inputs pass through unchanged. Closes the mailrs D-pre #3
2509    /// reverse-acceptance gap — anywhere a PG schema writes
2510    /// `expr::bytea`, SPG now matches.
2511    Bytea,
2512    /// v7.37.5 ship triage — generic cast target for the long tail
2513    /// of PG type names the parser meets in `expr::TYPE` shapes that
2514    /// don't deserve their own enum variant. The engine routes these
2515    /// through `column_type_to_data_type` + the existing typed
2516    /// `coerce_value` dispatch, so adding a new PG type to SPG
2517    /// implicitly adds its cast-target form too — no parser change
2518    /// per type. The string carries the lowercase PG type ident
2519    /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
2520    /// a clear message when the type isn't known.
2521    Named(String),
2522}
2523
2524impl fmt::Display for CastTarget {
2525    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2526        f.write_str(match self {
2527            Self::Int => "int",
2528            Self::BigInt => "bigint",
2529            Self::Float => "float",
2530            Self::Text => "text",
2531            Self::Bool => "bool",
2532            Self::Vector => "vector",
2533            Self::Interval => "interval",
2534            Self::Timestamptz => "timestamptz",
2535            Self::Json => "json",
2536            Self::Jsonb => "jsonb",
2537            Self::RegType => "regtype",
2538            Self::RegClass => "regclass",
2539            Self::Date => "date",
2540            Self::Timestamp => "timestamp",
2541            Self::TextArray => "TEXT[]",
2542            Self::IntArray => "INT[]",
2543            Self::BigIntArray => "BIGINT[]",
2544            Self::TsVector => "tsvector",
2545            Self::TsQuery => "tsquery",
2546            Self::Uuid => "uuid",
2547            Self::Bytea => "bytea",
2548            // v7.37.5 — `Self::Named` carries its own canonical name.
2549            Self::Named(name) => return f.write_str(name),
2550        })
2551    }
2552}
2553
2554#[derive(Debug, Clone, PartialEq)]
2555pub enum Literal {
2556    Integer(i64),
2557    Float(f64),
2558    String(String),
2559    Bool(bool),
2560    Null,
2561    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
2562    Vector(Vec<f32>),
2563    /// TEXT[] value carried through the prepared-bind path
2564    /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
2565    /// text form, so the array rides the AST natively).
2566    TextArray(Vec<Option<String>>),
2567    /// INT[] value carried through the prepared-bind path.
2568    IntArray(Vec<Option<i32>>),
2569    /// BIGINT[] value carried through the prepared-bind path.
2570    BigIntArray(Vec<Option<i64>>),
2571    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
2572    /// Three independent dimensions: `months` (variable-length;
2573    /// year/month), `days` (fixed 86400 seconds at non-DST, but
2574    /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
2575    /// stays distinguishable), and `micros` (sub-day; can carry).
2576    /// `text` keeps the original spelling so Display round-trips
2577    /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
2578    Interval {
2579        months: i32,
2580        days: i32,
2581        micros: i64,
2582        text: String,
2583    },
2584}
2585
2586#[derive(Debug, Clone, PartialEq, Eq)]
2587pub struct ColumnName {
2588    pub qualifier: Option<String>,
2589    pub name: String,
2590}
2591
2592#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2593pub enum BinOp {
2594    Or,
2595    And,
2596    Eq,
2597    NotEq,
2598    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
2599    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
2600    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
2601    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
2602    /// PG-style JOIN ON predicates and pg_dump output.
2603    IsDistinctFrom,
2604    IsNotDistinctFrom,
2605    Lt,
2606    LtEq,
2607    Gt,
2608    GtEq,
2609    Add,
2610    Sub,
2611    Mul,
2612    Div,
2613    /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
2614    /// precedence as Mul/Div; result type follows left operand.
2615    Mod,
2616    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
2617    /// operands of equal dimension; engine returns `Value::Float(d)`.
2618    L2Distance,
2619    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
2620    /// more similar" remains true (matches pgvector's published convention).
2621    InnerProduct,
2622    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
2623    CosineDistance,
2624    /// SQL string concatenation `||`. NULL propagates.
2625    Concat,
2626    /// Bitwise OR `|` on integers.
2627    BitOr,
2628    /// Bitwise AND `&` on integers.
2629    BitAnd,
2630    /// v4.14 `json -> key` — element access by string key (object)
2631    /// or integer index (array). Returns a JSON value.
2632    JsonGet,
2633    /// v4.14 `json ->> key` — same access, returns the result as
2634    /// TEXT (unwraps a top-level JSON string; renders other scalars
2635    /// as their canonical text).
2636    JsonGetText,
2637    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
2638    /// text array literal like `'{a,0,b}'`. Returns JSON.
2639    JsonGetPath,
2640    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
2641    JsonGetPathText,
2642    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
2643    /// when every key/value in `sub_json` is structurally present in
2644    /// the left side. Matches PG semantics (top-level + recursive).
2645    JsonContains,
2646    /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
2647    /// `a <@ b` is defined as `b @> a` (same semantics, swapped
2648    /// sides). Eval dispatch reuses `JsonContains` with swapped args.
2649    JsonContainedBy,
2650    /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
2651    /// returns BOOL. For an object, true if `key` is an existing
2652    /// member name; for an array, true if any element is the string
2653    /// `key` (PG semantics).
2654    JsonKeyExists,
2655    /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
2656    /// returns BOOL.
2657    JsonKeysAny,
2658    /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
2659    /// returns BOOL.
2660    JsonKeysAll,
2661    /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
2662    /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
2663    /// tsvector` and engine eval normalises either ordering.
2664    TsMatch,
2665    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
2666    /// `<<`. LHS network is strictly inside RHS network (no equality).
2667    InetContainedBy,
2668    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
2669    /// `<<=`. LHS network ⊆ RHS network.
2670    InetContainedByEq,
2671    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
2672    /// LHS network strictly contains RHS network.
2673    InetContains,
2674    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
2675    /// LHS network ⊇ RHS network.
2676    InetContainsEq,
2677    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
2678    /// True iff either network contains any address of the other.
2679    InetOverlap,
2680}
2681
2682#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2683pub enum UnOp {
2684    Not,
2685    Neg,
2686    /// Bitwise NOT `~` on integers.
2687    BitNot,
2688}
2689
2690// --- Display impls (round-trip-safe) --------------------------------------
2691
2692impl Statement {
2693    /// v7.18 — classify whether the statement is read-only at
2694    /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
2695    /// route SELECT-shaped traffic through the fan-out
2696    /// `AsyncReadHandle` (no writer-lock contention) while
2697    /// keeping DML / DDL / TX-control on the single-writer path.
2698    ///
2699    /// The classification matches what
2700    /// `Engine::execute_readonly_with_cancel` accepts: anything
2701    /// that does NOT mutate catalog, statistics, session state,
2702    /// or transaction state. WaitForWalPosition is included
2703    /// (engine returns `Unsupported`, but the classification is
2704    /// semantically read-only — no mutation). Empty is excluded
2705    /// out of an abundance of caution — the no-op routes
2706    /// through the writer so any future side effect lands
2707    /// uniformly.
2708    ///
2709    /// **Not connection-state aware**. `SET LOCAL` / `RESET`
2710    /// affect session parameters and must run on the writer
2711    /// engine that owns the session state; they classify as
2712    /// writer-path here. Same for `BEGIN` / `COMMIT` /
2713    /// `ROLLBACK` / `SAVEPOINT` — transaction control is
2714    /// always writer-path.
2715    #[must_use]
2716    pub fn is_readonly(&self) -> bool {
2717        match self {
2718            Statement::Select(_)
2719            | Statement::Explain(_)
2720            | Statement::ShowTables
2721            | Statement::ShowDatabases
2722            | Statement::ShowCreateTable(_)
2723            | Statement::ShowIndexes(_)
2724            | Statement::ShowStatus
2725            | Statement::ShowVariables
2726            | Statement::ShowProcesslist
2727            | Statement::ShowColumns(_)
2728            | Statement::ShowUsers
2729            | Statement::ShowPublications
2730            | Statement::ShowSubscriptions
2731            | Statement::WaitForWalPosition { .. } => true,
2732            // Everything else mutates catalog, statistics,
2733            // session state, or transaction state — writer path.
2734            // Listed explicitly so a new Statement variant fails
2735            // the match exhaustiveness check and forces a
2736            // classification decision at add-site.
2737            Statement::Empty
2738            | Statement::DropTable { .. }
2739            | Statement::DropIndex { .. }
2740            | Statement::CreateTable(_)
2741            | Statement::CreateExtension(_)
2742            | Statement::DoBlock(_)
2743            | Statement::CreateIndex(_)
2744            | Statement::Insert(_)
2745            | Statement::Update(_)
2746            | Statement::Delete(_)
2747            | Statement::Merge(_)
2748            | Statement::Begin
2749            | Statement::Commit
2750            | Statement::Rollback
2751            | Statement::Savepoint(_)
2752            | Statement::RollbackToSavepoint(_)
2753            | Statement::ReleaseSavepoint(_)
2754            | Statement::CreateUser(_)
2755            | Statement::DropUser(_)
2756            | Statement::AlterIndex(_)
2757            | Statement::AlterTable(_)
2758            | Statement::CreatePublication(_)
2759            | Statement::DropPublication(_)
2760            | Statement::CreateSubscription(_)
2761            | Statement::DropSubscription(_)
2762            | Statement::Analyze(_)
2763            | Statement::CompactColdSegments
2764            | Statement::SetParameter { .. }
2765            | Statement::SetParameterList(_)
2766            | Statement::SetTransaction { .. }
2767            | Statement::ShowParameter(_)
2768            | Statement::ResetParameter(_)
2769            | Statement::CreateFunction(_)
2770            | Statement::CreateTrigger(_)
2771            | Statement::DropTrigger { .. }
2772            | Statement::DropFunction { .. }
2773            | Statement::CreateSequence(_)
2774            | Statement::AlterSequence(_)
2775            | Statement::DropSequence { .. }
2776            | Statement::CreateView(_)
2777            | Statement::DropView { .. }
2778            | Statement::CreateMaterializedView(_)
2779            | Statement::RefreshMaterializedView { .. }
2780            | Statement::DropMaterializedView { .. }
2781            | Statement::CreateType(_)
2782            | Statement::DropType { .. }
2783            | Statement::CreateDomain(_)
2784            | Statement::DropDomain { .. }
2785            | Statement::CreateSchema { .. }
2786            | Statement::DropSchema { .. } => false,
2787        }
2788    }
2789}
2790
2791impl fmt::Display for Statement {
2792    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2793        match self {
2794            Self::Empty => Ok(()),
2795            Self::DropTable { names, if_exists } => {
2796                f.write_str("DROP TABLE ")?;
2797                if *if_exists {
2798                    f.write_str("IF EXISTS ")?;
2799                }
2800                for (i, n) in names.iter().enumerate() {
2801                    if i > 0 {
2802                        f.write_str(", ")?;
2803                    }
2804                    write!(f, "{}", quote_ident(n))?;
2805                }
2806                Ok(())
2807            }
2808            Self::DropIndex { name, if_exists } => {
2809                f.write_str("DROP INDEX ")?;
2810                if *if_exists {
2811                    f.write_str("IF EXISTS ")?;
2812                }
2813                write!(f, "{}", quote_ident(name))
2814            }
2815            Self::Select(s) => s.fmt(f),
2816            Self::CreateTable(s) => s.fmt(f),
2817            Self::CreateIndex(s) => s.fmt(f),
2818            Self::Insert(s) => s.fmt(f),
2819            Self::Update(s) => s.fmt(f),
2820            Self::Delete(s) => s.fmt(f),
2821            Self::Merge(s) => {
2822                // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
2823                // (it round-trips for the cases tests cover, not for
2824                // round-tripping every edge of the surface).
2825                f.write_str("MERGE INTO ")?;
2826                write!(f, "{}", quote_ident(&s.target))?;
2827                if let Some(a) = &s.target_alias {
2828                    write!(f, " {}", quote_ident(a))?;
2829                }
2830                f.write_str(" USING ")?;
2831                write!(f, "{}", quote_ident(&s.source))?;
2832                if let Some(a) = &s.source_alias {
2833                    write!(f, " {}", quote_ident(a))?;
2834                }
2835                write!(f, " ON {}", s.on)?;
2836                for clause in &s.clauses {
2837                    f.write_str(" WHEN ")?;
2838                    f.write_str(match clause.matched {
2839                        MergeMatched::Matched => "MATCHED",
2840                        MergeMatched::NotMatched => "NOT MATCHED",
2841                    })?;
2842                    if let Some(c) = &clause.condition {
2843                        write!(f, " AND {c}")?;
2844                    }
2845                    f.write_str(" THEN ")?;
2846                    match &clause.action {
2847                        MergeAction::Insert { columns, values } => {
2848                            f.write_str("INSERT (")?;
2849                            for (i, c) in columns.iter().enumerate() {
2850                                if i > 0 {
2851                                    f.write_str(", ")?;
2852                                }
2853                                write!(f, "{}", quote_ident(c))?;
2854                            }
2855                            f.write_str(") VALUES (")?;
2856                            for (i, v) in values.iter().enumerate() {
2857                                if i > 0 {
2858                                    f.write_str(", ")?;
2859                                }
2860                                write!(f, "{v}")?;
2861                            }
2862                            f.write_str(")")?;
2863                        }
2864                        MergeAction::Update { assignments } => {
2865                            f.write_str("UPDATE SET ")?;
2866                            for (i, (c, e)) in assignments.iter().enumerate() {
2867                                if i > 0 {
2868                                    f.write_str(", ")?;
2869                                }
2870                                write!(f, "{} = {e}", quote_ident(c))?;
2871                            }
2872                        }
2873                        MergeAction::Delete => f.write_str("DELETE")?,
2874                        MergeAction::DoNothing => f.write_str("DO NOTHING")?,
2875                    }
2876                }
2877                Ok(())
2878            }
2879            Self::Begin => f.write_str("BEGIN"),
2880            Self::Commit => f.write_str("COMMIT"),
2881            Self::Rollback => f.write_str("ROLLBACK"),
2882            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
2883            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
2884            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
2885            Self::ShowTables => f.write_str("SHOW TABLES"),
2886            Self::ShowDatabases => f.write_str("SHOW DATABASES"),
2887            Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
2888            Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
2889            Self::ShowStatus => f.write_str("SHOW STATUS"),
2890            Self::ShowVariables => f.write_str("SHOW VARIABLES"),
2891            Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
2892            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
2893            Self::CreateUser(s) => write!(
2894                f,
2895                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
2896                quote_ident(&s.name),
2897                s.role
2898            ),
2899            Self::DropUser(n) => write!(f, "DROP USER {}", quote_ident(n)),
2900            Self::ShowUsers => f.write_str("SHOW USERS"),
2901            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
2902            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
2903            Self::CreateSubscription(s) => {
2904                write!(
2905                    f,
2906                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
2907                    quote_ident(&s.name),
2908                    s.conn_str.replace('\'', "''")
2909                )?;
2910                for (i, p) in s.publications.iter().enumerate() {
2911                    if i > 0 {
2912                        f.write_str(", ")?;
2913                    }
2914                    write!(f, "{}", quote_ident(p))?;
2915                }
2916                Ok(())
2917            }
2918            Self::DropSubscription(name) => {
2919                write!(f, "DROP SUBSCRIPTION {}", quote_ident(name))
2920            }
2921            Self::WaitForWalPosition { pos, timeout_ms } => {
2922                write!(f, "WAIT FOR WAL POSITION {pos}")?;
2923                if let Some(ms) = timeout_ms {
2924                    write!(f, " WITH TIMEOUT {ms}")?;
2925                }
2926                Ok(())
2927            }
2928            Self::Analyze(None) => f.write_str("ANALYZE"),
2929            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
2930            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
2931            Self::Explain(e) => {
2932                if e.suggest {
2933                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
2934                } else if e.analyze {
2935                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
2936                } else {
2937                    write!(f, "EXPLAIN {}", e.inner)
2938                }
2939            }
2940            Self::AlterIndex(a) => {
2941                write!(f, "ALTER INDEX ")?;
2942                match &a.target {
2943                    AlterIndexTarget::Rebuild { encoding } => {
2944                        write!(f, "{} REBUILD", quote_ident(&a.name))?;
2945                        if let Some(enc) = encoding {
2946                            write!(f, " WITH (encoding = {enc})")?;
2947                        }
2948                        Ok(())
2949                    }
2950                    AlterIndexTarget::Rename { new, if_exists } => {
2951                        if *if_exists {
2952                            f.write_str("IF EXISTS ")?;
2953                        }
2954                        write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
2955                    }
2956                }
2957            }
2958            Self::AlterTable(a) => {
2959                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
2960                for (i, t) in a.targets.iter().enumerate() {
2961                    if i > 0 {
2962                        f.write_str(", ")?;
2963                    }
2964                    fmt_alter_target(f, t)?;
2965                }
2966                Ok(())
2967            }
2968            Self::CreatePublication(p) => {
2969                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
2970                match &p.scope {
2971                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
2972                    PublicationScope::ForTables(ts) => {
2973                        f.write_str(" FOR TABLE ")?;
2974                        for (i, t) in ts.iter().enumerate() {
2975                            if i > 0 {
2976                                f.write_str(", ")?;
2977                            }
2978                            write!(f, "{}", quote_ident(t))?;
2979                        }
2980                        Ok(())
2981                    }
2982                    PublicationScope::AllTablesExcept(ts) => {
2983                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
2984                        for (i, t) in ts.iter().enumerate() {
2985                            if i > 0 {
2986                                f.write_str(", ")?;
2987                            }
2988                            write!(f, "{}", quote_ident(t))?;
2989                        }
2990                        Ok(())
2991                    }
2992                }
2993            }
2994            Self::CreateExtension(name) => {
2995                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
2996            }
2997            Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
2998            Self::DropPublication(name) => {
2999                write!(f, "DROP PUBLICATION {}", quote_ident(name))
3000            }
3001            Self::SetParameter { name, value } => {
3002                write!(f, "SET {name} = ")?;
3003                match value {
3004                    SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
3005                    SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
3006                    SetValue::Default => f.write_str("DEFAULT"),
3007                }
3008            }
3009            Self::SetTransaction { isolation } => {
3010                write!(f, "SET TRANSACTION ISOLATION LEVEL ")?;
3011                let name = match isolation {
3012                    IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
3013                    IsolationLevel::ReadCommitted => "READ COMMITTED",
3014                    IsolationLevel::RepeatableRead => "REPEATABLE READ",
3015                    IsolationLevel::Serializable => "SERIALIZABLE",
3016                };
3017                f.write_str(name)
3018            }
3019            Self::ShowParameter(name) => write!(f, "SHOW {name}"),
3020            Self::SetParameterList(pairs) => {
3021                f.write_str("SET ")?;
3022                for (i, (name, value)) in pairs.iter().enumerate() {
3023                    if i > 0 {
3024                        f.write_str(", ")?;
3025                    }
3026                    write!(f, "{name} = ")?;
3027                    match value {
3028                        SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
3029                        SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
3030                        SetValue::Default => f.write_str("DEFAULT")?,
3031                    }
3032                }
3033                Ok(())
3034            }
3035            Self::ResetParameter(None) => f.write_str("RESET ALL"),
3036            Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
3037            Self::CreateFunction(s) => s.fmt(f),
3038            Self::CreateTrigger(s) => s.fmt(f),
3039            Self::DropTrigger {
3040                name,
3041                table,
3042                if_exists,
3043            } => {
3044                f.write_str("DROP TRIGGER ")?;
3045                if *if_exists {
3046                    f.write_str("IF EXISTS ")?;
3047                }
3048                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
3049            }
3050            Self::DropFunction { name, if_exists } => {
3051                f.write_str("DROP FUNCTION ")?;
3052                if *if_exists {
3053                    f.write_str("IF EXISTS ")?;
3054                }
3055                write!(f, "{}", quote_ident(name))
3056            }
3057            Self::CreateSequence(s) => s.fmt(f),
3058            Self::AlterSequence(s) => s.fmt(f),
3059            Self::DropSequence { names, if_exists } => {
3060                f.write_str("DROP SEQUENCE ")?;
3061                if *if_exists {
3062                    f.write_str("IF EXISTS ")?;
3063                }
3064                for (i, n) in names.iter().enumerate() {
3065                    if i > 0 {
3066                        f.write_str(", ")?;
3067                    }
3068                    write!(f, "{}", quote_ident(n))?;
3069                }
3070                Ok(())
3071            }
3072            Self::CreateView(v) => v.fmt(f),
3073            Self::DropView { names, if_exists } => {
3074                f.write_str("DROP VIEW ")?;
3075                if *if_exists {
3076                    f.write_str("IF EXISTS ")?;
3077                }
3078                for (i, n) in names.iter().enumerate() {
3079                    if i > 0 {
3080                        f.write_str(", ")?;
3081                    }
3082                    write!(f, "{}", quote_ident(n))?;
3083                }
3084                Ok(())
3085            }
3086            Self::CreateMaterializedView(v) => v.fmt(f),
3087            Self::RefreshMaterializedView { name, with_data } => {
3088                write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
3089                if !*with_data {
3090                    f.write_str(" WITH NO DATA")?;
3091                }
3092                Ok(())
3093            }
3094            Self::DropMaterializedView { names, if_exists } => {
3095                f.write_str("DROP MATERIALIZED VIEW ")?;
3096                if *if_exists {
3097                    f.write_str("IF EXISTS ")?;
3098                }
3099                for (i, n) in names.iter().enumerate() {
3100                    if i > 0 {
3101                        f.write_str(", ")?;
3102                    }
3103                    write!(f, "{}", quote_ident(n))?;
3104                }
3105                Ok(())
3106            }
3107            Self::CreateType(t) => t.fmt(f),
3108            Self::DropType { names, if_exists } => {
3109                f.write_str("DROP TYPE ")?;
3110                if *if_exists {
3111                    f.write_str("IF EXISTS ")?;
3112                }
3113                for (i, n) in names.iter().enumerate() {
3114                    if i > 0 {
3115                        f.write_str(", ")?;
3116                    }
3117                    write!(f, "{}", quote_ident(n))?;
3118                }
3119                Ok(())
3120            }
3121            Self::CreateDomain(d) => d.fmt(f),
3122            Self::DropDomain { names, if_exists } => {
3123                f.write_str("DROP DOMAIN ")?;
3124                if *if_exists {
3125                    f.write_str("IF EXISTS ")?;
3126                }
3127                for (i, n) in names.iter().enumerate() {
3128                    if i > 0 {
3129                        f.write_str(", ")?;
3130                    }
3131                    write!(f, "{}", quote_ident(n))?;
3132                }
3133                Ok(())
3134            }
3135            Self::CreateSchema {
3136                name,
3137                if_not_exists,
3138            } => {
3139                f.write_str("CREATE SCHEMA ")?;
3140                if *if_not_exists {
3141                    f.write_str("IF NOT EXISTS ")?;
3142                }
3143                write!(f, "{}", quote_ident(name))
3144            }
3145            Self::DropSchema { names, if_exists } => {
3146                f.write_str("DROP SCHEMA ")?;
3147                if *if_exists {
3148                    f.write_str("IF EXISTS ")?;
3149                }
3150                for (i, n) in names.iter().enumerate() {
3151                    if i > 0 {
3152                        f.write_str(", ")?;
3153                    }
3154                    write!(f, "{}", quote_ident(n))?;
3155                }
3156                Ok(())
3157            }
3158        }
3159    }
3160}
3161
3162impl fmt::Display for CreateDomainStatement {
3163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3164        write!(
3165            f,
3166            "CREATE DOMAIN {} AS {}",
3167            quote_ident(&self.name),
3168            self.base_type
3169        )?;
3170        if let Some(d) = &self.default {
3171            write!(f, " DEFAULT {d}")?;
3172        }
3173        if self.not_null {
3174            f.write_str(" NOT NULL")?;
3175        }
3176        for c in &self.checks {
3177            write!(f, " CHECK ({c})")?;
3178        }
3179        Ok(())
3180    }
3181}
3182
3183impl fmt::Display for CreateTypeStatement {
3184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3185        write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
3186        match &self.kind {
3187            TypeKind::Enum { labels } => {
3188                f.write_str("ENUM (")?;
3189                for (i, l) in labels.iter().enumerate() {
3190                    if i > 0 {
3191                        f.write_str(", ")?;
3192                    }
3193                    write!(f, "'{}'", l.replace('\'', "''"))?;
3194                }
3195                f.write_str(")")
3196            }
3197            TypeKind::Composite { fields } => {
3198                f.write_str("(")?;
3199                for (i, (n, t)) in fields.iter().enumerate() {
3200                    if i > 0 {
3201                        f.write_str(", ")?;
3202                    }
3203                    write!(f, "{} {}", quote_ident(n), t)?;
3204                }
3205                f.write_str(")")
3206            }
3207        }
3208    }
3209}
3210
3211impl fmt::Display for CreateMaterializedViewStatement {
3212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3213        f.write_str("CREATE MATERIALIZED VIEW ")?;
3214        if self.if_not_exists {
3215            f.write_str("IF NOT EXISTS ")?;
3216        }
3217        write!(f, "{}", quote_ident(&self.name))?;
3218        if !self.columns.is_empty() {
3219            f.write_str(" (")?;
3220            for (i, c) in self.columns.iter().enumerate() {
3221                if i > 0 {
3222                    f.write_str(", ")?;
3223                }
3224                write!(f, "{}", quote_ident(c))?;
3225            }
3226            f.write_str(")")?;
3227        }
3228        write!(f, " AS {}", self.body)?;
3229        if !self.with_data {
3230            f.write_str(" WITH NO DATA")?;
3231        }
3232        Ok(())
3233    }
3234}
3235
3236impl fmt::Display for CreateViewStatement {
3237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3238        f.write_str("CREATE ")?;
3239        if self.or_replace {
3240            f.write_str("OR REPLACE ")?;
3241        }
3242        if self.temporary {
3243            f.write_str("TEMPORARY ")?;
3244        }
3245        f.write_str("VIEW ")?;
3246        if self.if_not_exists {
3247            f.write_str("IF NOT EXISTS ")?;
3248        }
3249        write!(f, "{}", quote_ident(&self.name))?;
3250        if !self.columns.is_empty() {
3251            f.write_str(" (")?;
3252            for (i, c) in self.columns.iter().enumerate() {
3253                if i > 0 {
3254                    f.write_str(", ")?;
3255                }
3256                write!(f, "{}", quote_ident(c))?;
3257            }
3258            f.write_str(")")?;
3259        }
3260        write!(f, " AS {}", self.body)
3261    }
3262}
3263
3264impl fmt::Display for CreateSequenceStatement {
3265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3266        f.write_str("CREATE ")?;
3267        if self.temporary {
3268            f.write_str("TEMPORARY ")?;
3269        }
3270        f.write_str("SEQUENCE ")?;
3271        if self.if_not_exists {
3272            f.write_str("IF NOT EXISTS ")?;
3273        }
3274        write!(f, "{}", quote_ident(&self.name))?;
3275        if let Some(dt) = self.data_type {
3276            write!(f, " AS {dt}")?;
3277        }
3278        write_sequence_options(f, &self.options)
3279    }
3280}
3281
3282impl fmt::Display for AlterSequenceStatement {
3283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3284        f.write_str("ALTER SEQUENCE ")?;
3285        if self.if_exists {
3286            f.write_str("IF EXISTS ")?;
3287        }
3288        write!(f, "{}", quote_ident(&self.name))?;
3289        write_sequence_options(f, &self.options)
3290    }
3291}
3292
3293impl fmt::Display for SequenceDataType {
3294    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3295        f.write_str(match self {
3296            Self::SmallInt => "smallint",
3297            Self::Int => "integer",
3298            Self::BigInt => "bigint",
3299        })
3300    }
3301}
3302
3303fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
3304    if let Some(n) = o.increment {
3305        write!(f, " INCREMENT BY {n}")?;
3306    }
3307    match o.min_value {
3308        Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
3309        Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
3310        None => {}
3311    }
3312    match o.max_value {
3313        Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
3314        Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
3315        None => {}
3316    }
3317    if let Some(n) = o.start {
3318        write!(f, " START WITH {n}")?;
3319    }
3320    match o.restart {
3321        Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
3322        Some(None) => f.write_str(" RESTART")?,
3323        None => {}
3324    }
3325    if let Some(n) = o.cache {
3326        write!(f, " CACHE {n}")?;
3327    }
3328    match o.cycle {
3329        Some(true) => f.write_str(" CYCLE")?,
3330        Some(false) => f.write_str(" NO CYCLE")?,
3331        None => {}
3332    }
3333    if let Some(ob) = &o.owned_by {
3334        match ob {
3335            SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
3336            SequenceOwnedBy::Column { table, column } => {
3337                write!(
3338                    f,
3339                    " OWNED BY {}.{}",
3340                    quote_ident(table),
3341                    quote_ident(column)
3342                )?;
3343            }
3344        }
3345    }
3346    Ok(())
3347}
3348
3349impl fmt::Display for CreateFunctionStatement {
3350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3351        f.write_str("CREATE ")?;
3352        if self.or_replace {
3353            f.write_str("OR REPLACE ")?;
3354        }
3355        write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
3356        for (i, arg) in self.args.iter().enumerate() {
3357            if i > 0 {
3358                f.write_str(", ")?;
3359            }
3360            match arg.mode {
3361                FunctionArgMode::In => {}
3362                FunctionArgMode::Out => f.write_str("OUT ")?,
3363                FunctionArgMode::InOut => f.write_str("INOUT ")?,
3364            }
3365            if let Some(name) = &arg.name {
3366                write!(f, "{} ", quote_ident(name))?;
3367            }
3368            match &arg.ty {
3369                FunctionArgType::Typed(t) => write!(f, "{t}")?,
3370                FunctionArgType::Raw(s) => f.write_str(s)?,
3371            }
3372        }
3373        f.write_str(") RETURNS ")?;
3374        match &self.returns {
3375            FunctionReturn::Trigger => f.write_str("TRIGGER")?,
3376            FunctionReturn::Void => f.write_str("VOID")?,
3377            FunctionReturn::Type(t) => write!(f, "{t}")?,
3378            FunctionReturn::Other(s) => f.write_str(s)?,
3379        }
3380        write!(f, " LANGUAGE {} AS $$", self.language)?;
3381        match &self.body {
3382            FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
3383            FunctionBody::Raw(s) => f.write_str(s)?,
3384        }
3385        f.write_str("$$")
3386    }
3387}
3388
3389impl fmt::Display for PlPgSqlBlock {
3390    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3391        if !self.declarations.is_empty() {
3392            f.write_str("DECLARE\n")?;
3393            for d in &self.declarations {
3394                write!(f, "  {} ", quote_ident(&d.name))?;
3395                match &d.ty {
3396                    FunctionArgType::Typed(t) => write!(f, "{t}")?,
3397                    FunctionArgType::Raw(s) => f.write_str(s)?,
3398                }
3399                if let Some(e) = &d.default {
3400                    write!(f, " := {e}")?;
3401                }
3402                f.write_str(";\n")?;
3403            }
3404        }
3405        f.write_str("BEGIN\n")?;
3406        for stmt in &self.statements {
3407            writeln!(f, "  {stmt};")?;
3408        }
3409        f.write_str("END")
3410    }
3411}
3412
3413impl fmt::Display for PlPgSqlStmt {
3414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3415        match self {
3416            Self::Assign { target, value } => write!(f, "{target} := {value}"),
3417            Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
3418            Self::Return(t) => match t {
3419                ReturnTarget::New => f.write_str("RETURN NEW"),
3420                ReturnTarget::Old => f.write_str("RETURN OLD"),
3421                ReturnTarget::Null => f.write_str("RETURN NULL"),
3422                ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
3423            },
3424            Self::If {
3425                branches,
3426                else_branch,
3427            } => {
3428                for (i, (cond, body)) in branches.iter().enumerate() {
3429                    if i == 0 {
3430                        write!(f, "IF {cond} THEN ")?;
3431                    } else {
3432                        write!(f, " ELSIF {cond} THEN ")?;
3433                    }
3434                    for (j, s) in body.iter().enumerate() {
3435                        if j > 0 {
3436                            f.write_str("; ")?;
3437                        }
3438                        write!(f, "{s}")?;
3439                    }
3440                }
3441                if !else_branch.is_empty() {
3442                    f.write_str(" ELSE ")?;
3443                    for (j, s) in else_branch.iter().enumerate() {
3444                        if j > 0 {
3445                            f.write_str("; ")?;
3446                        }
3447                        write!(f, "{s}")?;
3448                    }
3449                }
3450                f.write_str(" END IF")
3451            }
3452            Self::Raise {
3453                level,
3454                message,
3455                args,
3456            } => {
3457                let lvl = match level {
3458                    RaiseLevel::Notice => "NOTICE",
3459                    RaiseLevel::Warning => "WARNING",
3460                    RaiseLevel::Info => "INFO",
3461                    RaiseLevel::Log => "LOG",
3462                    RaiseLevel::Debug => "DEBUG",
3463                    RaiseLevel::Exception => "EXCEPTION",
3464                };
3465                write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
3466                for a in args {
3467                    write!(f, ", {a}")?;
3468                }
3469                Ok(())
3470            }
3471            Self::EmbeddedSql(s) => write!(f, "{s}"),
3472        }
3473    }
3474}
3475
3476impl fmt::Display for AssignTarget {
3477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3478        match self {
3479            Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
3480            Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
3481            Self::Local(n) => f.write_str(n),
3482        }
3483    }
3484}
3485
3486impl fmt::Display for CreateTriggerStatement {
3487    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3488        f.write_str("CREATE ")?;
3489        if self.or_replace {
3490            f.write_str("OR REPLACE ")?;
3491        }
3492        write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
3493        match self.timing {
3494            TriggerTiming::Before => f.write_str("BEFORE")?,
3495            TriggerTiming::After => f.write_str("AFTER")?,
3496            TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
3497        }
3498        for (i, e) in self.events.iter().enumerate() {
3499            if i == 0 {
3500                f.write_str(" ")?;
3501            } else {
3502                f.write_str(" OR ")?;
3503            }
3504            match e {
3505                TriggerEvent::Insert => f.write_str("INSERT")?,
3506                TriggerEvent::Update => {
3507                    f.write_str("UPDATE")?;
3508                    if !self.update_columns.is_empty() {
3509                        f.write_str(" OF ")?;
3510                        for (j, col) in self.update_columns.iter().enumerate() {
3511                            if j > 0 {
3512                                f.write_str(", ")?;
3513                            }
3514                            f.write_str(&quote_ident(col))?;
3515                        }
3516                    }
3517                }
3518                TriggerEvent::Delete => f.write_str("DELETE")?,
3519                TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
3520            }
3521        }
3522        write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
3523        match self.for_each {
3524            TriggerForEach::Row => f.write_str("ROW")?,
3525            TriggerForEach::Statement => f.write_str("STATEMENT")?,
3526        }
3527        write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
3528    }
3529}
3530
3531impl fmt::Display for CreateIndexStatement {
3532    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3533        if self.is_unique {
3534            f.write_str("CREATE UNIQUE INDEX ")?;
3535        } else {
3536            f.write_str("CREATE INDEX ")?;
3537        }
3538        if self.if_not_exists {
3539            f.write_str("IF NOT EXISTS ")?;
3540        }
3541        write!(
3542            f,
3543            "{} ON {} ",
3544            quote_ident(&self.name),
3545            quote_ident(&self.table)
3546        )?;
3547        match self.method {
3548            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
3549            IndexMethod::Brin => f.write_str("USING brin ")?,
3550            IndexMethod::Gin => f.write_str("USING gin ")?,
3551            IndexMethod::BTree => {}
3552        }
3553        if let Some(expr) = &self.expression {
3554            write!(f, "({})", expr)?;
3555        } else if self.extra_columns.is_empty() {
3556            // v7.15.0 — preserve operator class on round-trip
3557            // (`(col opclass)`) so WAL replay reconstructs the
3558            // engine-routing intent (e.g. `gin_trgm_ops` →
3559            // trigram-GIN build path).
3560            if let Some(op) = &self.opclass {
3561                write!(f, "({} {})", quote_ident(&self.column), op)?;
3562            } else {
3563                write!(f, "({})", quote_ident(&self.column))?;
3564            }
3565        } else {
3566            // v7.9.14 — multi-column key. Emit each column quoted
3567            // so the round-tripped form re-parses to identical AST.
3568            f.write_str("(")?;
3569            write!(f, "{}", quote_ident(&self.column))?;
3570            for c in &self.extra_columns {
3571                write!(f, ", {}", quote_ident(c))?;
3572            }
3573            f.write_str(")")?;
3574        }
3575        if !self.included_columns.is_empty() {
3576            f.write_str(" INCLUDE (")?;
3577            for (i, c) in self.included_columns.iter().enumerate() {
3578                if i > 0 {
3579                    f.write_str(", ")?;
3580                }
3581                write!(f, "{}", quote_ident(c))?;
3582            }
3583            f.write_str(")")?;
3584        }
3585        if let Some(pred) = &self.partial_predicate {
3586            write!(f, " WHERE {}", pred)?;
3587        }
3588        Ok(())
3589    }
3590}
3591
3592impl fmt::Display for CreateTableStatement {
3593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3594        f.write_str("CREATE TABLE ")?;
3595        if self.if_not_exists {
3596            f.write_str("IF NOT EXISTS ")?;
3597        }
3598        write!(f, "{}", quote_ident(&self.name))?;
3599        // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
3600        // no column list and no constraints; the table inherits its
3601        // columns from the parent at engine-DDL time.
3602        if let Some(spec) = &self.partition_of {
3603            write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
3604            return match &spec.bounds {
3605                PartitionOfBoundsAst::Range { lower, upper } => {
3606                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
3607                }
3608                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
3609            };
3610        }
3611        f.write_str(" (")?;
3612        for (i, col) in self.columns.iter().enumerate() {
3613            if i > 0 {
3614                f.write_str(", ")?;
3615            }
3616            write!(f, "{col}")?;
3617        }
3618        // v7.6.0 — render FK constraints in table-level form, after
3619        // the column list. WAL replay round-trips through Display, so
3620        // every FK must serialise here for replay to reconstruct the
3621        // schema bit-for-bit.
3622        for fk in &self.foreign_keys {
3623            f.write_str(", ")?;
3624            write!(f, "{fk}")?;
3625        }
3626        // v7.13.0 — render table-level constraints (PRIMARY KEY /
3627        // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
3628        // column-level UNIQUE / CHECK get lifted to this list at
3629        // parse time, so emitting only here avoids double-counting.
3630        for tc in &self.table_constraints {
3631            f.write_str(", ")?;
3632            write!(f, "{tc}")?;
3633        }
3634        f.write_str(")")?;
3635        // v7.37.6-B — partition-parent suffix renders after the
3636        // closing column-list paren, before the optional MySQL
3637        // table-options tail (which Display doesn't currently emit).
3638        if let Some(spec) = &self.partition_by {
3639            f.write_str(" PARTITION BY ")?;
3640            match spec.kind {
3641                PartitionKindAst::Range => f.write_str("RANGE ")?,
3642            }
3643            f.write_str("(")?;
3644            for (i, col) in spec.key_columns.iter().enumerate() {
3645                if i > 0 {
3646                    f.write_str(", ")?;
3647                }
3648                f.write_str(&quote_ident(col))?;
3649            }
3650            f.write_str(")")?;
3651        }
3652        Ok(())
3653    }
3654}
3655
3656fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
3657    match t {
3658        AlterTableTarget::SetHotTierBytes(n) => {
3659            write!(f, "SET hot_tier_bytes = {n}")
3660        }
3661        AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
3662        AlterTableTarget::DropForeignKey { name, if_exists } => {
3663            f.write_str("DROP CONSTRAINT ")?;
3664            if *if_exists {
3665                f.write_str("IF EXISTS ")?;
3666            }
3667            write!(f, "{}", quote_ident(name))
3668        }
3669        AlterTableTarget::AddColumn {
3670            column,
3671            if_not_exists,
3672        } => {
3673            f.write_str("ADD COLUMN ")?;
3674            if *if_not_exists {
3675                f.write_str("IF NOT EXISTS ")?;
3676            }
3677            write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
3678            if !column.nullable {
3679                f.write_str(" NOT NULL")?;
3680            }
3681            if let Some(d) = &column.default {
3682                write!(f, " DEFAULT {d}")?;
3683            }
3684            if column.auto_increment {
3685                f.write_str(" AUTO_INCREMENT")?;
3686            }
3687            if column.is_primary_key {
3688                f.write_str(" PRIMARY KEY")?;
3689            }
3690            Ok(())
3691        }
3692        AlterTableTarget::AlterColumnType {
3693            column,
3694            new_type,
3695            using,
3696        } => {
3697            write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
3698            if let Some(u) = using {
3699                write!(f, " USING {u}")?;
3700            }
3701            Ok(())
3702        }
3703        AlterTableTarget::DropColumn {
3704            column,
3705            if_exists,
3706            cascade,
3707        } => {
3708            f.write_str("DROP COLUMN ")?;
3709            if *if_exists {
3710                f.write_str("IF EXISTS ")?;
3711            }
3712            write!(f, "{}", quote_ident(column))?;
3713            if *cascade {
3714                f.write_str(" CASCADE")?;
3715            }
3716            Ok(())
3717        }
3718        AlterTableTarget::AddTableConstraint(tc) => {
3719            write!(f, "ADD {tc}")
3720        }
3721        AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
3722            // Round-trip-safe spelling: re-parsing this form lowers
3723            // back to SetColumnAutoIncrement (the nextval default is
3724            // how pg_dump says "serial").
3725            let seq = seq_name
3726                .clone()
3727                .unwrap_or_else(|| alloc::format!("{column}_seq"));
3728            write!(
3729                f,
3730                "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
3731                quote_ident(column)
3732            )
3733        }
3734        AlterTableTarget::RenameColumn { old, new } => {
3735            write!(
3736                f,
3737                "RENAME COLUMN {} TO {}",
3738                quote_ident(old),
3739                quote_ident(new)
3740            )
3741        }
3742        AlterTableTarget::RenameTable { new } => {
3743            write!(f, "RENAME TO {}", quote_ident(new))
3744        }
3745        AlterTableTarget::SetTriggerEnabled { which, enabled } => {
3746            f.write_str(if *enabled {
3747                "ENABLE TRIGGER "
3748            } else {
3749                "DISABLE TRIGGER "
3750            })?;
3751            match which {
3752                TriggerSelector::All => f.write_str("ALL"),
3753                TriggerSelector::Named(n) => f.write_str(&quote_ident(n)),
3754            }
3755        }
3756    }
3757}
3758
3759impl fmt::Display for TableConstraint {
3760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3761        match self {
3762            Self::PrimaryKey { name, columns } => {
3763                if let Some(n) = name {
3764                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
3765                }
3766                f.write_str("PRIMARY KEY (")?;
3767                for (i, c) in columns.iter().enumerate() {
3768                    if i > 0 {
3769                        f.write_str(", ")?;
3770                    }
3771                    f.write_str(&quote_ident(c))?;
3772                }
3773                f.write_str(")")
3774            }
3775            Self::Unique {
3776                name,
3777                columns,
3778                nulls_not_distinct,
3779            } => {
3780                if let Some(n) = name {
3781                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
3782                }
3783                f.write_str("UNIQUE ")?;
3784                if *nulls_not_distinct {
3785                    f.write_str("NULLS NOT DISTINCT ")?;
3786                }
3787                f.write_str("(")?;
3788                for (i, c) in columns.iter().enumerate() {
3789                    if i > 0 {
3790                        f.write_str(", ")?;
3791                    }
3792                    f.write_str(&quote_ident(c))?;
3793                }
3794                f.write_str(")")
3795            }
3796            Self::Check { name, expr } => {
3797                if let Some(n) = name {
3798                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
3799                }
3800                write!(f, "CHECK ({expr})")
3801            }
3802            Self::Index { name, columns } => {
3803                f.write_str("KEY ")?;
3804                if let Some(n) = name {
3805                    write!(f, "{} ", quote_ident(n))?;
3806                }
3807                f.write_str("(")?;
3808                for (i, c) in columns.iter().enumerate() {
3809                    if i > 0 {
3810                        f.write_str(", ")?;
3811                    }
3812                    f.write_str(&quote_ident(c))?;
3813                }
3814                f.write_str(")")
3815            }
3816            Self::FulltextIndex { name, columns } => {
3817                // Mysqldump emits `FULLTEXT KEY name (cols)` —
3818                // Display rounds back to that shape so dump
3819                // replay reproduces the input verbatim.
3820                f.write_str("FULLTEXT KEY ")?;
3821                if let Some(n) = name {
3822                    write!(f, "{} ", quote_ident(n))?;
3823                }
3824                f.write_str("(")?;
3825                for (i, c) in columns.iter().enumerate() {
3826                    if i > 0 {
3827                        f.write_str(", ")?;
3828                    }
3829                    f.write_str(&quote_ident(c))?;
3830                }
3831                f.write_str(")")
3832            }
3833        }
3834    }
3835}
3836
3837impl fmt::Display for ForeignKeyConstraint {
3838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3839        if let Some(name) = &self.name {
3840            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
3841        }
3842        f.write_str("FOREIGN KEY (")?;
3843        for (i, c) in self.columns.iter().enumerate() {
3844            if i > 0 {
3845                f.write_str(", ")?;
3846            }
3847            f.write_str(&quote_ident(c))?;
3848        }
3849        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
3850        if !self.parent_columns.is_empty() {
3851            f.write_str(" (")?;
3852            for (i, c) in self.parent_columns.iter().enumerate() {
3853                if i > 0 {
3854                    f.write_str(", ")?;
3855                }
3856                f.write_str(&quote_ident(c))?;
3857            }
3858            f.write_str(")")?;
3859        }
3860        // Only render non-default actions to keep Display output
3861        // close to user input. SPG's default is RESTRICT (matches
3862        // SQL spec).
3863        if self.on_delete != FkAction::Restrict {
3864            write!(f, " ON DELETE {}", self.on_delete)?;
3865        }
3866        if self.on_update != FkAction::Restrict {
3867            write!(f, " ON UPDATE {}", self.on_update)?;
3868        }
3869        Ok(())
3870    }
3871}
3872
3873impl fmt::Display for FkAction {
3874    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3875        match self {
3876            Self::Restrict => f.write_str("RESTRICT"),
3877            Self::Cascade => f.write_str("CASCADE"),
3878            Self::SetNull => f.write_str("SET NULL"),
3879            Self::SetDefault => f.write_str("SET DEFAULT"),
3880            Self::NoAction => f.write_str("NO ACTION"),
3881        }
3882    }
3883}
3884
3885impl fmt::Display for ColumnDef {
3886    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3887        // v7.30.1 (mailrs round-24 class audit) — the type position
3888        // must re-parse to the same ColumnDef: a user-defined type
3889        // reference and the MySQL inline ENUM / SET value lists all
3890        // lower `ty` to Text, so rendering `ty` lost them.
3891        write!(f, "{}", quote_ident(&self.name))?;
3892        if let Some(ut) = &self.user_type_ref {
3893            write!(f, " {}", quote_ident(ut))?;
3894        } else if let Some(variants) = &self.inline_enum_variants {
3895            write_variant_list(f, "ENUM", variants)?;
3896        } else if let Some(variants) = &self.inline_set_variants {
3897            write_variant_list(f, "SET", variants)?;
3898        } else {
3899            write!(f, " {}", self.ty)?;
3900        }
3901        if self.is_unsigned {
3902            f.write_str(" UNSIGNED")?;
3903        }
3904        // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
3905        // DDL. Only emits when non-default so the typical output
3906        // stays unchanged.
3907        match self.collation {
3908            Collation::Binary => {}
3909            Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
3910        }
3911        if let Some(d) = &self.default {
3912            write!(f, " DEFAULT {d}")?;
3913        }
3914        if self.auto_increment {
3915            f.write_str(" AUTO_INCREMENT")?;
3916        }
3917        if !self.nullable {
3918            f.write_str(" NOT NULL")?;
3919        }
3920        // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
3921        // is NOT lifted to a table-level constraint at parse time
3922        // (unlike UNIQUE / CHECK), so the WAL round trip of a
3923        // prepared CREATE TABLE silently dropped the primary key.
3924        if self.is_primary_key {
3925            f.write_str(" PRIMARY KEY")?;
3926        }
3927        // The parser accepts only CURRENT_TIMESTAMP here (stored as
3928        // now()), so that spelling is the lossless round trip.
3929        if self.on_update_runtime.is_some() {
3930            f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
3931        }
3932        // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
3933        // replay reconstructs the computed-column declaration. The
3934        // expression sits inside a single set of parens; STORED is
3935        // the only variant the parser accepts.
3936        if let Some(gen_expr) = &self.generated_stored_expr {
3937            write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
3938        }
3939        Ok(())
3940    }
3941}
3942
3943/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
3944/// types (MySQL flavour; `ty` is Text underneath).
3945fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
3946    write!(f, " {kw}(")?;
3947    for (i, v) in variants.iter().enumerate() {
3948        if i > 0 {
3949            f.write_str(", ")?;
3950        }
3951        write!(f, "'{}'", v.replace('\'', "''"))?;
3952    }
3953    f.write_str(")")
3954}
3955
3956impl fmt::Display for InsertStatement {
3957    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3958        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
3959        if let Some(cols) = &self.columns {
3960            f.write_str(" (")?;
3961            for (i, c) in cols.iter().enumerate() {
3962                if i > 0 {
3963                    f.write_str(", ")?;
3964                }
3965                f.write_str(&quote_ident(c))?;
3966            }
3967            f.write_str(")")?;
3968        }
3969        // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
3970        // skipping the VALUES list (mailrs round-5 G4).
3971        if let Some(sel) = &self.select_source {
3972            write!(f, " {sel}")?;
3973        } else {
3974            f.write_str(" VALUES ")?;
3975            for (ri, row) in self.rows.iter().enumerate() {
3976                if ri > 0 {
3977                    f.write_str(", ")?;
3978                }
3979                f.write_str("(")?;
3980                for (i, v) in row.iter().enumerate() {
3981                    if i > 0 {
3982                        f.write_str(", ")?;
3983                    }
3984                    write!(f, "{v}")?;
3985                }
3986                f.write_str(")")?;
3987            }
3988        }
3989        // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
3990        // Display round trip: WAL persistence renders the bind-final
3991        // AST through this impl, and a replayed bare INSERT turns a
3992        // legal upsert no-op into a UNIQUE violation that refuses to
3993        // open the catalog.
3994        if let Some(oc) = &self.on_conflict {
3995            write!(f, " {oc}")?;
3996        }
3997        write_returning(self.returning.as_deref(), f)?;
3998        Ok(())
3999    }
4000}
4001
4002/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
4003/// parser produced, so the AST→SQL round trip preserves upsert
4004/// semantics (WAL replay depends on it).
4005impl fmt::Display for OnConflictClause {
4006    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4007        f.write_str("ON CONFLICT")?;
4008        if !self.target_columns.is_empty() {
4009            f.write_str(" (")?;
4010            for (i, c) in self.target_columns.iter().enumerate() {
4011                if i > 0 {
4012                    f.write_str(", ")?;
4013                }
4014                f.write_str(&quote_ident(c))?;
4015            }
4016            f.write_str(")")?;
4017        }
4018        match &self.action {
4019            OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
4020            OnConflictAction::Update {
4021                assignments,
4022                where_,
4023            } => {
4024                f.write_str(" DO UPDATE SET ")?;
4025                for (i, (col, expr)) in assignments.iter().enumerate() {
4026                    if i > 0 {
4027                        f.write_str(", ")?;
4028                    }
4029                    write!(f, "{} = {expr}", quote_ident(col))?;
4030                }
4031                if let Some(w) = where_ {
4032                    write!(f, " WHERE {w}")?;
4033                }
4034                Ok(())
4035            }
4036        }
4037    }
4038}
4039
4040/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
4041/// tail for the three DML Display impls.
4042fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4043    let Some(items) = ret else {
4044        return Ok(());
4045    };
4046    f.write_str(" RETURNING ")?;
4047    for (i, item) in items.iter().enumerate() {
4048        if i > 0 {
4049            f.write_str(", ")?;
4050        }
4051        write!(f, "{item}")?;
4052    }
4053    Ok(())
4054}
4055
4056impl fmt::Display for UpdateStatement {
4057    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4058        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
4059        for (i, (col, expr)) in self.assignments.iter().enumerate() {
4060            if i > 0 {
4061                f.write_str(", ")?;
4062            }
4063            write!(f, "{} = {expr}", quote_ident(col))?;
4064        }
4065        if let Some(w) = &self.where_ {
4066            write!(f, " WHERE {w}")?;
4067        }
4068        write_returning(self.returning.as_deref(), f)?;
4069        Ok(())
4070    }
4071}
4072
4073impl fmt::Display for DeleteStatement {
4074    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4075        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
4076        if let Some(w) = &self.where_ {
4077            write!(f, " WHERE {w}")?;
4078        }
4079        write_returning(self.returning.as_deref(), f)?;
4080        Ok(())
4081    }
4082}
4083
4084impl fmt::Display for CteBody {
4085    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4086        match self {
4087            Self::Select(s) => write!(f, "{s}"),
4088            Self::Insert(s) => write!(f, "{s}"),
4089            Self::Update(s) => write!(f, "{s}"),
4090            Self::Delete(s) => write!(f, "{s}"),
4091        }
4092    }
4093}
4094
4095impl fmt::Display for SelectStatement {
4096    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4097        // v7.30.1 (mailrs round-24 class audit) — the WITH clause
4098        // must survive the round trip; a CTE-using statement
4099        // re-parsed without it references undefined tables.
4100        if !self.ctes.is_empty() {
4101            f.write_str("WITH ")?;
4102            if self.ctes.iter().any(|c| c.recursive) {
4103                f.write_str("RECURSIVE ")?;
4104            }
4105            for (i, cte) in self.ctes.iter().enumerate() {
4106                if i > 0 {
4107                    f.write_str(", ")?;
4108                }
4109                f.write_str(&quote_ident(&cte.name))?;
4110                if !cte.column_overrides.is_empty() {
4111                    f.write_str(" (")?;
4112                    for (ci, c) in cte.column_overrides.iter().enumerate() {
4113                        if ci > 0 {
4114                            f.write_str(", ")?;
4115                        }
4116                        f.write_str(&quote_ident(c))?;
4117                    }
4118                    f.write_str(")")?;
4119                }
4120                write!(f, " AS ({})", cte.body)?;
4121            }
4122            f.write_str(" ")?;
4123        }
4124        write_bare_select(self, f)?;
4125        for (kind, peer) in &self.unions {
4126            f.write_str(match kind {
4127                UnionKind::Distinct => " UNION ",
4128                UnionKind::All => " UNION ALL ",
4129            })?;
4130            write_bare_select(peer, f)?;
4131        }
4132        if !self.order_by.is_empty() {
4133            f.write_str(" ORDER BY ")?;
4134            for (i, o) in self.order_by.iter().enumerate() {
4135                if i > 0 {
4136                    f.write_str(", ")?;
4137                }
4138                write!(f, "{}", o.expr)?;
4139                if o.desc {
4140                    f.write_str(" DESC")?;
4141                }
4142                match o.nulls_first {
4143                    Some(true) => f.write_str(" NULLS FIRST")?,
4144                    Some(false) => f.write_str(" NULLS LAST")?,
4145                    None => {}
4146                }
4147            }
4148        }
4149        // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
4150        // exists in the FETCH FIRST spelling; rendering it as LIMIT
4151        // dropped the tie-extension semantics on replay. The parser
4152        // accepts OFFSET before FETCH, so keep that order here.
4153        if self.limit_with_ties {
4154            if let Some(o) = &self.offset {
4155                write!(f, " OFFSET {o}")?;
4156            }
4157            if let Some(n) = &self.limit {
4158                write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
4159            }
4160        } else {
4161            if let Some(n) = &self.limit {
4162                write!(f, " LIMIT {n}")?;
4163            }
4164            if let Some(o) = &self.offset {
4165                write!(f, " OFFSET {o}")?;
4166            }
4167        }
4168        Ok(())
4169    }
4170}
4171
4172fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4173    f.write_str("SELECT ")?;
4174    if s.distinct {
4175        f.write_str("DISTINCT ")?;
4176    }
4177    write_bare_select_body(s, f)
4178}
4179
4180fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4181    for (i, item) in s.items.iter().enumerate() {
4182        if i > 0 {
4183            f.write_str(", ")?;
4184        }
4185        write!(f, "{item}")?;
4186    }
4187    if let Some(t) = &s.from {
4188        write!(f, " FROM {t}")?;
4189    }
4190    if let Some(e) = &s.where_ {
4191        write!(f, " WHERE {e}")?;
4192    }
4193    if let Some(gs) = &s.group_by {
4194        f.write_str(" GROUP BY ")?;
4195        for (i, g) in gs.iter().enumerate() {
4196            if i > 0 {
4197                f.write_str(", ")?;
4198            }
4199            write!(f, "{g}")?;
4200        }
4201    } else if s.group_by_all {
4202        // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
4203        // shortcut parses to group_by: None + this flag; dropping
4204        // it turned an aggregate query into a bare projection on
4205        // re-parse.
4206        f.write_str(" GROUP BY ALL")?;
4207    }
4208    if let Some(h) = &s.having {
4209        write!(f, " HAVING {h}")?;
4210    }
4211    Ok(())
4212}
4213
4214impl fmt::Display for SelectItem {
4215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4216        match self {
4217            Self::Wildcard => f.write_str("*"),
4218            Self::Expr { expr, alias } => {
4219                write!(f, "{expr}")?;
4220                if let Some(a) = alias {
4221                    write!(f, " AS {}", quote_ident(a))?;
4222                }
4223                Ok(())
4224            }
4225        }
4226    }
4227}
4228
4229impl fmt::Display for FromClause {
4230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4231        write!(f, "{}", self.primary)?;
4232        for j in &self.joins {
4233            match j.kind {
4234                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
4235                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
4236                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
4237            }
4238            if let Some(on) = &j.on {
4239                write!(f, " ON {on}")?;
4240            }
4241        }
4242        Ok(())
4243    }
4244}
4245
4246impl fmt::Display for TableRef {
4247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4248        // v7.30.1 (mailrs round-24 class audit) — the dynamic
4249        // table-ref shapes must round-trip: rendering only the
4250        // (synthetic) name turned LATERAL / unnest() /
4251        // generate_series() into references to nonexistent tables
4252        // on re-parse.
4253        if let Some(inner) = &self.lateral_subquery {
4254            write!(f, "LATERAL ({inner})")?;
4255            if let Some(a) = &self.alias {
4256                write!(f, " AS {}", quote_ident(a))?;
4257            }
4258            return Ok(());
4259        }
4260        if let Some(expr) = &self.unnest_expr {
4261            write!(f, "UNNEST({expr})")?;
4262            if let Some(a) = &self.alias {
4263                write!(f, " AS {}", quote_ident(a))?;
4264                if !self.unnest_column_aliases.is_empty() {
4265                    f.write_str(" (")?;
4266                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
4267                        if i > 0 {
4268                            f.write_str(", ")?;
4269                        }
4270                        f.write_str(&quote_ident(c))?;
4271                    }
4272                    f.write_str(")")?;
4273                }
4274            }
4275            return Ok(());
4276        }
4277        if let Some(args) = &self.generate_series_args {
4278            f.write_str("generate_series(")?;
4279            for (i, a) in args.iter().enumerate() {
4280                if i > 0 {
4281                    f.write_str(", ")?;
4282                }
4283                write!(f, "{a}")?;
4284            }
4285            f.write_str(")")?;
4286            if let Some(a) = &self.alias {
4287                write!(f, " AS {}", quote_ident(a))?;
4288            }
4289            return Ok(());
4290        }
4291        write!(f, "{}", quote_ident(&self.name))?;
4292        if let Some(seg) = self.as_of_segment {
4293            write!(f, " AS OF SEGMENT {seg}")?;
4294        }
4295        if let Some(a) = &self.alias {
4296            write!(f, " AS {}", quote_ident(a))?;
4297        }
4298        Ok(())
4299    }
4300}
4301
4302impl fmt::Display for ColumnName {
4303    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4304        if let Some(q) = &self.qualifier {
4305            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
4306        } else {
4307            write!(f, "{}", quote_ident(&self.name))
4308        }
4309    }
4310}
4311
4312impl fmt::Display for Expr {
4313    #[allow(clippy::too_many_lines)]
4314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4315        match self {
4316            Self::Literal(l) => write!(f, "{l}"),
4317            Self::Column(c) => write!(f, "{c}"),
4318            Self::Placeholder(n) => write!(f, "${n}"),
4319            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
4320            Self::Unary { op, expr } => match op {
4321                UnOp::Not => write!(f, "(NOT {expr})"),
4322                UnOp::Neg => write!(f, "(-{expr})"),
4323                UnOp::BitNot => write!(f, "(~{expr})"),
4324            },
4325            Self::Cast { expr, target } => write!(f, "({expr}::{target})"),
4326            Self::AggregateOrdered {
4327                call,
4328                order_by,
4329                distinct,
4330                filter,
4331            } => {
4332                let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
4333                    for (i, o) in order_by.iter().enumerate() {
4334                        if i > 0 {
4335                            f.write_str(", ")?;
4336                        }
4337                        write!(f, "{}", o.expr)?;
4338                        if o.desc {
4339                            f.write_str(" DESC")?;
4340                        }
4341                        match o.nulls_first {
4342                            Some(true) => f.write_str(" NULLS FIRST")?,
4343                            Some(false) => f.write_str(" NULLS LAST")?,
4344                            None => {}
4345                        }
4346                    }
4347                    Ok(())
4348                };
4349                // Ordered-set aggregates (`percentile_cont(f) WITHIN
4350                // GROUP (ORDER BY x)`) render the in-parens args as the
4351                // direct argument and the sort spec under WITHIN GROUP —
4352                // not as an in-argument ORDER BY.
4353                let ordered_set = matches!(
4354                    call.as_ref(),
4355                    Expr::FunctionCall { name, .. }
4356                        if matches!(
4357                            name.to_ascii_lowercase().as_str(),
4358                            "percentile_cont" | "percentile_disc" | "mode"
4359                        )
4360                );
4361                if ordered_set {
4362                    write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
4363                    fmt_order_by(f)?;
4364                    f.write_str(")")?;
4365                } else {
4366                    // `name([DISTINCT ]args [ORDER BY …])` — peel the
4367                    // inner call's parens to splice modifiers.
4368                    let inner = alloc::format!("{call}");
4369                    let body = inner.strip_suffix(')').unwrap_or(&inner);
4370                    let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
4371                    write!(f, "{head}(")?;
4372                    if *distinct {
4373                        f.write_str("DISTINCT ")?;
4374                    }
4375                    write!(f, "{args_part}")?;
4376                    if !order_by.is_empty() {
4377                        f.write_str(" ORDER BY ")?;
4378                        fmt_order_by(f)?;
4379                    }
4380                    f.write_str(")")?;
4381                }
4382                if let Some(cond) = filter {
4383                    write!(f, " FILTER (WHERE {cond})")?;
4384                }
4385                Ok(())
4386            }
4387            Self::IsNull { expr, negated } => {
4388                if *negated {
4389                    write!(f, "({expr} IS NOT NULL)")
4390                } else {
4391                    write!(f, "({expr} IS NULL)")
4392                }
4393            }
4394            Self::FunctionCall { name, args } => {
4395                write!(f, "{name}(")?;
4396                for (i, a) in args.iter().enumerate() {
4397                    if i > 0 {
4398                        f.write_str(", ")?;
4399                    }
4400                    write!(f, "{a}")?;
4401                }
4402                f.write_str(")")
4403            }
4404            Self::Like {
4405                expr,
4406                pattern,
4407                negated,
4408                case_insensitive,
4409            } => {
4410                let op = match (negated, case_insensitive) {
4411                    (false, false) => "LIKE",
4412                    (true, false) => "NOT LIKE",
4413                    (false, true) => "ILIKE",
4414                    (true, true) => "NOT ILIKE",
4415                };
4416                write!(f, "({expr} {op} {pattern})")
4417            }
4418            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
4419            Self::WindowFunction {
4420                name,
4421                args,
4422                partition_by,
4423                order_by,
4424                frame,
4425                null_treatment,
4426            } => {
4427                write!(f, "{name}(")?;
4428                for (i, a) in args.iter().enumerate() {
4429                    if i > 0 {
4430                        f.write_str(", ")?;
4431                    }
4432                    write!(f, "{a}")?;
4433                }
4434                f.write_str(")")?;
4435                // v7.30.1 (mailrs round-24 class audit) — IGNORE
4436                // NULLS sits between the arg list and OVER; dropping
4437                // it reverted replayed queries to RESPECT NULLS.
4438                if matches!(null_treatment, NullTreatment::Ignore) {
4439                    f.write_str(" IGNORE NULLS")?;
4440                }
4441                f.write_str(" OVER (")?;
4442                if !partition_by.is_empty() {
4443                    f.write_str("PARTITION BY ")?;
4444                    for (i, p) in partition_by.iter().enumerate() {
4445                        if i > 0 {
4446                            f.write_str(", ")?;
4447                        }
4448                        write!(f, "{p}")?;
4449                    }
4450                }
4451                if !order_by.is_empty() {
4452                    if !partition_by.is_empty() {
4453                        f.write_str(" ")?;
4454                    }
4455                    f.write_str("ORDER BY ")?;
4456                    for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
4457                        if i > 0 {
4458                            f.write_str(", ")?;
4459                        }
4460                        write!(f, "{e}")?;
4461                        if *desc {
4462                            f.write_str(" DESC")?;
4463                        }
4464                        match nulls_first {
4465                            Some(true) => f.write_str(" NULLS FIRST")?,
4466                            Some(false) => f.write_str(" NULLS LAST")?,
4467                            None => {}
4468                        }
4469                    }
4470                }
4471                if let Some(fr) = frame {
4472                    if !partition_by.is_empty() || !order_by.is_empty() {
4473                        f.write_str(" ")?;
4474                    }
4475                    let k = match fr.kind {
4476                        FrameKind::Rows => "ROWS",
4477                        FrameKind::Range => "RANGE",
4478                    };
4479                    if let Some(end) = &fr.end {
4480                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
4481                    } else {
4482                        write!(f, "{k} {}", fr.start)?;
4483                    }
4484                }
4485                f.write_str(")")
4486            }
4487            Self::ScalarSubquery(s) => write!(f, "({s})"),
4488            Self::Exists { subquery, negated } => {
4489                if *negated {
4490                    write!(f, "NOT EXISTS ({subquery})")
4491                } else {
4492                    write!(f, "EXISTS ({subquery})")
4493                }
4494            }
4495            Self::InSubquery {
4496                expr,
4497                subquery,
4498                negated,
4499            } => {
4500                if *negated {
4501                    write!(f, "({expr} NOT IN ({subquery}))")
4502                } else {
4503                    write!(f, "({expr} IN ({subquery}))")
4504                }
4505            }
4506            Self::InList {
4507                expr,
4508                list,
4509                negated,
4510            } => {
4511                let kw = if *negated { " NOT IN (" } else { " IN (" };
4512                write!(f, "({expr}{kw}")?;
4513                for (i, e) in list.iter().enumerate() {
4514                    if i > 0 {
4515                        f.write_str(", ")?;
4516                    }
4517                    write!(f, "{e}")?;
4518                }
4519                f.write_str("))")
4520            }
4521            Self::Array(items) => {
4522                f.write_str("ARRAY[")?;
4523                for (i, e) in items.iter().enumerate() {
4524                    if i > 0 {
4525                        f.write_str(", ")?;
4526                    }
4527                    write!(f, "{e}")?;
4528                }
4529                f.write_str("]")
4530            }
4531            Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
4532            Self::AnyAll {
4533                expr,
4534                op,
4535                array,
4536                is_any,
4537            } => {
4538                let kw = if *is_any { "ANY" } else { "ALL" };
4539                write!(f, "({expr} {op} {kw}({array}))")
4540            }
4541            Self::Case {
4542                operand,
4543                branches,
4544                else_branch,
4545            } => {
4546                f.write_str("CASE")?;
4547                if let Some(op) = operand {
4548                    write!(f, " {op}")?;
4549                }
4550                for (w, t) in branches {
4551                    write!(f, " WHEN {w} THEN {t}")?;
4552                }
4553                if let Some(e) = else_branch {
4554                    write!(f, " ELSE {e}")?;
4555                }
4556                f.write_str(" END")
4557            }
4558        }
4559    }
4560}
4561
4562impl fmt::Display for Literal {
4563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4564        match self {
4565            Self::Integer(n) => write!(f, "{n}"),
4566            Self::Float(x) => {
4567                let s = format!("{x}");
4568                // Default Display for an integral f64 (e.g. 1.0) emits "1",
4569                // which would round-trip back to Integer. Force a dot.
4570                if s.contains('.') || s.contains('e') || s.contains('E') {
4571                    f.write_str(&s)
4572                } else {
4573                    write!(f, "{s}.0")
4574                }
4575            }
4576            Self::String(s) => {
4577                f.write_str("'")?;
4578                for c in s.chars() {
4579                    if c == '\'' {
4580                        f.write_str("''")?;
4581                    } else {
4582                        write!(f, "{c}")?;
4583                    }
4584                }
4585                f.write_str("'")
4586            }
4587            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
4588            Self::Null => f.write_str("NULL"),
4589            // PG external array form. Display round-trip re-enters
4590            // through the column-typed text coerce, same as pgwire.
4591            Self::TextArray(items) => {
4592                f.write_str("'{")?;
4593                for (i, it) in items.iter().enumerate() {
4594                    if i > 0 {
4595                        f.write_str(",")?;
4596                    }
4597                    match it {
4598                        None => f.write_str("NULL")?,
4599                        Some(s) => {
4600                            f.write_str("\"")?;
4601                            for c in s.chars() {
4602                                match c {
4603                                    // array-element escapes
4604                                    '"' | '\\' => write!(f, "\\{c}")?,
4605                                    // the OUTER wrapper is a SQL string
4606                                    // literal — embedded quotes must
4607                                    // double, or the rendered form
4608                                    // (WAL replay parses it back) is
4609                                    // invalid SQL
4610                                    '\'' => f.write_str("''")?,
4611                                    _ => write!(f, "{c}")?,
4612                                }
4613                            }
4614                            f.write_str("\"")?;
4615                        }
4616                    }
4617                }
4618                f.write_str("}'")
4619            }
4620            Self::IntArray(items) => {
4621                f.write_str("'{")?;
4622                for (i, it) in items.iter().enumerate() {
4623                    if i > 0 {
4624                        f.write_str(",")?;
4625                    }
4626                    match it {
4627                        None => f.write_str("NULL")?,
4628                        Some(n) => write!(f, "{n}")?,
4629                    }
4630                }
4631                f.write_str("}'")
4632            }
4633            Self::BigIntArray(items) => {
4634                f.write_str("'{")?;
4635                for (i, it) in items.iter().enumerate() {
4636                    if i > 0 {
4637                        f.write_str(",")?;
4638                    }
4639                    match it {
4640                        None => f.write_str("NULL")?,
4641                        Some(n) => write!(f, "{n}")?,
4642                    }
4643                }
4644                f.write_str("}'")
4645            }
4646            Self::Vector(v) => {
4647                f.write_str("[")?;
4648                for (i, x) in v.iter().enumerate() {
4649                    if i > 0 {
4650                        f.write_str(", ")?;
4651                    }
4652                    let s = format!("{x}");
4653                    // Mirror Float Display: force a dot so re-parse stays
4654                    // numerically literal.
4655                    if s.contains('.') || s.contains('e') || s.contains('E') {
4656                        f.write_str(&s)?;
4657                    } else {
4658                        write!(f, "{s}.0")?;
4659                    }
4660                }
4661                f.write_str("]")
4662            }
4663            Self::Interval { text, .. } => {
4664                f.write_str("INTERVAL '")?;
4665                for c in text.chars() {
4666                    if c == '\'' {
4667                        f.write_str("''")?;
4668                    } else {
4669                        write!(f, "{c}")?;
4670                    }
4671                }
4672                f.write_str("'")
4673            }
4674        }
4675    }
4676}
4677
4678impl fmt::Display for BinOp {
4679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4680        f.write_str(match self {
4681            Self::Or => "OR",
4682            Self::And => "AND",
4683            Self::Eq => "=",
4684            Self::NotEq => "<>",
4685            Self::IsDistinctFrom => "IS DISTINCT FROM",
4686            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
4687            Self::Lt => "<",
4688            Self::LtEq => "<=",
4689            Self::Gt => ">",
4690            Self::GtEq => ">=",
4691            Self::Add => "+",
4692            Self::Sub => "-",
4693            Self::Mul => "*",
4694            Self::Div => "/",
4695            Self::Mod => "%",
4696            Self::L2Distance => "<->",
4697            Self::InnerProduct => "<#>",
4698            Self::CosineDistance => "<=>",
4699            Self::Concat => "||",
4700            Self::BitOr => "|",
4701            Self::BitAnd => "&",
4702            Self::JsonGet => "->",
4703            Self::JsonGetText => "->>",
4704            Self::JsonGetPath => "#>",
4705            Self::JsonGetPathText => "#>>",
4706            Self::JsonContains => "@>",
4707            Self::JsonContainedBy => "<@",
4708            Self::JsonKeyExists => "?",
4709            Self::JsonKeysAny => "?|",
4710            Self::JsonKeysAll => "?&",
4711            Self::TsMatch => "@@",
4712            Self::InetContainedBy => "<<",
4713            Self::InetContainedByEq => "<<=",
4714            Self::InetContains => ">>",
4715            Self::InetContainsEq => ">>=",
4716            Self::InetOverlap => "&&",
4717        })
4718    }
4719}
4720
4721/// Quote `s` as a PG double-quoted identifier when required (keyword,
4722/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
4723/// Otherwise return it as-is. Returns an owned `String` to keep the call site
4724/// uniform.
4725fn quote_ident(s: &str) -> String {
4726    let needs_quote = match s.chars().next() {
4727        None => true,
4728        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
4729        _ => {
4730            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
4731                || s.chars().any(|c| c.is_ascii_uppercase())
4732                || is_keyword(s)
4733        }
4734    };
4735    if !needs_quote {
4736        return s.to_string();
4737    }
4738    let mut out = String::with_capacity(s.len() + 2);
4739    out.push('"');
4740    for c in s.chars() {
4741        if c == '"' {
4742            out.push_str("\"\"");
4743        } else {
4744            out.push(c);
4745        }
4746    }
4747    out.push('"');
4748    out
4749}
4750
4751fn is_keyword(s: &str) -> bool {
4752    matches!(
4753        &*s.to_ascii_lowercase(),
4754        "select"
4755            | "from"
4756            | "where"
4757            | "as"
4758            | "null"
4759            | "true"
4760            | "false"
4761            | "and"
4762            | "or"
4763            | "not"
4764            | "create"
4765            | "table"
4766            | "insert"
4767            | "into"
4768            | "values"
4769            | "index"
4770            | "on"
4771            | "begin"
4772            | "commit"
4773            | "rollback"
4774            | "is"
4775            | "between"
4776            | "in"
4777            | "like"
4778            | "group"
4779            | "distinct"
4780            | "union"
4781            | "all"
4782            | "join"
4783            | "inner"
4784            | "left"
4785            | "cross"
4786            | "outer"
4787            | "default"
4788            | "savepoint"
4789            | "release"
4790            | "to"
4791            | "having"
4792            | "show"
4793            | "extract"
4794            | "offset"
4795            | "asc"
4796            | "desc"
4797            | "interval"
4798    )
4799}
4800
4801#[cfg(test)]
4802mod tests {
4803    use super::*;
4804    use alloc::vec;
4805
4806    #[test]
4807    fn integer_literal_renders_without_dot() {
4808        assert_eq!(Literal::Integer(42).to_string(), "42");
4809    }
4810
4811    #[test]
4812    fn integral_float_keeps_dot() {
4813        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
4814        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
4815        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
4816    }
4817
4818    #[test]
4819    fn string_literal_doubles_quote() {
4820        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
4821    }
4822
4823    #[test]
4824    fn bool_and_null_render_uppercase() {
4825        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
4826        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
4827        assert_eq!(Literal::Null.to_string(), "NULL");
4828    }
4829
4830    #[test]
4831    fn binary_op_always_parenthesised() {
4832        let e = Expr::Binary {
4833            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
4834            op: BinOp::Add,
4835            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
4836        };
4837        assert_eq!(e.to_string(), "(1 + 2)");
4838    }
4839
4840    #[test]
4841    fn select_star_from_table() {
4842        let s = SelectStatement {
4843            items: vec![SelectItem::Wildcard],
4844            from: Some(FromClause {
4845                primary: TableRef {
4846                    name: "users".into(),
4847                    alias: None,
4848                    as_of_segment: None,
4849                    unnest_expr: None,
4850                    unnest_column_aliases: Vec::new(),
4851                    generate_series_args: None,
4852                    lateral_subquery: None,
4853                    jsonb_each_text_arg: None,
4854                },
4855                joins: vec![],
4856            }),
4857            where_: None,
4858            group_by: None,
4859            group_by_all: false,
4860            having: None,
4861            unions: vec![],
4862            order_by: Vec::new(),
4863            limit: None,
4864            offset: None,
4865            limit_with_ties: false,
4866            distinct: false,
4867            ctes: vec![],
4868        };
4869        assert_eq!(s.to_string(), "SELECT * FROM users");
4870    }
4871
4872    #[test]
4873    fn quote_ident_for_uppercase_and_keyword() {
4874        assert_eq!(quote_ident("foo"), "foo");
4875        assert_eq!(quote_ident("Foo"), "\"Foo\"");
4876        assert_eq!(quote_ident("select"), "\"select\"");
4877        assert_eq!(quote_ident(""), "\"\"");
4878        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
4879    }
4880}