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/// `COPY … TO STDOUT` output format. `text` is PG's default
15/// (tab-separated, `\N` nulls, backslash escapes); `csv` follows
16/// RFC-4180-style quoting.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum CopyFormat {
19    #[default]
20    Text,
21    Csv,
22}
23
24/// Options for `COPY … TO STDOUT [WITH] (…)`. Defaults reproduce the
25/// bare `COPY … TO STDOUT` text-format behaviour, so an empty option
26/// list is a no-op. `delimiter` / `null_str` / `quote` fall back to the
27/// per-format defaults (text: `\t` / `\N`; csv: `,` / `` / `"`) when
28/// unset.
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct CopyOptions {
31    pub format: CopyFormat,
32    pub header: bool,
33    pub delimiter: Option<char>,
34    pub null_str: Option<String>,
35    pub quote: Option<char>,
36    /// v7.39 (round 247) — CSV `ESCAPE`: the character that precedes a
37    /// quote (or itself) inside a quoted cell. Defaults to the quote
38    /// character (PG's doubling behavior).
39    pub escape: Option<char>,
40    /// v7.39 (round 247) — CSV `FORCE_QUOTE (col, …)` / `FORCE_QUOTE *`:
41    /// columns whose non-NULL cells always quote. `Some(vec![])` is the
42    /// `*` spelling (every column).
43    pub force_quote: Option<Vec<String>>,
44    /// v7.39 (round 265) — CSV `FORCE_NOT_NULL (col, …)`: for these
45    /// columns an UNQUOTED empty field reads as the empty string rather
46    /// than NULL (probed). COPY FROM only.
47    pub force_not_null: Option<Vec<String>>,
48    /// v7.39 (round 265) — CSV `FORCE_NULL (col, …)`: for these columns
49    /// a QUOTED empty field (`""`) also reads as NULL (probed). COPY
50    /// FROM only.
51    pub force_null: Option<Vec<String>>,
52}
53
54/// v7.39 (round 218) — FETCH / MOVE cursor direction. PG grammar: single-row
55/// forms (NEXT / PRIOR / FIRST / LAST / ABSOLUTE n / RELATIVE n) return at
56/// most one row; multi-row forms (bare n / ALL / FORWARD [n|ALL] /
57/// BACKWARD [n|ALL]) stream a run. A negative bare/FORWARD count means
58/// BACKWARD (normalized at execution).
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum CursorDirection {
61    Next,
62    Prior,
63    First,
64    Last,
65    Absolute(i64),
66    Relative(i64),
67    /// Bare `FETCH n` / `FORWARD n` (negative = backward n).
68    Count(i64),
69    /// `ALL` / `FORWARD ALL`.
70    All,
71    Backward(i64),
72    BackwardAll,
73}
74
75impl fmt::Display for CursorDirection {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self {
78            Self::Next => f.write_str("NEXT"),
79            Self::Prior => f.write_str("PRIOR"),
80            Self::First => f.write_str("FIRST"),
81            Self::Last => f.write_str("LAST"),
82            Self::Absolute(n) => write!(f, "ABSOLUTE {n}"),
83            Self::Relative(n) => write!(f, "RELATIVE {n}"),
84            Self::Count(n) => write!(f, "FORWARD {n}"),
85            Self::All => f.write_str("ALL"),
86            Self::Backward(n) => write!(f, "BACKWARD {n}"),
87            Self::BackwardAll => f.write_str("BACKWARD ALL"),
88        }
89    }
90}
91
92/// v7.39 (round 320, V53) — what a `DISCARD` throws away.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum DiscardTarget {
95    All,
96    Plans,
97    Sequences,
98    Temp,
99}
100
101impl fmt::Display for DiscardTarget {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(match self {
104            Self::All => "ALL",
105            Self::Plans => "PLANS",
106            Self::Sequences => "SEQUENCES",
107            Self::Temp => "TEMP",
108        })
109    }
110}
111
112/// v7.39 (round 535) — which maintenance statement, and therefore what
113/// its target names. Measured on PG18: INDEX / TABLE / CLUSTER name a
114/// relation, SCHEMA names a schema, and SYSTEM / DATABASE name neither
115/// in a way SPG can refuse.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum MaintainKind {
118    ReindexRelation,
119    ReindexSchema,
120    /// `REINDEX SYSTEM` / `REINDEX DATABASE`, and a bare `CLUSTER`.
121    Whole,
122    ClusterRelation,
123}
124
125/// v7.39 (round 547) — see [`Statement::SetDbRoleSetting`]. Boxed in the
126/// enum so the variant costs one pointer.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct SetDbRoleSettingStatement {
129    pub database: Option<String>,
130    pub role: Option<String>,
131    pub param: Option<String>,
132    pub value: Option<String>,
133}
134
135/// v7.39 (round 696) — which operand a [`Statement::ValidateOnly`] names,
136/// and therefore which catalog answers whether it exists.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum ValidateOnlyKind {
139    /// `LOCK TABLE <t> [, …]` — the relation must exist.
140    LockTable,
141    /// Every role named must exist: `DROP OWNED BY <r> [, …]`,
142    /// `REASSIGN OWNED BY <r> [, …] TO <r>`, and (round 697)
143    /// `SET SESSION AUTHORIZATION <r>`.
144    RoleName,
145    /// `SECURITY LABEL …` — PG refuses unconditionally, because no label
146    /// provider is loaded. SPG has none either.
147    SecurityLabel,
148    /// v7.39 (round 697) — `CREATE EXTENSION <e>`: the extension must be
149    /// AVAILABLE (PG: `extension "x" is not available`).
150    ExtensionAvailable,
151    /// v7.39 (round 708) — `ALTER TYPE <t> <any no-op form>`: the TYPE must
152    /// exist (PG: `type "x" does not exist`); the action itself stays a
153    /// no-op (PG genuinely renames; that residual is recorded).
154    TypeName,
155    /// v7.39 (round 708) — `ALTER AGGREGATE name(args) …`: names[0] is the
156    /// aggregate, the rest its argument type names (`*` = the `(*)` form).
157    /// Existence only; the action no-ops (PG really renames built-ins —
158    /// measured — and SPG does not model that).
159    AggregateName,
160    /// v7.39 (round 708) — `DROP CONVERSION <c>`: SPG ships no conversions,
161    /// so every name answers PG's `conversion "x" does not exist`.
162    ConversionName,
163    /// v7.39 (round 708) — `DROP LANGUAGE <l>`: an unknown language does
164    /// not exist; a shipped one is required (PG's two wordings, measured).
165    LanguageName,
166    /// v7.39 (round 709) — a collation name: performable or PG's
167    /// `collation "x" for encoding "UTF8" does not exist`.
168    CollationName,
169    /// v7.39 (round 709) — a text search configuration name.
170    TsConfigName,
171    /// v7.39 (round 709) — an event trigger name. SPG has none, so the
172    /// not-found answer is total.
173    EventTriggerName,
174    /// v7.39 (round 709) — a tablespace name. SPG has none beyond PG's two
175    /// built-ins, whose drop PG refuses with `permission denied` (measured).
176    TablespaceName,
177    /// v7.39 (round 709) — a large-object oid (names[0], decimal). The
178    /// registry is real (round 287), so the check is a lookup.
179    LargeObjectOid,
180    /// v7.39 (round 706) — `CREATE SERVER` / `CREATE FOREIGN TABLE` /
181    /// `CREATE FOREIGN DATA WRAPPER`. SPG has no foreign-data
182    /// infrastructure at all, so PG's refusals (`foreign-data wrapper "x"
183    /// does not exist`, `server "x" does not exist`) cannot be copied —
184    /// PG can refuse because the missing piece is installable there.
185    /// Accepted with a WARNING, the extension resolution (round 697):
186    /// refusing turns a dump that restores today into one that needs
187    /// editing, and silent acceptance was the actual defect.
188    ForeignInfra,
189    /// v7.39 (round 697) — `DROP EXTENSION <e>`: it must be installed
190    /// (PG: `extension "x" does not exist`).
191    ExtensionInstalled,
192}
193
194#[derive(Debug, Clone, PartialEq)]
195#[allow(clippy::large_enum_variant)] // Statement::Select dominates; Boxing would touch every match site
196pub enum Statement {
197    /// v7.39 (round 695) — `ALTER SYSTEM SET <name> = …` / `RESET <name>`.
198    ///
199    /// It used to be swallowed with the rest of the ALTER no-ops, which meant
200    /// `ALTER SYSTEM SET nosuch_guc = 1` was ACCEPTED where PG18 answers
201    /// `unrecognized configuration parameter`. SPG still applies nothing —
202    /// there is no postgresql.auto.conf to write — but a name it does not
203    /// know is now refused rather than swallowed.
204    ///
205    /// `None` is `RESET ALL`, which names no parameter.
206    AlterSystem {
207        parameter: Option<String>,
208    },
209    /// `DROP DATABASE [IF EXISTS] <name>`. SPG is single-database, so
210    /// this never succeeds; the name and the flag are carried so the
211    /// engine can answer with PG's wording for the two cases PG itself
212    /// has — an unknown name, or the database you are connected to.
213    DropDatabase {
214        name: String,
215        if_exists: bool,
216    },
217    /// A statement SPG accepts as a no-op but PG refuses inside a
218    /// transaction block — today `CREATE DATABASE` / `DROP DATABASE`,
219    /// which are no-ops here because SPG is single-database.
220    ///
221    /// The no-op path they used to share (`Statement::Empty`) also
222    /// carries CREATE ROLE, CREATE CAST and a dozen others that PG is
223    /// happy to run inside a transaction, so the object has to be named
224    /// to refuse the right ones.
225    NoOpPreventedInTransaction {
226        what: String,
227    },
228    /// v7.39 (round 696) — statements SPG performs nothing for, but whose
229    /// OPERAND PG validates before performing nothing either.
230    ///
231    /// All four used to be consumed whole by `is_dump_noise_statement`,
232    /// which meant `LOCK TABLE nosuch` and `DROP OWNED BY nosuchrole` were
233    /// ACCEPTED where PG18 errors. Accepting a statement that names
234    /// something that does not exist is the F29 shape: the caller is told
235    /// their intent was understood when the object it referred to is not
236    /// there.
237    ///
238    /// They share one variant because they share one rule — resolve the
239    /// name, refuse if absent, otherwise no-op — and four variants would be
240    /// four places for that rule to drift.
241    /// v7.39 (round 707) — `DROP AGGREGATE [IF EXISTS] name(argtypes)[, …]`.
242    /// Consumed whole by the dump-noise list before, so `DROP AGGREGATE
243    /// nosuch(int)` reported success. PG validates every named aggregate's
244    /// EXISTENCE first (measured: a list with one unknown fails on the
245    /// unknown even when an earlier entry exists), renders the signature
246    /// with canonical type names (`int` → `integer`), and refuses to drop a
247    /// built-in (`cannot drop function sum(integer) because it is required
248    /// by the database system`). Every SPG aggregate is a built-in, so the
249    /// outcome is one of those two errors — or the IF EXISTS no-op.
250    ///
251    /// `args` holds the argument type names as written; `None` is the
252    /// `(*)` spelling.
253    DropAggregate {
254        if_exists: bool,
255        items: Vec<(String, Option<Vec<String>>)>,
256    },
257    /// v7.39 (round 750) — `ALTER ROLE|USER <name> … PASSWORD 'x' |
258    /// PASSWORD NULL`. The one attribute of the no-op family with a
259    /// SECURITY consequence: it was silently dropped (ledgered r710),
260    /// so a rotated credential never rotated. `None` = PASSWORD NULL
261    /// (the role keeps existing but can no longer password-auth).
262    AlterRolePassword {
263        name: String,
264        password: Option<String>,
265    },
266    ValidateOnly {
267        kind: ValidateOnlyKind,
268        /// The names the statement referred to. Empty means the form names
269        /// nothing (`SECURITY LABEL`, whose refusal is unconditional).
270        names: Vec<String>,
271    },
272
273    /// v7.39 (round 547) — `ALTER ROLE … SET/RESET` and
274    /// `ALTER DATABASE … SET/RESET`: the GUC defaults a session picks up
275    /// when it starts. Both used to land in the pg_dump no-op tail, so
276    /// the statement reported success and changed nothing.
277    ///
278    /// `database` / `role` are `None` for PG's oid 0 — `ALTER ROLE ALL`
279    /// sets both to None. `param` is `None` for RESET ALL. `value` is
280    /// `None` for RESET of one parameter.
281    SetDbRoleSetting(Box<SetDbRoleSettingStatement>),
282    /// v7.39 (round 288) — `SET CONSTRAINTS { ALL | <name>… }
283    /// { DEFERRED | IMMEDIATE }`. `deferred` carries the timing; the
284    /// name list is not yet honoured (ALL is what pg_dump emits and
285    /// what a circular-FK restore needs), so a named form applies to
286    /// all deferrable constraints too rather than silently doing
287    /// nothing.
288    /// v7.39 (round 308) — `SET CONSTRAINTS { ALL | name [, …] }
289    /// { DEFERRED | IMMEDIATE }`. An empty `names` is the ALL form;
290    /// otherwise the timing applies only to the constraints listed.
291    SetConstraints {
292        names: Vec<String>,
293        deferred: bool,
294    },
295
296    /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
297    /// [CASCADE | RESTRICT]`. Engine removes the matching tables
298    /// (each one) from the catalog; IF EXISTS makes the drop
299    /// idempotent. CASCADE / RESTRICT trailers parsed silently
300    /// (SPG always cascades index drops on table drop).
301    DropTable {
302        names: Vec<String>,
303        if_exists: bool,
304    },
305    /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
306    /// matching index across whichever table holds it.
307    DropIndex {
308        name: String,
309        if_exists: bool,
310    },
311    /// v7.14.0 — empty / comment-only statement. The lexer strips
312    /// `--` line comments and `/* … */` block comments (including
313    /// the MySQL conditional `/*!NNNNN … */` form) before the
314    /// parser ever sees them; a SQL chunk that contains nothing
315    /// else lands here. Engine returns CommandOk no-op so
316    /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
317    /// wrapped in conditional comments, etc.) load cleanly.
318    /// v7.39 (round 277) — SQL-level `PREPARE <name> [(type, …)] AS
319    /// <stmt>`. Session-scoped; the body keeps its `$N` placeholders
320    /// and is substituted at EXECUTE time.
321    Prepare {
322        name: String,
323        /// Declared parameter type names, in order. Empty when the
324        /// `(type, …)` list was omitted (PG infers them).
325        param_types: Vec<String>,
326        body: alloc::boxed::Box<Statement>,
327        /// The statement's own source text, which
328        /// `pg_prepared_statements.statement` reports verbatim.
329        source: String,
330    },
331    /// v7.39 (round 277) — `EXECUTE <name> [(arg, …)]`.
332    Execute {
333        name: String,
334        args: Vec<Expr>,
335    },
336    /// v7.39 (round 277) — `DEALLOCATE {<name> | ALL}`. `None` = ALL.
337    Deallocate(Option<String>),
338    /// v7.39 (round 280) — `CREATE STATISTICS [IF NOT EXISTS] <name>
339    /// [(kind, …)] ON <col>, … FROM <table>`. SPG records the object so
340    /// dumps restore and reflection is honest; the planner does not
341    /// consult it yet.
342    CreateStatistics {
343        name: String,
344        if_not_exists: bool,
345        /// Requested kinds as PG's single letters (`d` ndistinct,
346        /// `f` dependencies, `m` mcv). Empty = PG's default set.
347        kinds: Vec<String>,
348        columns: Vec<String>,
349        table: String,
350    },
351    /// v7.39 (round 280) — `DROP STATISTICS [IF EXISTS] <name>`.
352    DropStatistics {
353        name: String,
354        if_exists: bool,
355    },
356    /// v7.39 (round 278) — `CALL <proc>(…)`. Parses; the engine
357    /// reports that the procedure does not exist, because SPG has no
358    /// procedure catalog. Carried as a statement rather than raised at
359    /// parse time so the failure is a missing OBJECT (42883), not a
360    /// syntax error.
361    Call(String),
362    /// v7.39 (round 278) — `PREPARE TRANSACTION '<gid>'`. Same shape:
363    /// 2PC is unavailable, which PG itself reports when
364    /// `max_prepared_transactions` is 0.
365    PrepareTransaction(String),
366    Empty,
367    /// v7.39 (round 218) — `DECLARE <name> [BINARY] [INSENSITIVE]
368    /// [[NO] SCROLL] CURSOR [{WITH|WITHOUT} HOLD] FOR <select>`. The
369    /// canonical driver path for streaming large result sets (psycopg2
370    /// named cursors, JDBC setFetchSize).
371    DeclareCursor {
372        name: String,
373        /// `None` = neither keyword (PG default: backward allowed when the
374        /// plan supports it — always, for SPG's materialized cursors);
375        /// `Some(true)` = SCROLL; `Some(false)` = NO SCROLL (backward
376        /// fetch errors 55000).
377        scroll: Option<bool>,
378        /// `WITH HOLD` — survives the creating transaction's COMMIT.
379        hold: bool,
380        query: Box<Statement>,
381    },
382    /// v7.39 (round 218) — `FETCH [<direction>] [FROM|IN] <name>`.
383    FetchCursor {
384        name: String,
385        direction: CursorDirection,
386    },
387    /// v7.39 (round 218) — `MOVE [<direction>] [FROM|IN] <name>`: FETCH
388    /// without returning rows; the command tag carries the move count.
389    MoveCursor {
390        name: String,
391        direction: CursorDirection,
392    },
393    /// v7.39 (round 218) — `CLOSE <name>` / `CLOSE ALL` (`None` = ALL).
394    CloseCursor {
395        name: Option<String>,
396    },
397    /// v7.39 (round 222) — `LISTEN <channel>`: subscribe this session to
398    /// async notifications on the channel.
399    Listen(String),
400    /// v7.39 (round 222) — `NOTIFY <channel> [, '<payload>']`. Delivered at
401    /// COMMIT (PG semantics: transactional, deduplicated within the tx);
402    /// immediately under autocommit.
403    Notify {
404        channel: String,
405        payload: Option<String>,
406    },
407    /// v7.39 (round 222) — `UNLISTEN <channel>` / `UNLISTEN *` (`None` = *).
408    Unlisten(Option<String>),
409    /// `COPY table [(cols)] TO STDOUT` — the engine renders the
410    /// visible rows in COPY text format (tab-separated, `\N`
411    /// nulls, backslash escapes) as a single-text-column result
412    /// set; the wire layer streams CopyData from it.
413    CopyTo {
414        table: String,
415        columns: Option<Vec<String>>,
416        /// v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT`: an
417        /// arbitrary SELECT/VALUES/CTE (a whole [`Statement`], so set-ops and
418        /// VALUES ride through unchanged) whose result set is streamed in COPY
419        /// format. `Some` overrides `table`/`columns` (which are empty then);
420        /// `None` is the classic `COPY <table> …` shape.
421        query: Option<Box<Statement>>,
422        /// v7.37.x — `WITH (FORMAT csv, HEADER, DELIMITER, NULL, QUOTE)`
423        /// and the legacy `WITH CSV HEADER …` spelling. Default =
424        /// text format, no header (bare `COPY … TO STDOUT`).
425        options: CopyOptions,
426    },
427    /// v7.39 (round 249) — `COPY table [(cols)] FROM '<path>' [(opts)]`.
428    /// The engine is no_std and cannot read the file itself: the host
429    /// (embedded / server / tooling) reads the path and hands the bytes to
430    /// `Engine::copy_from_buffer`. Dispatching this statement straight to
431    /// the engine reports that contract.
432    CopyFromFile {
433        table: String,
434        columns: Option<Vec<String>>,
435        path: String,
436        options: CopyOptions,
437    },
438    /// v7.39 (round 249/252) — `COPY <table> [(cols)] TO '<file>'` (and
439    /// the `COPY (<query>) TO '<file>'` form). The engine is no_std and
440    /// cannot write the file itself: the host renders the payload via
441    /// `Engine::copy_to_buffer` and writes the path.
442    CopyToFile {
443        table: String,
444        columns: Option<Vec<String>>,
445        query: Option<Box<Statement>>,
446        path: String,
447        options: CopyOptions,
448    },
449    Select(SelectStatement),
450    CreateTable(CreateTableStatement),
451    /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
452    /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
453    /// no-op so PG dumps that include extension declarations
454    /// (notably `pgvector`) load against SPG without splitting
455    /// init scripts. mailrs migration follow-up F3.
456    CreateExtension(String),
457    /// v7.9.27 → v7.16.2 — PG `DO $$ … $$ [LANGUAGE plpgsql];`
458    /// block. The body is now CAPTURED as a [`PlPgSqlBlock`] and
459    /// the engine executes it at top level (mailrs round-10
460    /// A.2). Pre-v7.16.2 the parser discarded the body and the
461    /// engine returned CommandOk — a SEV-1 silent no-op that
462    /// turned mailrs's `DO BEGIN IF EXISTS … THEN ALTER … END
463    /// $$` idempotent migrations into invisible no-ops.
464    DoBlock(PlPgSqlBlock),
465    CreateIndex(CreateIndexStatement),
466    Insert(InsertStatement),
467    /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
468    Update(UpdateStatement),
469    /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
470    Delete(DeleteStatement),
471    /// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ `MERGE` statement.
472    /// `MERGE INTO target [alias] USING source [alias] ON cond
473    /// WHEN MATCHED [AND cond] THEN { UPDATE SET … | DELETE | DO NOTHING }
474    /// WHEN NOT MATCHED [AND cond] THEN { INSERT (cols) VALUES (vals) | DO NOTHING }
475    /// [WHEN …]`. SPG v7.17 supports table-based source (subquery
476    /// source is a follow-up); BY SOURCE / BY TARGET and RETURNING
477    /// are also follow-ups.
478    Merge(MergeStatement),
479    /// v7.39 (round 169) — `VACUUM [(opts)] [FULL|FREEZE|VERBOSE|ANALYZE]
480    /// [<table>]`. Was a parse-time no-op from the pre-MVCC era; with the
481    /// in-place MVCC gate ON, tombstoned versions are REAL bloat and a
482    /// customer's manual VACUUM must actually reclaim. `analyze` mirrors
483    /// the `VACUUM ANALYZE` spelling.
484    Vacuum {
485        table: Option<String>,
486        analyze: bool,
487    },
488    /// `BEGIN` / `START TRANSACTION` — with an optional explicit
489    /// `ISOLATION LEVEL …` mode (`None` = use the session default). PG
490    /// applies the level for the duration of this transaction only.
491    Begin(Option<IsolationLevel>),
492    Commit,
493    Rollback,
494    /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
495    /// stack so a later `ROLLBACK TO <name>` can undo just the work
496    /// since this point.
497    Savepoint(String),
498    /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
499    /// named savepoint and discard later savepoints. Does not end the
500    /// transaction.
501    RollbackToSavepoint(String),
502    /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
503    /// rolling back. Keeps the work done since then.
504    ReleaseSavepoint(String),
505    /// `SHOW TABLES` — return the list of tables in the catalog.
506    ShowTables,
507    /// v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES` /
508    /// `SHOW SCHEMAS`. SPG is single-database; the executor
509    /// returns the canonical MySQL set so the mysql / MariaDB
510    /// client populates its database selector.
511    ShowDatabases,
512    /// v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE TABLE <t>`
513    /// returns a 2-column row `(Table, "Create Table")` carrying
514    /// the synthesized DDL. mysqldump emits this for every
515    /// table at scrape time.
516    ShowCreateTable(String),
517    /// v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES FROM <t>`
518    /// (also `SHOW INDEX`, `SHOW KEYS`).
519    ShowIndexes(String),
520    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS`.
521    ShowStatus,
522    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW VARIABLES`.
523    ShowVariables,
524    /// v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
525    ShowProcesslist,
526    /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
527    /// pgbouncer sends `DISCARD ALL` between pooled client sessions to make
528    /// the connection look brand new to the next client; it used to be
529    /// swallowed as dump noise, so nothing was discarded.
530    Discard(DiscardTarget),
531    /// v7.39 (round 318, V51) — MySQL `KILL [CONNECTION | QUERY] <expr>`.
532    /// The id is an expression because MariaDB accepts one
533    /// (`KILL connection_id()` is the documented way to drop your own
534    /// connection). `query_only` is the `QUERY` form: stop the target's
535    /// running statement but leave it connected.
536    Kill {
537        query_only: bool,
538        id: Box<Expr>,
539    },
540    /// `SHOW COLUMNS FROM <table>` — return one row per column with
541    /// its declared name / type / nullability.
542    ShowColumns(String),
543    /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
544    /// Role is optional; defaults to `readonly` when omitted.
545    CreateUser(CreateUserStatement),
546    /// `DROP USER 'name'` (v4.1). v7.39 (read01 round 58) — `IF EXISTS` is
547    /// carried through: PG skips with a NOTICE rather than erroring.
548    DropUser {
549        name: String,
550        if_exists: bool,
551    },
552    /// v7.39 (RLS) — `SET ROLE { name | NONE | DEFAULT }` / `RESET ROLE`.
553    /// `Some(name)` switches the session's effective role (drives
554    /// `current_user` and RLS enforcement); `None` resets to the login
555    /// identity (the Admin superuser).
556    SetRole(Option<String>),
557    /// v7.39 (read01 round 57) — `GRANT <privs> ON <object> TO <roles>`.
558    Grant(GrantStatement),
559    /// v7.39 (read01 round 57) — `REVOKE [GRANT OPTION FOR] <privs> ON
560    /// <object> FROM <roles>`.
561    Revoke(GrantStatement),
562    /// v7.39 (RLS) — `CREATE POLICY name ON table …`.
563    CreatePolicy(CreatePolicyStatement),
564    /// v7.39 (RLS) — `ALTER POLICY name ON table …`.
565    AlterPolicy(AlterPolicyStatement),
566    /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
567    DropPolicy(DropPolicyStatement),
568    /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
569    ShowUsers,
570    /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
571    /// single-column text table describing the rewritten plan tree
572    /// for `inner`. `analyze` triggers an actual exec to attach
573    /// observed row counts and elapsed micros to each node.
574    Explain(ExplainStatement),
575    /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
576    /// Synchronous rebuild of an NSW index. With the optional
577    /// encoding clause, every stored cell at the indexed column is
578    /// also re-encoded through `coerce_value` before the new graph
579    /// builds.
580    AlterIndex(AlterIndexStatement),
581    /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
582    /// The only setting in v6.7.2 is `hot_tier_bytes`, which
583    /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
584    /// for the named table.
585    AlterTable(AlterTableStatement),
586    /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
587    /// The catalog row lives in `spg_publications`. Publisher-side
588    /// WAL filtering arrives in v6.1.5.
589    CreatePublication(CreatePublicationStatement),
590    /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
591    /// no-op when the publication does not exist.
592    DropPublication {
593        name: String,
594        /// v7.39 (round 754, F31-B4) — `IF EXISTS` quietly skips a
595        /// missing publication; the bare form refuses with PG's
596        /// sentence (PG18-measured — the old "silent no-op" note on
597        /// the executor was wrong).
598        if_exists: bool,
599    },
600    /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
601    /// publication ordered by name with `(name, scope_summary,
602    /// table_count)` columns. The scope summary is the human-
603    /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
604    /// TABLES EXCEPT …`; `table_count` is `NULL` for the
605    /// `AllTables` scope and the table-list length otherwise.
606    ShowPublications,
607    /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
608    /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
609    /// in `spg_subscriptions`; when the subscription is
610    /// `enabled = true` (default) the server spawns a
611    /// background worker that connects to `conn` and drains the
612    /// requested publication(s) into the local engine.
613    CreateSubscription(CreateSubscriptionStatement),
614    /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
615    /// PUBLICATION, silent no-op when absent. Stops the
616    /// associated worker thread before removing the row.
617    DropSubscription {
618        name: String,
619        /// v7.39 (round 754, F31-B4) — same contract as
620        /// [`Statement::DropPublication`].
621        if_exists: bool,
622    },
623    /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
624    /// subscription ordered by name with `(name, conn_str,
625    /// publications, enabled, last_received_pos)`.
626    ShowSubscriptions,
627    /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
628    /// Blocks until the local server's apply position reaches
629    /// `<pos>` or `<ms>` elapses. Server-layer command: the
630    /// engine refuses it (`EngineError::Unsupported`) since
631    /// `lag_state` lives in `spg-server`'s `ServerState`.
632    WaitForWalPosition {
633        pos: u64,
634        /// `None` → wait forever; `Some(ms)` → return after `ms`
635        /// milliseconds even if the target isn't reached.
636        timeout_ms: Option<u64>,
637    },
638    /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
639    /// table; `ANALYZE <name>` re-stats just one. Populates
640    /// `spg_statistic` with per-column null_frac + n_distinct +
641    /// 100-bucket equi-depth histogram.
642    Analyze(Option<String>),
643    /// v7.39 (round 535) — `REINDEX { INDEX | TABLE | SCHEMA | DATABASE
644    /// | SYSTEM } [CONCURRENTLY] <name>` and `CLUSTER [VERBOSE]
645    /// [<table> [USING <index>]]`.
646    ///
647    /// SPG has neither index bloat nor a clustering order to rebuild, so
648    /// the work is a no-op — but PG VALIDATES the target, and both were
649    /// swallowed at parse time, so `REINDEX TABLE typo` reported success.
650    /// The name is carried now so the engine can say what PG says.
651    Maintain {
652        kind: MaintainKind,
653        /// `REINDEX … CONCURRENTLY`. Carried for the same reason as
654        /// [`CreateIndexStatement::concurrently`]: PG bars the
655        /// CONCURRENTLY form inside a transaction block and allows the
656        /// plain one.
657        concurrently: bool,
658        /// `None` for the whole-database forms, which name nothing.
659        target: Option<String>,
660    },
661    /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] [ONLY] <name>
662    /// [, ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE |
663    /// RESTRICT]`. Clears every row from each named table. SPG's
664    /// SEQUENCE identity is per-table; RESTART IDENTITY reinitializes
665    /// the associated sequence to its starting value. CASCADE
666    /// currently walks direct FK-referring tables and truncates
667    /// them too (PG's semantics). The ONLY modifier (skip partitions)
668    /// and RESTRICT (default) are accepted with no effect since
669    /// SPG's declarative partitions are always truncated together.
670    Truncate {
671        tables: Vec<String>,
672        restart_identity: bool,
673        cascade: bool,
674        /// v7.39 (round 647) — `TRUNCATE ONLY t`. Absorbed as a no-op
675        /// since v7.14 on the reasoning that SPG's children are separate
676        /// relations a truncate does not descend into. Same reasoning
677        /// round 621 applied to `FROM ONLY`, and it stopped being true
678        /// for the same reason: measured, `TRUNCATE <inheritance parent>`
679        /// leaves the children's rows where PG empties them, and
680        /// `TRUNCATE ONLY <partitioned parent>` is silently accepted
681        /// where PG refuses it outright.
682        only: bool,
683    },
684    /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
685    /// BTree-cold indices and merges small cold-tier segments
686    /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
687    /// 4 MiB) into a single larger segment per (table, index).
688    /// `WHERE` predicate filtering on which tables to compact is
689    /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
690    /// v6.7.3 only supports the bare form.
691    CompactColdSegments,
692    /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
693    /// parameter on the engine; v7.12.1 honours
694    /// `default_text_search_config` (consumed by `to_tsvector` /
695    /// `plainto_tsquery` family when called without an explicit
696    /// config arg). All other names are accepted as a no-op so PG
697    /// dumps with `SET client_encoding`, `SET search_path` etc.
698    /// load cleanly.
699    SetParameter {
700        name: String,
701        value: SetValue,
702        /// v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to the
703        /// current transaction; the engine saves the prior value and
704        /// restores it at COMMIT / ROLLBACK. Plain `SET` (and `SET
705        /// SESSION`) leave this false and persist for the session.
706        local: bool,
707    },
708    /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
709    /// multi-assignment (mysqldump preamble uses
710    /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
711    /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
712    /// source order. Pairs whose LHS is a MySQL session/user
713    /// variable (`@VAR` / `@@VAR`) are recorded with the raw
714    /// name so the engine can ignore them; pairs whose LHS is
715    /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
716    /// go through the regular `set_session_param` path.
717    SetParameterList(Vec<(String, SetValue)>),
718    /// v7.39 (round 430) — MySQL's USER-defined variables:
719    /// `SET @x = 5, @s := CONCAT('a','b')`. Distinct from
720    /// [`Self::SetParameter`] (a `@@`-style engine/session setting) in
721    /// every way that matters: the value is an arbitrary EXPRESSION, the
722    /// name lives in its own per-session namespace, and reading an unset
723    /// one answers NULL rather than raising. `:=` and `=` are the same
724    /// assignment here.
725    ///
726    /// Before this the parser stripped every `@`, so `@x` and `@@x` were
727    /// the same node: `SET @x = 5` silently landed in the session-parameter
728    /// store where nothing could read it back, and `SELECT @x` failed with
729    /// "Unknown system variable".
730    /// v7.39 (round 554) — `SET @a = …, SETTING = …`.
731    ///
732    /// `settings` is the trailing half a mysqldump preamble writes:
733    /// `SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'`
734    /// saves a value and changes it in one statement. The parser used
735    /// to refuse the mixture outright, so no mysqldump could be
736    /// restored past its preamble.
737    SetUserVars(Vec<(String, Expr)>, Vec<(String, Expr)>),
738    /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
739    /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
740    /// silently accepted). PG-standard surface for picking an
741    /// isolation level. Engine tracks the value on
742    /// `Engine::current_isolation_level()`; actual MVCC / SSI
743    /// semantics implementation lands separately. PG itself maps
744    /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
745    /// effectively every level reads as READ COMMITTED in v7.37.8.
746    SetTransaction {
747        isolation: IsolationLevel,
748    },
749    /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
750    /// with the parameter's current value as TEXT. Today the only
751    /// recognised param is `transaction_isolation`; further
752    /// surfaces (`search_path`, `application_name`, …) land as the
753    /// session-parameter inventory grows.
754    ShowParameter(String),
755    /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
756    /// to its default. No-op for parameters SPG does not track.
757    ResetParameter(Option<String>),
758    /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
759    /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
760    /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
761    /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
762    /// languages parse but error at exec time with a clear
763    /// unsupported message.
764    CreateFunction(CreateFunctionStatement),
765    /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
766    /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
767    /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
768    /// triggers and column-list / WHEN clauses are out of scope
769    /// for v7.12.4.
770    CreateTrigger(CreateTriggerStatement),
771    /// v7.39 (round 139) — `CREATE RULE name AS ON event TO table [WHERE cond]
772    /// DO [ALSO|INSTEAD] { NOTHING | command }` query-rewrite rule.
773    CreateRule(CreateRuleStatement),
774    /// v7.39 (round 139) — `DROP RULE [IF EXISTS] name ON table`.
775    DropRule {
776        name: String,
777        table: String,
778        if_exists: bool,
779    },
780    /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
781    /// no-op when missing if `IF EXISTS` is set.
782    DropTrigger {
783        name: String,
784        table: String,
785        if_exists: bool,
786    },
787    /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
788    /// DROP TRIGGER but global (no table scope).
789    DropFunction {
790        name: String,
791        /// v7.39 (read01 round 62) — the argument TYPES, when the statement gave
792        /// them: `DROP FUNCTION f(int)` drops that overload only. `None` = no
793        /// argument list, which PG accepts only when the name is unambiguous.
794        args: Option<Vec<String>>,
795        if_exists: bool,
796    },
797    /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
798    /// [AS data_type]
799    /// [INCREMENT [BY] n]
800    /// [MINVALUE n | NO MINVALUE]
801    /// [MAXVALUE n | NO MAXVALUE]
802    /// [START [WITH] n]
803    /// [CACHE n]
804    /// [[NO] CYCLE]
805    /// [OWNED BY {table.col | NONE}]`.
806    /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
807    /// emits + nextval/currval/setval downstream all work.
808    CreateSequence(CreateSequenceStatement),
809    /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
810    /// the same option grammar as CREATE SEQUENCE, plus
811    /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
812    AlterSequence(AlterSequenceStatement),
813    /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
814    /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
815    /// silently (no FK on sequences).
816    DropSequence {
817        names: Vec<String>,
818        if_exists: bool,
819    },
820    /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
821    /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
822    /// silent-no-op VIEW story from the v7.17 customer-readiness
823    /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
824    /// so any downstream `SELECT FROM v` errored with table-not-
825    /// found. The view body is stored verbatim; SELECT FROM <v>
826    /// rewrites at exec-time by prepending the view body as a
827    /// synthetic CTE.
828    CreateView(CreateViewStatement),
829    /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
830    /// [CASCADE | RESTRICT]`. Removes the matching view from the
831    /// catalog; CASCADE/RESTRICT parsed silently.
832    DropView {
833        names: Vec<String>,
834        if_exists: bool,
835    },
836    /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
837    /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
838    /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
839    /// model: the materialised result lives as a regular table
840    /// with the matching name + a parallel
841    /// `materialized_views` registry mapping name → body source
842    /// (used by REFRESH).
843    CreateMaterializedView(CreateMaterializedViewStatement),
844    /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
845    /// [NO] DATA]`. Re-runs the stored body and replaces the
846    /// cached rows. `WITH NO DATA` truncates without re-running.
847    RefreshMaterializedView {
848        name: String,
849        with_data: bool,
850    },
851    /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
852    /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
853    /// backing table and the source registry entry.
854    DropMaterializedView {
855        names: Vec<String>,
856        if_exists: bool,
857    },
858    /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
859    /// …)`. Closes the silent-no-op CREATE TYPE story so PG
860    /// dumps that declare enum types load with real constraints
861    /// instead of becoming free-form TEXT. Future kinds
862    /// (composite / range / domain) extend the inner `kind`
863    /// enum.
864    CreateType(CreateTypeStatement),
865    /// v7.37 D.55 — `ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
866    /// [{BEFORE | AFTER} 'existing']`. Extends an enum's label list so
867    /// enum evolution stops being a silent no-op. `position` is
868    /// `Some((is_before, anchor))`.
869    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
870    /// Used to be swallowed by the ALTER TYPE no-op tail, so the rename was
871    /// accepted and silently ignored.
872    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
873    /// Used to be swallowed as dump noise, so a comment was accepted and lost
874    /// (and obj_description / col_description always returned NULL).
875    /// `kind` is lowercase ("table" / "column" / "index" / …); for a column
876    /// `name` is the dotted `table.column`. `comment: None` = `IS NULL` = remove.
877    CommentOn {
878        kind: String,
879        name: String,
880        comment: Option<String>,
881    },
882    AlterTypeRenameValue {
883        type_name: String,
884        old: String,
885        new: String,
886    },
887    AlterTypeAddValue {
888        type_name: String,
889        label: String,
890        if_not_exists: bool,
891        position: Option<(bool, String)>,
892    },
893    /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
894    /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
895    /// from the catalog.
896    DropType {
897        names: Vec<String>,
898        if_exists: bool,
899    },
900    /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
901    /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
902    /// A DOMAIN is a named CHECK-constrained alias over a built-
903    /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
904    /// every column declared with the domain. Closes the
905    /// silent-no-op CREATE DOMAIN story so PG dumps that ship
906    /// validated identifier types (email, positive_int, …) keep
907    /// their guarantees.
908    CreateDomain(CreateDomainStatement),
909    /// v7.39 (round 260) — `ALTER DOMAIN name <action>`. Every form was
910    /// previously swallowed by the catch-all DDL arm: the statement
911    /// reported success and did nothing, so a migration that dropped a
912    /// constraint kept rejecting the data it had just been told to
913    /// accept.
914    AlterDomain {
915        name: String,
916        action: AlterDomainAction,
917    },
918    /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
919    /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
920    /// domain from the catalog.
921    DropDomain {
922        names: Vec<String>,
923        if_exists: bool,
924    },
925    /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
926    /// name [AUTHORIZATION user]`. SPG is single-database;
927    /// schemas are tracked as a namespace registry so pg_dump
928    /// multi-schema declarations land cleanly and `SELECT *
929    /// FROM information_schema.schemata` returns real entries.
930    /// Schema-qualified `schema.table` references still strip
931    /// the prefix at lookup time per PG (schemas are not
932    /// isolation boundaries in v7.17 — see project-next-docket
933    /// for the v7.18+ isolation tracking).
934    CreateSchema {
935        name: String,
936        if_not_exists: bool,
937    },
938    /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
939    /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
940    /// from the registry; built-in `public` / `pg_catalog` /
941    /// `information_schema` cannot be dropped.
942    DropSchema {
943        names: Vec<String>,
944        if_exists: bool,
945    },
946}
947
948/// v7.39 (round 260) — the `ALTER DOMAIN` actions SPG implements.
949#[derive(Debug, Clone, PartialEq)]
950pub enum AlterDomainAction {
951    AddConstraint { name: Option<String>, check: Expr },
952    DropConstraint { name: String, if_exists: bool },
953    SetDefault(Expr),
954    DropDefault,
955    SetNotNull,
956    DropNotNull,
957    RenameTo(String),
958}
959
960/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
961#[derive(Debug, Clone, PartialEq)]
962pub struct CreateDomainStatement {
963    pub name: String,
964    /// Base type for the domain (one of the built-in
965    /// `ColumnTypeName` variants).
966    pub base_type: ColumnTypeName,
967    /// v7.39 (round 259) — `CREATE DOMAIN child AS parent …` where
968    /// `parent` is itself a DOMAIN. The parser already captured the
969    /// unknown type name; it just was not carried here, so the parent's
970    /// CHECK constraints were invisible and a value violating them was
971    /// silently accepted. `base_type` still holds the ultimate scalar
972    /// type, which is what the storage tier stores.
973    pub base_domain: Option<String>,
974    /// Optional `DEFAULT <expr>`. Resolved at engine-side
975    /// CREATE TABLE time when a column is bound to this domain.
976    pub default: Option<Expr>,
977    /// `NOT NULL` from the domain definition. Engine ORs this
978    /// with the column-level nullability so the strictest of the
979    /// two wins (i.e. the column is non-nullable if either side
980    /// says so).
981    pub not_null: bool,
982    /// Zero-or-more `CHECK (expr)` predicates. Each one is
983    /// enforced as part of the column's CHECK list at INSERT /
984    /// UPDATE time, with `VALUE` substituted for the column's
985    /// current cell value.
986    pub checks: Vec<Expr>,
987}
988
989/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
990#[derive(Debug, Clone, PartialEq, Eq)]
991pub struct CreateTypeStatement {
992    pub name: String,
993    pub kind: TypeKind,
994}
995
996/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
997/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
998/// and later (COMPOSITE, RANGE) can land without an AST shape
999/// migration.
1000///
1001/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
1002/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
1003/// stores the field list in the catalog so PG dumps that emit
1004/// `CREATE TYPE … AS (…)` don't error out; using a composite type
1005/// as a column type lands in Phase 2 (Value::Composite encoding +
1006/// ROW() literal + field-access syntax).
1007#[derive(Debug, Clone, PartialEq, Eq)]
1008pub enum TypeKind {
1009    /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
1010    /// labels are ordered).
1011    Enum { labels: Vec<String> },
1012    /// `AS (field_name field_type, …)`. Order matters; PG
1013    /// composite literals are positional.
1014    Composite {
1015        fields: Vec<(String, ColumnTypeName)>,
1016        /// v7.39 (round 264) — parallel to `fields`: the raw type NAME
1017        /// when a field's type is not a builtin (i.e. another composite).
1018        /// The parser already captures it; without carrying it here a
1019        /// nested composite field resolved to the Text placeholder and
1020        /// the inner record never became a record.
1021        field_user_types: Vec<Option<String>>,
1022    },
1023}
1024
1025/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
1026/// a string literal, an identifier (often a config name), an
1027/// integer/float, or the bare `DEFAULT` keyword.
1028#[derive(Debug, Clone, PartialEq)]
1029pub enum SetValue {
1030    String(String),
1031    Ident(String),
1032    Number(String),
1033    Default,
1034}
1035
1036/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
1037/// at parse time and tracks the selected value on the engine. The
1038/// actual semantic differentiation (REPEATABLE READ snapshot,
1039/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
1040/// today every level reads as effective READ COMMITTED (which is
1041/// also how PG treats READ UNCOMMITTED — it silently upgrades to
1042/// READ COMMITTED). Default = `ReadCommitted`.
1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1044pub enum IsolationLevel {
1045    ReadUncommitted,
1046    #[default]
1047    ReadCommitted,
1048    RepeatableRead,
1049    Serializable,
1050}
1051
1052impl IsolationLevel {
1053    /// Canonical PG-style display name, as `SHOW transaction_isolation`
1054    /// would return it. v7.39 (round 770, F31 tranche 6 #154) — PG
1055    /// KEEPS the "read uncommitted" label (measured: `BEGIN ISOLATION
1056    /// LEVEL READ UNCOMMITTED; SHOW transaction_isolation` answers
1057    /// `read uncommitted`) and only BEHAVES as read committed; the old
1058    /// fold renamed the label too.
1059    pub fn as_pg_str(self) -> &'static str {
1060        match self {
1061            Self::ReadUncommitted => "read uncommitted",
1062            Self::ReadCommitted => "read committed",
1063            Self::RepeatableRead => "repeatable read",
1064            Self::Serializable => "serializable",
1065        }
1066    }
1067}
1068
1069impl core::fmt::Display for IsolationLevel {
1070    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1071        f.write_str(self.as_pg_str())
1072    }
1073}
1074
1075/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
1076/// single fixed-shape DDL; the WITH-clause options PG supports
1077/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
1078/// scope for v6.1.4 — `enabled` defaults to true and there are
1079/// no other knobs to set in v6.1.x.
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct CreateSubscriptionStatement {
1082    pub name: String,
1083    /// Connection string in PG keyword=value form (e.g.
1084    /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
1085    /// `host` and `port` fields; the rest is reserved for
1086    /// future v6.1.x options.
1087    pub conn_str: String,
1088    /// One or more publications on the remote side. Order is
1089    /// preserved verbatim from the DDL; the worker requests them
1090    /// in this order. v6.1.4 records the list; v6.1.5
1091    /// publisher-side filtering enforces it.
1092    pub publications: Vec<String>,
1093}
1094
1095/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
1096#[derive(Debug, Clone, PartialEq, Eq)]
1097pub struct CreateSequenceStatement {
1098    pub name: String,
1099    pub if_not_exists: bool,
1100    pub temporary: bool,
1101    /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
1102    pub data_type: Option<SequenceDataType>,
1103    pub options: SequenceOptions,
1104}
1105
1106/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
1107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1108pub enum SequenceDataType {
1109    SmallInt,
1110    Int,
1111    BigInt,
1112}
1113
1114/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
1115/// All fields are optional. `min_value`/`max_value` carry
1116/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
1117#[derive(Debug, Clone, Default, PartialEq, Eq)]
1118pub struct SequenceOptions {
1119    pub increment: Option<i64>,
1120    pub min_value: Option<SeqBound>,
1121    pub max_value: Option<SeqBound>,
1122    pub start: Option<i64>,
1123    /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
1124    /// RESTART, `Some(Some(n))` = RESTART WITH n.
1125    pub restart: Option<Option<i64>>,
1126    pub cache: Option<i64>,
1127    pub cycle: Option<bool>,
1128    pub owned_by: Option<SequenceOwnedBy>,
1129}
1130
1131/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
1132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1133pub enum SeqBound {
1134    Value(i64),
1135    NoBound,
1136}
1137
1138/// v7.17.0 — `OWNED BY {table.col | NONE}`.
1139#[derive(Debug, Clone, PartialEq, Eq)]
1140pub enum SequenceOwnedBy {
1141    None,
1142    Column { table: String, column: String },
1143}
1144
1145/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
1146#[derive(Debug, Clone, PartialEq)]
1147pub struct CreateMaterializedViewStatement {
1148    pub name: String,
1149    pub if_not_exists: bool,
1150    /// Optional `(col, col, …)` rename list. Applies to the
1151    /// backing table at CREATE / REFRESH time.
1152    pub columns: Vec<String>,
1153    /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
1154    /// the cached rows.
1155    pub body: SelectStatement,
1156    /// `WITH DATA` (default) = materialise the rows at CREATE
1157    /// time. `WITH NO DATA` = create an empty backing table;
1158    /// callers must REFRESH before SELECT returns rows.
1159    pub with_data: bool,
1160    /// v7.38 (read01 P6.49) — when true this node came from
1161    /// `CREATE TABLE … AS <select>` (CTAS) / `SELECT … INTO`, so the
1162    /// executor creates a plain table and does NOT register it in the
1163    /// materialized-view registry (no REFRESH semantics).
1164    pub as_plain_table: bool,
1165    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE … AS <select>`. Only
1166    /// meaningful together with `as_plain_table`; the executor puts the
1167    /// resulting table in the creating session's namespace.
1168    pub temporary: bool,
1169}
1170
1171/// v7.39 (read01 round 132) — `WITH [LOCAL | CASCADED] CHECK OPTION` on an
1172/// auto-updatable view. `Cascaded` is PG's default when the bare
1173/// `WITH CHECK OPTION` is written.
1174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1175pub enum ViewCheckOption {
1176    Local,
1177    Cascaded,
1178}
1179
1180/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
1181#[derive(Debug, Clone, PartialEq)]
1182pub struct CreateViewStatement {
1183    pub name: String,
1184    pub or_replace: bool,
1185    pub if_not_exists: bool,
1186    pub temporary: bool,
1187    /// Optional `(col, col, …)` rename list. When non-empty,
1188    /// these override the body's projected column names per-
1189    /// position at SELECT-from-view time.
1190    pub columns: Vec<String>,
1191    /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
1192    /// time to materialise the view as a synthetic CTE.
1193    pub body: SelectStatement,
1194    /// v7.39 (round 132) — `WITH CHECK OPTION`. When set, a write through this
1195    /// view whose resulting row fails the view's WHERE is rejected (SQLSTATE
1196    /// 44000). `None` = no check option.
1197    pub check_option: Option<ViewCheckOption>,
1198}
1199
1200/// v7.17.0 — `ALTER SEQUENCE` AST node.
1201#[derive(Debug, Clone, PartialEq, Eq)]
1202pub struct AlterSequenceStatement {
1203    pub name: String,
1204    pub if_exists: bool,
1205    pub options: SequenceOptions,
1206    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`. Set
1207    /// instead of `options`; the two forms are mutually exclusive in PG.
1208    pub rename_to: Option<String>,
1209}
1210
1211/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
1212/// the [`PublicationScope`] shape. v6.1.2 only accepted
1213/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
1214/// variants by flipping the parser gate (no AST migration).
1215#[derive(Debug, Clone, PartialEq, Eq)]
1216pub struct CreatePublicationStatement {
1217    pub name: String,
1218    pub scope: PublicationScope,
1219}
1220
1221/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
1222/// flips the parser gate for the `ForTables` / `AllTablesExcept`
1223/// variants — the on-disk shape, snapshot serialisation, and the
1224/// AST round-trip Display path were already in place in v6.1.2
1225/// so this is a parser-only widening.
1226#[derive(Debug, Clone, PartialEq, Eq)]
1227pub enum PublicationScope {
1228    AllTables,
1229    ForTables(Vec<String>),
1230    AllTablesExcept(Vec<String>),
1231    /// v7.39 (round 754, F31-B5) — `FOR TABLES IN SCHEMA <name>`
1232    /// (PG 15+). AST-only: the executor folds `public` to
1233    /// [`PublicationScope::AllTables`] (SPG's single-schema world)
1234    /// and refuses any other schema with PG's sentence, so the
1235    /// catalog / serializer / replication filter never see it.
1236    TablesInSchema(String),
1237}
1238
1239#[derive(Debug, Clone, PartialEq, Eq)]
1240pub struct AlterIndexStatement {
1241    pub name: String,
1242    pub target: AlterIndexTarget,
1243}
1244
1245#[derive(Debug, Clone, PartialEq, Eq)]
1246pub enum AlterIndexTarget {
1247    /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
1248    /// rebuilds the existing graph in place without touching the
1249    /// column encoding; `Some(enc)` re-encodes every cell first.
1250    Rebuild { encoding: Option<VecEncoding> },
1251    /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
1252    /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
1253    /// uses it to make the migration idempotent (re-running on a
1254    /// DB where the rename already happened is a no-op rather
1255    /// than an error).
1256    Rename { new: String, if_exists: bool },
1257    /// v7.39 (round 710) — `SET ( option = value, … )` / `RESET ( … )`.
1258    /// Was a SYNTAX ERROR; PG resolves the INDEX first (`relation "x"
1259    /// does not exist`), so the index is validated and the storage
1260    /// parameters no-op (SPG engine-manages them, as ALTER TABLE's
1261    /// SET/RESET arms already record).
1262    StorageParams,
1263}
1264
1265/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
1266/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
1267/// can add more SET subjects without changing the dispatch shape.
1268#[derive(Debug, Clone, PartialEq)]
1269pub struct AlterTableStatement {
1270    pub name: String,
1271    /// v7.13.2 — mailrs round-6 S1. One or more subactions
1272    /// separated by commas in the source SQL. PG-semantic apply
1273    /// is sequential; engine bails on first error (no
1274    /// transactional rollback of completed subactions in v7.13).
1275    /// Single-subaction shape stays a 1-element vec.
1276    pub targets: Vec<AlterTableTarget>,
1277}
1278
1279#[derive(Debug, Clone, PartialEq)]
1280#[allow(clippy::large_enum_variant)]
1281pub enum AlterTableTarget {
1282    /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
1283    ///
1284    /// Both were accepted-and-ignored since v7.37.18, on the reasoning
1285    /// that SPG has no PG-style inheritance. Round 645 gave it one, and
1286    /// the reasoning went stale: `NO INHERIT` reported success while the
1287    /// child stayed attached, which is the worst kind of answer — the
1288    /// statement says it worked and the catalog disagrees.
1289    Inherit { parent: String, detach: bool },
1290    /// Per-table hot-tier byte budget override. The freezer
1291    /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
1292    SetHotTierBytes(u64),
1293    /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
1294    /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
1295    /// Engine validates existing rows against the new constraint
1296    /// before installing it.
1297    AddForeignKey(ForeignKeyConstraint),
1298    /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
1299    /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
1300    /// no-op when no FK with that name exists; otherwise raises.
1301    DropForeignKey { name: String, if_exists: bool },
1302    /// v7.39 (round 431) — MySQL's `ALTER TABLE t DROP {INDEX|KEY} name`,
1303    /// the counterpart of `ADD INDEX`. Lowers to the same catalog action
1304    /// as the standalone `DROP INDEX` statement.
1305    DropIndex { name: String, if_exists: bool },
1306    /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
1307    /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
1308    /// (20 migrate-*.sql hits). Engine appends the column to the
1309    /// schema and back-fills every existing row with the DEFAULT
1310    /// (or NULL when no DEFAULT and the column is nullable).
1311    AddColumn {
1312        column: ColumnDef,
1313        if_not_exists: bool,
1314    },
1315    /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
1316    /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
1317    /// existing row's column value by evaluating the optional
1318    /// USING expression (default `col::<ty>`) and re-coercing
1319    /// against the new column type.
1320    AlterColumnType {
1321        column: String,
1322        new_type: ColumnTypeName,
1323        using: Option<Expr>,
1324        /// v7.39 (round 713) — `COLLATE <name>` between the type and
1325        /// USING. PG re-collates the column, and an ABSENT clause RESETS
1326        /// the collation to the type default (measured round 713) — so
1327        /// `None` is not "leave it alone". The type parser consumed the
1328        /// clause all along and this surface dropped it on the floor:
1329        /// the statement succeeded and the ordering did not change, the
1330        /// silent-divergence shape. Folded variant + the name as written.
1331        collation: Option<(Collation, String)>,
1332    },
1333    /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
1334    /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
1335    /// every row's value at that position is removed; any index
1336    /// on the column is dropped. `if_exists` makes the drop a
1337    /// no-op when the column is missing. `cascade` removes
1338    /// dependents (FKs referencing the column, partial indexes
1339    /// whose predicate names the column); without it, the engine
1340    /// rejects when dependents exist.
1341    DropColumn {
1342        column: String,
1343        if_exists: bool,
1344        cascade: bool,
1345    },
1346    /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
1347    /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
1348    /// CONSTRAINT name CHECK (expr)` — table-level constraints
1349    /// installed post-CREATE-TABLE. pg_dump emits PKs as a
1350    /// separate ALTER TABLE statement, so this surface lets the
1351    /// dump load straight through.
1352    AddTableConstraint(TableConstraint),
1353    /// v7.39 (round 652) — `OWNER TO <role>`. SPG is single-owner, so
1354    /// there is nothing to record; what PG does that SPG did not is
1355    /// REFUSE a role that does not exist. The name has to reach the
1356    /// engine for that, because only the engine knows the roles.
1357    OwnerTo { role: String },
1358    /// v7.39 (round 652) — `CLUSTER ON <index>` and `SET WITHOUT
1359    /// CLUSTER` (the latter as `None`). SPG has no clustered storage, so
1360    /// the hint is still a no-op; naming an index that does not exist is
1361    /// not.
1362    ClusterOn { index: Option<String> },
1363    /// v7.39 (round 652) — `VALIDATE CONSTRAINT <name>`: scan the rows
1364    /// already in the table against a constraint added `NOT VALID` and,
1365    /// if they all pass, mark it validated. It used to be swallowed as a
1366    /// no-op on the theory that SPG validated at ADD time; SPG did not.
1367    ValidateConstraint { name: String },
1368    /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
1369    /// Renames the column in the schema and propagates the rename
1370    /// to every stored source string that references it as a
1371    /// (potentially-qualified) column identifier: CHECK predicates,
1372    /// partial-index predicates, runtime DEFAULT expressions, and
1373    /// triggers' `UPDATE OF` column lists. Function bodies and
1374    /// trigger bodies are NOT auto-rewritten — they're loose
1375    /// source text and may contain references SPG can't statically
1376    /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
1377    /// the column even if dependents exist; users renaming a
1378    /// column referenced by a function body update the function
1379    /// body separately.
1380    RenameColumn { old: String, new: String },
1381    /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
1382    /// Reachable now that the schema stores user-supplied constraint names.
1383    RenameConstraint { old: String, new: String },
1384    /// v7.22 (round-13 T2) — mark a column auto-incrementing.
1385    /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
1386    /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
1387    /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
1388    /// (identity); both lower to this. SPG's auto-increment is
1389    /// max+1-scan based, so the dump's `setval(…)` calls stay
1390    /// no-ops without losing the sequence position.
1391    SetColumnAutoIncrement {
1392        column: String,
1393        /// The implicit sequence pg_dump names for an identity
1394        /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
1395        /// nextval target for a serial default. The engine creates
1396        /// it if absent so the dump's later `setval(s, …)` lands.
1397        seq_name: Option<String>,
1398    },
1399    /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
1400    /// table itself (mailrs round-10 A.5 carve-out — mailrs's
1401    /// migrate-042 uses it). The engine moves the table entry
1402    /// in the catalog under the new name; child catalog state
1403    /// (FKs pointing at this table, triggers watching this
1404    /// table) tracks the rename through the storage layer.
1405    RenameTable { new: String },
1406    /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
1407    /// { ALL | <name> }`. Toggles whether row-level triggers
1408    /// fire on subsequent INSERT/UPDATE/DELETE on the table.
1409    /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
1410    /// ENABLE epilogue around every table's data block so the
1411    /// rows already-computed in prod don't get re-rewritten
1412    /// (and so trigger-driven side effects like
1413    /// audit/queueing don't re-fire during a bulk reload).
1414    /// `which == TriggerSelector::All` toggles every trigger
1415    /// on the table; `Named(name)` toggles one trigger. The
1416    /// engine persists the disabled state on `TriggerDef.enabled`
1417    /// (catalog FILE_VERSION 25+) and the row-write paths skip
1418    /// the trigger when `!enabled`.
1419    SetTriggerEnabled {
1420        which: TriggerSelector,
1421        enabled: bool,
1422    },
1423    /// v7.39 (RLS) — `ALTER TABLE t { ENABLE | DISABLE | FORCE | NO FORCE }
1424    /// ROW LEVEL SECURITY`. `enabled` = Some for ENABLE/DISABLE (sets
1425    /// `relrowsecurity`); `force` = Some for FORCE/NO FORCE (sets
1426    /// `relforcerowsecurity`). Exactly one is `Some` per statement.
1427    SetRowSecurity {
1428        enabled: Option<bool>,
1429        force: Option<bool>,
1430    },
1431    /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child
1432    /// <bounds>`. Promotes an existing table `child` to a partition
1433    /// of `parent` using PG-style `FOR VALUES …` / `DEFAULT` bounds.
1434    /// Engine validates that `child`'s columns are layout-compatible
1435    /// with `parent` and that every row in `child` satisfies the
1436    /// bound before installing the role.
1437    AttachPartition {
1438        child: String,
1439        bounds: PartitionOfBoundsAst,
1440    },
1441    /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
1442    /// child [CONCURRENTLY] [FINALIZE]`. Demotes a partition back
1443    /// to a standalone table (clears `partition_role`) and removes
1444    /// it from the parent's child set. v7.37.16.5: `CONCURRENTLY`
1445    /// is parser-accepted; engine performs the same atomic detach
1446    /// (single-engine, no replication lag — the PG semantics that
1447    /// require the two-phase split don't apply).
1448    DetachPartition {
1449        child: String,
1450        concurrently: bool,
1451        finalize: bool,
1452    },
1453    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col SET DEFAULT
1454    /// <expr>`. Engine re-parses + freezes the literal at this point,
1455    /// matching CREATE TABLE-side default semantics. Volatile shapes
1456    /// (`now()` / `nextval`) take the runtime-default path.
1457    AlterColumnSetDefault { column: String, default_expr: Expr },
1458    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col DROP DEFAULT`.
1459    AlterColumnDropDefault { column: String },
1460    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col SET NOT NULL`.
1461    /// Engine validates that no existing row has NULL in that column
1462    /// before flipping the flag (PG semantics — partial NOT NULL
1463    /// would surface inconsistently).
1464    AlterColumnSetNotNull { column: String },
1465    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col DROP NOT NULL`.
1466    AlterColumnDropNotNull { column: String },
1467    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN col RESTART
1468    /// [WITH n]` on an identity column (`None` = bare RESTART, from the
1469    /// column's start value = 1). Engine records a next-value floor over
1470    /// SPG's max+1 identity allocation.
1471    AlterColumnRestart { column: String, with: Option<i64> },
1472    /// v7.38 (read01 U10) — `ALTER TABLE … ALTER COLUMN col DROP
1473    /// EXPRESSION` turns a stored generated column into a plain column
1474    /// (its generation expression is removed; existing values are kept).
1475    AlterColumnDropExpression { column: String, if_exists: bool },
1476    /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
1477    /// de-generate an identity column into a plain column.
1478    AlterColumnDropIdentity { column: String, if_exists: bool },
1479    /// v7.38 (read01 U12) — `ALTER TABLE … ALTER COLUMN col SET
1480    /// EXPRESSION AS (expr)` (PG 17) changes a stored generated column's
1481    /// expression and recomputes every existing row.
1482    AlterColumnSetExpression { column: String, expr: Expr },
1483    /// v7.39 (round 710) — `OF <type>` / the type half of the typed-table
1484    /// binding. The BINDING stays a no-op (recorded); the TYPE must exist
1485    /// (PG: `type "x" does not exist`).
1486    OfType { type_name: String },
1487    /// v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`. The
1488    /// identity setting no-ops (SPG has no logical replication consumer);
1489    /// the INDEX must exist on this table (PG: `index "i" for table "t"
1490    /// does not exist`).
1491    ReplicaIdentityUsingIndex { index: String },
1492}
1493
1494/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
1495/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
1496/// modifiers; v7.16.1 ships the two shapes pg_dump actually
1497/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
1498/// shouldn't surface from a dump.
1499#[derive(Debug, Clone, PartialEq, Eq)]
1500pub enum TriggerSelector {
1501    /// Every trigger on the table.
1502    All,
1503    /// A specific trigger by name.
1504    Named(String),
1505}
1506
1507/// Each bool mirrors one independent PG `EXPLAIN (…)` option (ANALYZE,
1508/// SUGGEST, COSTS OFF, BUFFERS, TIMING OFF, …); they compose freely, so a
1509/// bitflags word or a nested options struct would only relocate the lint
1510/// while making the option each caller sets harder to read.
1511#[allow(clippy::struct_excessive_bools)]
1512#[derive(Debug, Clone, PartialEq)]
1513pub struct ExplainStatement {
1514    pub analyze: bool,
1515    /// v7.39 (round 225) — widened from SelectStatement so EXPLAIN
1516    /// INSERT/UPDATE/DELETE parses (PG explains DML); the engine renders
1517    /// `Insert on / Update on / Delete on` trees for them.
1518    pub inner: Box<Statement>,
1519    /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
1520    /// advisor pass: after the regular plan tree, the engine
1521    /// emits one suggestion line per column referenced in the
1522    /// query's WHERE / JOIN that has no covering index on the
1523    /// owning table.
1524    pub suggest: bool,
1525    /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
1526    /// `elapsed=…us` annotations from the Total line (and any
1527    /// future cost-bearing lines). PG-standard option used by
1528    /// regression suites and diff-friendly EXPLAIN output. When
1529    /// `true`, takes precedence over the per-session
1530    /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
1531    pub costs_off: bool,
1532    /// v7.37.22 (22.7) — `EXPLAIN (BUFFERS) <SELECT>`. PG-standard
1533    /// option that surfaces hot/cold/shared block counters. SPG's
1534    /// hot-tier scan path counts examined rows; the BUFFERS option
1535    /// makes that an explicit per-operator annotation.
1536    pub buffers: bool,
1537    /// v7.37.22 (22.7) — `EXPLAIN (TIMING [ON|OFF]) <SELECT>`. PG
1538    /// uses this to disable per-operator timing while still
1539    /// emitting actual-row counts (cheaper than ANALYZE). Default
1540    /// when EXPLAIN ANALYZE is set: TIMING ON. `false` strips the
1541    /// timing portion of the Total line. Decoupled from `costs_off`:
1542    /// PG's COSTS OFF strips estimated cost; TIMING OFF strips
1543    /// measured wall-clock.
1544    pub timing_off: bool,
1545    /// v7.37.22 (22.7) — `EXPLAIN (SETTINGS) <SELECT>`. PG appends
1546    /// modified GUC values to the plan output. SPG emits the
1547    /// session params that diverge from default after the main
1548    /// plan body.
1549    pub settings: bool,
1550    /// v7.37.22 (22.7) — `EXPLAIN (WAL) <SELECT>`. PG counts WAL
1551    /// bytes / records / FPI emitted by the query. SPG's
1552    /// write-side queries (INSERT/UPDATE/DELETE wrapped in EXPLAIN
1553    /// ANALYZE) report against the engine WAL counter delta.
1554    pub wal: bool,
1555    /// v7.39 (round 227) — `EXPLAIN (SUMMARY OFF)` suppresses the trailing
1556    /// `Planning Time:` / `Execution Time:` lines. PG defaults SUMMARY on
1557    /// for ANALYZE and off otherwise; SPG emits them for ANALYZE unless
1558    /// this is set.
1559    pub summary_off: bool,
1560    /// v7.37.23 (23.5) — `EXPLAIN (FORMAT text|json|xml|yaml)`.
1561    /// PG's standard format selector. Default is text. JSON / XML
1562    /// / YAML emit a single-row TEXT result whose body wraps the
1563    /// existing line-per-operator text in the chosen container —
1564    /// PG-compatible just enough for dashboards that parse those
1565    /// container shapes (pgAdmin's JSON path picker, etc.).
1566    pub format: ExplainFormat,
1567}
1568
1569#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1570pub enum ExplainFormat {
1571    #[default]
1572    Text,
1573    Json,
1574    Xml,
1575    Yaml,
1576}
1577
1578/// v7.39 (RLS) — the command a `CREATE POLICY` scopes to. `All` is the default.
1579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1580pub enum PolicyCmd {
1581    All,
1582    Select,
1583    Insert,
1584    Update,
1585    Delete,
1586}
1587
1588/// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
1589/// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`.
1590#[derive(Debug, Clone, PartialEq)]
1591pub struct CreatePolicyStatement {
1592    pub name: String,
1593    pub table: String,
1594    /// `true` = PERMISSIVE (default), `false` = RESTRICTIVE.
1595    pub permissive: bool,
1596    pub cmd: PolicyCmd,
1597    /// Empty = PUBLIC.
1598    pub roles: Vec<String>,
1599    pub using: Option<Expr>,
1600    pub with_check: Option<Expr>,
1601}
1602
1603/// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
1604/// [USING (expr)] [WITH CHECK (expr)] }`. Cannot change PERMISSIVE/RESTRICTIVE
1605/// or the command (matches PG).
1606#[derive(Debug, Clone, PartialEq)]
1607pub struct AlterPolicyStatement {
1608    pub name: String,
1609    pub table: String,
1610    pub rename_to: Option<String>,
1611    pub roles: Option<Vec<String>>,
1612    pub using: Option<Expr>,
1613    pub with_check: Option<Expr>,
1614}
1615
1616/// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
1617#[derive(Debug, Clone, PartialEq, Eq)]
1618pub struct DropPolicyStatement {
1619    pub name: String,
1620    pub table: String,
1621    pub if_exists: bool,
1622}
1623
1624#[derive(Debug, Clone, PartialEq, Eq)]
1625pub struct CreateUserStatement {
1626    pub name: String,
1627    /// Empty when the statement carried no PASSWORD — legal for a bare
1628    /// `CREATE ROLE`, which cannot log in anyway.
1629    pub password: String,
1630    /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
1631    /// the parser; the engine validates against `Role::parse` so a
1632    /// typo lands as a runtime error with a clear message rather than
1633    /// a parse failure.
1634    pub role: String,
1635    /// v7.39 (read01 round 58) — the PG role attributes. `None` = the
1636    /// statement did not say, so the default for its spelling applies:
1637    /// `CREATE USER` is `CREATE ROLE … LOGIN`, `CREATE ROLE` is NOLOGIN;
1638    /// both default to INHERIT and NOSUPERUSER.
1639    pub login: Option<bool>,
1640    pub inherit: Option<bool>,
1641    pub superuser: Option<bool>,
1642    /// `true` when spelled `CREATE USER` (LOGIN by default).
1643    pub is_user: bool,
1644}
1645
1646/// v7.39 (round 322, V46) — PG's function volatility class. Declarative:
1647/// it tells the planner how far a call may be moved or folded. SPG records
1648/// it faithfully (`pg_proc.provolatile`, `pg_get_functiondef`) and does not
1649/// yet exploit it for constant folding.
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1651pub enum FunctionVolatility {
1652    Immutable,
1653    Stable,
1654    #[default]
1655    Volatile,
1656}
1657
1658impl FunctionVolatility {
1659    /// PG's one-character `pg_proc.provolatile` code.
1660    #[must_use]
1661    pub const fn as_pg_char(self) -> &'static str {
1662        match self {
1663            Self::Immutable => "i",
1664            Self::Stable => "s",
1665            Self::Volatile => "v",
1666        }
1667    }
1668
1669    #[must_use]
1670    pub const fn as_sql(self) -> &'static str {
1671        match self {
1672            Self::Immutable => "IMMUTABLE",
1673            Self::Stable => "STABLE",
1674            Self::Volatile => "VOLATILE",
1675        }
1676    }
1677}
1678
1679/// v7.39 (round 322, V46) — PG's parallel-safety class.
1680#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1681pub enum FunctionParallel {
1682    #[default]
1683    Unsafe,
1684    Restricted,
1685    Safe,
1686}
1687
1688impl FunctionParallel {
1689    /// PG's one-character `pg_proc.proparallel` code.
1690    #[must_use]
1691    pub const fn as_pg_char(self) -> &'static str {
1692        match self {
1693            Self::Unsafe => "u",
1694            Self::Restricted => "r",
1695            Self::Safe => "s",
1696        }
1697    }
1698
1699    #[must_use]
1700    pub const fn as_sql(self) -> &'static str {
1701        match self {
1702            Self::Unsafe => "PARALLEL UNSAFE",
1703            Self::Restricted => "PARALLEL RESTRICTED",
1704            Self::Safe => "PARALLEL SAFE",
1705        }
1706    }
1707}
1708
1709/// v7.39 (round 322, V46) — the attribute clauses `CREATE FUNCTION` accepts
1710/// on either side of its body. Defaults are PG's: VOLATILE, called on null
1711/// input, SECURITY INVOKER, not leakproof, PARALLEL UNSAFE, and the
1712/// language's default cost / rows.
1713#[derive(Debug, Clone, Copy, PartialEq, Default)]
1714pub struct FunctionAttrs {
1715    pub volatility: FunctionVolatility,
1716    /// `STRICT` / `RETURNS NULL ON NULL INPUT`: a call with any NULL
1717    /// argument returns NULL without running the body.
1718    pub strict: bool,
1719    pub security_definer: bool,
1720    pub leakproof: bool,
1721    pub parallel: FunctionParallel,
1722    /// `COST n` — `None` leaves PG's per-language default.
1723    pub cost: Option<f64>,
1724    /// `ROWS n` — set-returning functions only; `None` = default.
1725    pub rows: Option<f64>,
1726}
1727
1728impl FunctionAttrs {
1729    /// The attribute words `pg_get_functiondef` puts on their own line,
1730    /// in PG's order (measured on 18.4: volatility, PARALLEL, STRICT,
1731    /// SECURITY DEFINER, LEAKPROOF, COST, ROWS). Empty when everything is
1732    /// at its default — PG then emits no such line at all.
1733    #[must_use]
1734    pub fn render_words(&self) -> alloc::vec::Vec<alloc::string::String> {
1735        let mut out = alloc::vec::Vec::new();
1736        if self.volatility != FunctionVolatility::Volatile {
1737            out.push(alloc::string::String::from(self.volatility.as_sql()));
1738        }
1739        if self.parallel != FunctionParallel::Unsafe {
1740            out.push(alloc::string::String::from(self.parallel.as_sql()));
1741        }
1742        if self.strict {
1743            out.push(alloc::string::String::from("STRICT"));
1744        }
1745        if self.security_definer {
1746            out.push(alloc::string::String::from("SECURITY DEFINER"));
1747        }
1748        if self.leakproof {
1749            out.push(alloc::string::String::from("LEAKPROOF"));
1750        }
1751        if let Some(c) = self.cost {
1752            out.push(alloc::format!("COST {}", render_attr_number(c)));
1753        }
1754        if let Some(r) = self.rows {
1755            out.push(alloc::format!("ROWS {}", render_attr_number(r)));
1756        }
1757        out
1758    }
1759}
1760
1761/// PG prints a whole-numbered cost / rows without a decimal point.
1762fn render_attr_number(v: f64) -> alloc::string::String {
1763    // no_std: `f64::fract` lives in std, so compare against the truncation.
1764    let whole = v as i64;
1765    if v.abs() < 1e15 && (whole as f64) == v {
1766        alloc::format!("{whole}")
1767    } else {
1768        alloc::format!("{v}")
1769    }
1770}
1771
1772/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
1773/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
1774/// (the row-level trigger body the CREATE TRIGGER below references).
1775/// Non-trigger user-defined functions parse but error at execution
1776/// time with a clear unsupported message; that surface lands in
1777/// v7.12.5+.
1778#[derive(Debug, Clone, PartialEq)]
1779pub struct CreateFunctionStatement {
1780    pub name: String,
1781    /// `OR REPLACE` was present; an existing function with the
1782    /// same name is overwritten instead of erroring.
1783    pub or_replace: bool,
1784    /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
1785    /// list `()` (sufficient for trigger functions). Other shapes
1786    /// parse and store the args but the executor refuses to call
1787    /// them.
1788    pub args: Vec<FunctionArg>,
1789    /// `RETURNS <type>` — `trigger` is the supported shape for
1790    /// v7.12.4; arbitrary return types parse to
1791    /// [`FunctionReturn::Other`].
1792    pub returns: FunctionReturn,
1793    /// `LANGUAGE <lang>` clause. PG accepts the clause on either
1794    /// side of `AS $$...$$`; the parser canonicalises to one slot.
1795    /// `plpgsql` and `sql` are the two interesting values.
1796    pub language: String,
1797    /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
1798    /// a structured AST; non-trigger / non-plpgsql bodies stay as
1799    /// the raw source text so the v7.12.5+ executor can pick them
1800    /// up without a parser rev.
1801    pub body: FunctionBody,
1802    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
1803    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. PG accepts them
1804    /// on either side of the body; before this they were a parse error, so
1805    /// PG's own `pg_dump` output would not restore.
1806    pub attrs: FunctionAttrs,
1807}
1808
1809/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
1810#[derive(Debug, Clone, PartialEq)]
1811pub struct FunctionArg {
1812    /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
1813    /// (the default); `OUT` / `INOUT` parse but the executor
1814    /// refuses them.
1815    pub mode: FunctionArgMode,
1816    /// Optional arg name. Trigger functions traditionally don't
1817    /// name their args (they read NEW/OLD instead), so `None` is
1818    /// the common case.
1819    pub name: Option<String>,
1820    /// Declared type, normalised to the SPG `DataType` mapping
1821    /// where one exists. Unknown / extension types parse as a
1822    /// raw string under [`FunctionArgType::Raw`].
1823    pub ty: FunctionArgType,
1824}
1825
1826#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1827pub enum FunctionArgMode {
1828    In,
1829    Out,
1830    InOut,
1831}
1832
1833#[derive(Debug, Clone, PartialEq)]
1834pub enum FunctionArgType {
1835    Typed(ColumnTypeName),
1836    /// Unknown / extension types — kept as the parser-side raw
1837    /// identifier so error messages can name them precisely.
1838    Raw(String),
1839}
1840
1841#[derive(Debug, Clone, PartialEq)]
1842pub enum FunctionReturn {
1843    /// `RETURNS TRIGGER` — the row-level trigger function shape.
1844    /// v7.12.4 ships exactly this for execution.
1845    Trigger,
1846    /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
1847    /// the function is unused (since v7.12.4 doesn't ship scalar
1848    /// function invocation).
1849    Void,
1850    /// `RETURNS <type>` for any concrete data type. Reserved for
1851    /// v7.12.5+'s scalar UDF surface.
1852    Type(ColumnTypeName),
1853    /// `RETURNS <ident>` for types SPG doesn't know — extension
1854    /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
1855    Other(String),
1856}
1857
1858#[derive(Debug, Clone, PartialEq)]
1859pub enum FunctionBody {
1860    /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
1861    /// trigger-function executor walks this directly without
1862    /// re-parsing.
1863    PlPgSql(PlPgSqlBlock),
1864    /// Raw source text — parser couldn't (or didn't try to)
1865    /// structure-parse the body. Used for `LANGUAGE sql`
1866    /// functions and any PL/pgSQL body that contains v7.12.5+
1867    /// features the v7.12.4 parser doesn't yet recognise. The
1868    /// executor returns an unsupported error when invoked.
1869    Raw(String),
1870}
1871
1872/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
1873/// from assignment + return to a real-PL/pgSQL surface:
1874/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
1875/// control flow, `RAISE` diagnostics, and embedded SQL
1876/// statements that execute through the regular engine path.
1877/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
1878/// which mailrs's trigger doesn't need but other PG customers
1879/// may; deferred to a future minor release.
1880#[derive(Debug, Clone, PartialEq)]
1881pub struct PlPgSqlBlock {
1882    /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
1883    /// preceding `BEGIN`. Empty when the body opens directly with
1884    /// `BEGIN`. Declarations execute in order; each may reference
1885    /// earlier-declared locals in its init expression.
1886    pub declarations: Vec<PlPgSqlDeclare>,
1887    pub statements: Vec<PlPgSqlStmt>,
1888    /// v7.37.20 (20.10) — `EXCEPTION WHEN <cond> [OR <cond>...] THEN
1889    /// <body>` handlers appended to the block. Empty when no
1890    /// EXCEPTION clause is present. When a body statement raises
1891    /// (via RAISE EXCEPTION, ASSERT falsy, or a runtime error),
1892    /// handlers are tried in order; the first matching condition
1893    /// runs its body and the block terminates cleanly. `OTHERS`
1894    /// matches any exception. Unhandled exceptions propagate.
1895    pub exception_handlers: Vec<ExceptionHandler>,
1896}
1897
1898/// v7.37.20 (20.10) — one `WHEN <cond> [OR <cond>...] THEN <body>`
1899/// arm inside an EXCEPTION block.
1900#[derive(Debug, Clone, PartialEq)]
1901pub struct ExceptionHandler {
1902    /// Condition names (`OTHERS`, `unique_violation`, etc.). Multiple
1903    /// conditions joined by `OR` share one handler body.
1904    pub conditions: Vec<String>,
1905    /// Statements to run when a matching exception is caught.
1906    pub body: Vec<PlPgSqlStmt>,
1907}
1908
1909/// v7.12.6 — single `DECLARE` entry: variable name + declared
1910/// type + optional initialiser. Variables default to SQL NULL
1911/// when no init is given (matches PG).
1912#[derive(Debug, Clone, PartialEq)]
1913pub struct PlPgSqlDeclare {
1914    pub name: String,
1915    /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
1916    /// knows it; raw text otherwise).
1917    pub ty: FunctionArgType,
1918    pub default: Option<Expr>,
1919}
1920
1921#[derive(Debug, Clone, PartialEq)]
1922pub enum PlPgSqlStmt {
1923    /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
1924    /// for clarity in error reporting (PG also forbids it) — the
1925    /// executor errors with a clear "OLD is read-only" message.
1926    Assign { target: AssignTarget, value: Expr },
1927    /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
1928    /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
1929    /// the SELECT statement with the INTO clause stripped; the
1930    /// engine runs it via `Engine::execute`, takes the first
1931    /// row's first column, and assigns to the local variable
1932    /// in the DECLARE scope. Single-column / single-row
1933    /// queries only at v7.16.2; multi-target (`INTO a, b`) is
1934    /// a v7.16.x follow-up.
1935    SelectInto {
1936        var: String,
1937        body: Box<SelectStatement>,
1938    },
1939    /// `RETURN <target>;` — trigger functions canonically return
1940    /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
1941    /// expression for forward compatibility with scalar UDFs.
1942    Return(ReturnTarget),
1943    /// v7.39 (read01 round 66) — `RETURN NEXT <expr>;`: append one row to the
1944    /// set a SETOF function is building, and KEEP GOING. Not a return.
1945    ReturnNext(Expr),
1946    /// v7.39 (read01 round 66) — `RETURN QUERY <select>;`: append every row the
1947    /// query yields, and keep going. It used to desugar to a side-effect
1948    /// statement whose result was DISCARDED — in a SETOF function that is the
1949    /// whole answer thrown away.
1950    ReturnQuery(Box<SelectStatement>),
1951    /// v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the dynamic
1952    /// twin. Its rows go to the set too; it used to run and discard them.
1953    ReturnQueryExecute { sql: Expr },
1954    /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
1955    /// [ELSE body] END IF;`. Branches are tried in order; first
1956    /// truthy condition wins; the optional ELSE runs when no
1957    /// condition matched.
1958    If {
1959        branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
1960        else_branch: Vec<PlPgSqlStmt>,
1961    },
1962    /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
1963    /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
1964    /// (logging — observable side effect only) or `EXCEPTION`
1965    /// (aborts the trigger and propagates as an error). v7.12.6
1966    /// supports the basic format-string substitution PG uses
1967    /// (`%` placeholders consumed positionally).
1968    Raise {
1969        level: RaiseLevel,
1970        message: String,
1971        args: Vec<Expr>,
1972    },
1973    /// v7.12.6 — embedded SQL statement inside the trigger body
1974    /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
1975    /// NEW.col / OLD.col references inside the embedded
1976    /// statement's expression tree are substituted with the
1977    /// current trigger context before the engine re-executes the
1978    /// statement. Recursion depth into nested triggers is
1979    /// bounded by the engine's existing trigger-fire guard.
1980    EmbeddedSql(Box<Statement>),
1981    /// v7.37.20 (20.14) — `ASSERT <condition> [, <message>];`. If
1982    /// the condition evaluates falsy the trigger / DO block aborts
1983    /// with the message (defaulting to a generic shape when none
1984    /// is provided). Same propagation shape as `RAISE EXCEPTION`
1985    /// — the error reaches the caller's query path. PG's behaviour
1986    /// is identical except for a `plpgsql.check_asserts` GUC that
1987    /// can disable the check globally; SPG always evaluates.
1988    Assert {
1989        condition: Expr,
1990        message: Option<Expr>,
1991    },
1992    /// v7.37.20 (20.3) — `WHILE <condition> LOOP <body> END LOOP;`.
1993    /// Iterate the body while condition evaluates truthy. Iteration
1994    /// count is bounded by `WHILE_LOOP_BUDGET` to prevent runaway
1995    /// loops; the executor errors out when reached. EXIT / CONTINUE
1996    /// inside the body queue with 20.2.
1997    While {
1998        condition: Expr,
1999        body: Vec<PlPgSqlStmt>,
2000    },
2001    /// v7.37.20 (20.4) — `FOR <var> IN [REVERSE] <start>..<end> LOOP
2002    /// <body> END LOOP;`. Integer iteration; `var` is BigInt-valued;
2003    /// bounds inclusive on both sides. REVERSE walks backward.
2004    /// Iteration budget guards runaway.
2005    ForRange {
2006        var: String,
2007        start: Expr,
2008        end: Expr,
2009        reverse: bool,
2010        body: Vec<PlPgSqlStmt>,
2011    },
2012    /// v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`. Runs the body
2013    /// repeatedly; only `EXIT [WHEN <cond>]` breaks out. Iteration
2014    /// budget guards runaway.
2015    Loop { body: Vec<PlPgSqlStmt> },
2016    /// v7.37.20 (20.2) — `EXIT [WHEN <condition>];` inside a loop.
2017    /// Unconditional (no WHEN) or conditional (only breaks when
2018    /// condition is truthy). Bubbles up as BodyOutcome::Break which
2019    /// the enclosing loop catches. Outside a loop it's a no-op.
2020    Exit { when: Option<Expr> },
2021    /// v7.37.20 (20.2) — `CONTINUE [WHEN <condition>];` inside a
2022    /// loop. Same shape as EXIT but bubbles up as BodyOutcome::Continue
2023    /// which the enclosing loop catches, skipping the remainder of
2024    /// the body and jumping to the next iteration.
2025    Continue { when: Option<Expr> },
2026    /// v7.37.20 (20.13) — `EXECUTE <string_expr>;` runs a runtime-
2027    /// computed SQL statement. The expression is evaluated to a
2028    /// text value, the resulting string is parsed and dispatched
2029    /// through the engine like an EmbeddedSql. USING <param_list>
2030    /// for placeholder binding queues with v7.40 PL/pgSQL epic.
2031    ExecuteDynamic { sql: Expr },
2032    /// v7.37.20 (20.5) — `FOR <var> IN <select_body> LOOP <body>
2033    /// END LOOP;`. Runs the SELECT once, iterates the resulting
2034    /// rows, binds the first column of each row to `var` as a
2035    /// scalar Value, then runs the body per iteration. EXIT /
2036    /// CONTINUE / ASSERT / RAISE etc. propagate through the
2037    /// enclosing loop's BodyOutcome discipline the same way
2038    /// FOR range and WHILE do. Full record-binding (var as
2039    /// composite carrying all columns) queues with v7.40 record
2040    /// type infrastructure.
2041    ForQuery {
2042        var: String,
2043        query: Box<SelectStatement>,
2044        body: Vec<PlPgSqlStmt>,
2045    },
2046    /// v7.37.20 (20.6) — `FOR <var> IN EXECUTE <string_expr> LOOP
2047    /// <body> END LOOP;`. Same shape as ForQuery but the SELECT is
2048    /// computed at runtime from a text expression, parsed on the
2049    /// fly, then iterated. Enables dynamic queries where the
2050    /// projection / FROM / WHERE clauses depend on runtime values.
2051    ForExecute {
2052        var: String,
2053        sql_expr: Expr,
2054        body: Vec<PlPgSqlStmt>,
2055    },
2056}
2057
2058#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2059pub enum RaiseLevel {
2060    /// `RAISE NOTICE` — diagnostic message, observable in the
2061    /// server log. Does not affect the trigger's outcome.
2062    Notice,
2063    /// `RAISE WARNING` — like NOTICE, slightly louder severity.
2064    Warning,
2065    /// `RAISE INFO` — like NOTICE, slightly quieter.
2066    Info,
2067    /// `RAISE LOG` — like NOTICE, lower priority.
2068    Log,
2069    /// `RAISE DEBUG` — like NOTICE, lowest priority.
2070    Debug,
2071    /// `RAISE EXCEPTION` — aborts the trigger function with the
2072    /// given message, propagating up to the caller as a query-
2073    /// level error.
2074    Exception,
2075}
2076
2077#[derive(Debug, Clone, PartialEq)]
2078pub enum AssignTarget {
2079    NewColumn(String),
2080    OldColumn(String),
2081    /// Reserved for v7.12.5 DECLARE'd local variables.
2082    Local(String),
2083}
2084
2085#[derive(Debug, Clone, PartialEq)]
2086pub enum ReturnTarget {
2087    /// `RETURN NEW;` — for BEFORE triggers, this is the row that
2088    /// actually gets written (possibly with NEW.col mutations
2089    /// applied). For AFTER triggers, the return value is ignored.
2090    New,
2091    /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
2092    /// the delete proceed; for BEFORE UPDATE / INSERT it's
2093    /// equivalent to dropping the write.
2094    Old,
2095    /// `RETURN NULL;` — for BEFORE triggers, skips the write
2096    /// entirely. For AFTER, the return value is ignored.
2097    Null,
2098    /// `RETURN <expr>;` — non-row return shape; reserved for the
2099    /// scalar UDF surface in v7.12.5+. Executor errors when used
2100    /// inside a trigger function.
2101    Expr(Expr),
2102}
2103
2104/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
2105/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
2106/// but the executor refuses them. `WHEN (cond)` clauses are out
2107/// of scope; the trigger function can short-circuit on a leading
2108/// IF inside its body once v7.12.5 lands IF.
2109#[derive(Debug, Clone, PartialEq)]
2110pub struct CreateTriggerStatement {
2111    pub name: String,
2112    pub or_replace: bool,
2113    pub timing: TriggerTiming,
2114    /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
2115    /// three entries in order.
2116    pub events: Vec<TriggerEvent>,
2117    pub table: String,
2118    /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
2119    /// only `Row`; `Statement` parses but the executor refuses.
2120    pub for_each: TriggerForEach,
2121    /// Name of the function to invoke. The function must exist at
2122    /// CREATE TRIGGER time — PG18-measured (round 753): PG refuses a
2123    /// forward reference (`function no_such_fn() does not exist`), so
2124    /// requiring it IS the PG behaviour (the old note claimed the
2125    /// opposite).
2126    pub function: String,
2127    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
2128    /// (mailrs round-5 G7). Non-empty only when the events list
2129    /// contains UPDATE and the user wrote the column-list filter.
2130    /// PG fires the trigger only when at least one of these
2131    /// columns appears in the SET clause; SPG conservatively
2132    /// fires on any UPDATE matching the listed columns or
2133    /// rewriting them at the row level. Empty vec = no filter
2134    /// (fire on every UPDATE).
2135    pub update_columns: Vec<String>,
2136    /// v7.39 (round 138) — `WHEN ( condition )` row-level filter: the row
2137    /// trigger fires only when the condition (over NEW / OLD) is true. `None`
2138    /// = no WHEN (fire unconditionally). Not allowed on INSTEAD OF triggers.
2139    pub when_condition: Option<Expr>,
2140}
2141
2142/// v7.39 (round 139) — `CREATE RULE` query-rewrite rule AST node.
2143#[derive(Debug, Clone, PartialEq)]
2144pub struct CreateRuleStatement {
2145    pub name: String,
2146    pub or_replace: bool,
2147    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
2148    pub event: String,
2149    pub table: String,
2150    /// `true` = `DO INSTEAD` (replace the operation), `false` = `DO ALSO`
2151    /// (run alongside; PG's default when neither keyword is written).
2152    pub instead: bool,
2153    /// Optional `WHERE ( condition )` — the rule applies only when it holds.
2154    pub when_condition: Option<Expr>,
2155    /// The `DO` commands (over NEW / OLD). Empty = `NOTHING`.
2156    pub commands: Vec<Statement>,
2157}
2158
2159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2160pub enum TriggerTiming {
2161    /// Fires before the row is written; the trigger function's
2162    /// return value (NEW or NULL) decides the row content and
2163    /// whether the write proceeds at all.
2164    Before,
2165    /// Fires after the row is written; the return value is
2166    /// ignored.
2167    After,
2168    /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
2169    /// v7.12.4 (SPG has no updatable-view surface).
2170    InsteadOf,
2171}
2172
2173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2174pub enum TriggerEvent {
2175    Insert,
2176    Update,
2177    Delete,
2178    /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
2179    /// so the trigger never fires.
2180    Truncate,
2181}
2182
2183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2184pub enum TriggerForEach {
2185    Row,
2186    Statement,
2187}
2188
2189/// v7.39 (round 537) — a `CREATE INDEX` key column's ordering clause.
2190///
2191/// SPG's index does not scan in a direction, but `indexdef` reproduces
2192/// the DDL and dropping this made `(a DESC NULLS LAST)` read back as
2193/// `(a)`. `nulls_first` is `None` when the statement did not say, in
2194/// which case PG's default applies — LAST for ascending, FIRST for
2195/// descending, and neither is rendered.
2196#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2197pub struct IndexColumnOrder {
2198    pub descending: bool,
2199    pub nulls_first: Option<bool>,
2200}
2201
2202#[derive(Debug, Clone, PartialEq)]
2203pub struct CreateIndexStatement {
2204    pub name: String,
2205    /// `CREATE INDEX CONCURRENTLY`. SPG builds indexes synchronously
2206    /// either way, so this changes nothing about how the index is made
2207    /// — it is carried because PG refuses the CONCURRENTLY form inside
2208    /// a transaction block and accepts the plain one, and the engine
2209    /// cannot tell them apart without it.
2210    pub concurrently: bool,
2211    /// v7.39 (round 537) — the leading key column's ordering clause,
2212    /// which is the column SPG indexes.
2213    pub key_order: IndexColumnOrder,
2214    /// v7.39 (round 538) — an explicit `COLLATE` on that key, as
2215    /// written. SPG orders text by bytes, so honouring it changes
2216    /// nothing; PG prints it, because an explicitly named collation and
2217    /// the one a column inherits are different objects.
2218    pub key_collation: Option<String>,
2219    pub table: String,
2220    pub column: String,
2221    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2222    /// (PG 15+). Default (`false`) is the SQL-standard NULLS DISTINCT, where
2223    /// any NULL in the key exempts the row from the uniqueness check.
2224    pub nulls_not_distinct: bool,
2225    /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
2226    /// graph for vector kNN); unspecified is the default B-tree index.
2227    pub method: IndexMethod,
2228    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2229    /// index name already exists, instead of raising `DuplicateIndex`.
2230    pub if_not_exists: bool,
2231    /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
2232    /// non-key columns the planner should treat as "covered" by
2233    /// this index when checking whether a query can run as an
2234    /// index-only scan. Empty when no `INCLUDE` clause was given.
2235    pub included_columns: Vec<String>,
2236    /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
2237    /// for which `<expr>` evaluates truthy enter the index;
2238    /// queries whose `WHERE` clause's canonical Display form
2239    /// matches this expression's Display form can be served by the
2240    /// partial index. Stored as a parsed `Expr` so the engine
2241    /// re-uses the existing evaluation path; storage persists the
2242    /// Display form on the catalog snapshot.
2243    pub partial_predicate: Option<Expr>,
2244    /// v6.8.2 — expression-based index. When `Some(expr)`, the
2245    /// index key is the result of `expr` evaluated on each row
2246    /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
2247    /// field still names the *primary* column the expression
2248    /// touches so existing planner shortcuts that resolve a
2249    /// column position stay valid. `None` = plain
2250    /// column-reference index (the legacy shape).
2251    pub expression: Option<Expr>,
2252    /// v7.9.14 — extra column names after the leading column in a
2253    /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
2254    /// planner today still only uses the leading column for index
2255    /// seeks; the extras are tracked verbatim so the same DDL
2256    /// round-trips through WAL replay + catalog snapshot, and so
2257    /// the engine can emit a clear warning at INDEX CREATE time
2258    /// that only the leading column is currently honoured.
2259    /// Composite BTree index keys land in v7.10.
2260    pub extra_columns: Vec<String>,
2261    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2262    /// enforces uniqueness on the indexed key (combined with the
2263    /// `partial_predicate` filter — only rows where the predicate
2264    /// evaluates truthy enter the uniqueness check). Standard SQL
2265    /// and PG's canonical way to express conditional uniqueness.
2266    /// mailrs K1.
2267    pub is_unique: bool,
2268    /// v7.15.0 — operator class on the leading column, when the
2269    /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2270    /// Lower-cased. Most opclasses are still informational; the
2271    /// engine routes on `gin_trgm_ops` specifically to build a
2272    /// trigram-shingle GIN over a TEXT column, and otherwise
2273    /// keeps the current "accepted and discarded" behaviour for
2274    /// pg_dump compatibility.
2275    pub opclass: Option<String>,
2276}
2277
2278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2279pub enum IndexMethod {
2280    /// Default — B-tree over `IndexKey`. Used for equality / range
2281    /// lookups on scalar columns.
2282    BTree,
2283    /// `USING hnsw` — NSW graph for kNN over a vector column.
2284    Hnsw,
2285    /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2286    /// metadata that records (min_key, max_key) for each page in a
2287    /// cold-tier segment, on the indexed column. The optimizer
2288    /// can use these summaries to skip pages whose range does NOT
2289    /// overlap a query's WHERE predicate. BRIN indexes carry no
2290    /// in-memory data — the summaries live in the segment v2
2291    /// envelope's sidecar. Created via the standard
2292    /// `CREATE INDEX … USING brin (col)` syntax.
2293    Brin,
2294    /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2295    /// column. Posting lists map `lexeme word` → row locators; the
2296    /// planner uses them to narrow `WHERE col @@ tsquery` to the
2297    /// candidate rows whose vectors contain a matching term, then
2298    /// re-evaluates the full `@@` semantics on each candidate.
2299    /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2300    /// silently degraded to a full scan at query time.
2301    Gin,
2302}
2303
2304/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2305/// inside a CREATE TABLE column list.
2306///
2307/// The source table's shape can only be read from the catalog, so the
2308/// parser records the clause and the engine expands it. `at` is how many
2309/// explicit columns preceded it: PG keeps the written order, so
2310/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2311#[derive(Debug, Clone, PartialEq)]
2312pub struct LikeSpec {
2313    pub source: String,
2314    pub at: usize,
2315    pub options: LikeOptions,
2316}
2317
2318/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2319/// types and NOT NULL and nothing else — measured on PG18, where a
2320/// copied generated column becomes a plain one and a copied identity
2321/// column loses its identity.
2322#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2323pub struct LikeOptions {
2324    pub defaults: bool,
2325    pub constraints: bool,
2326    pub identity: bool,
2327    pub generated: bool,
2328    pub indexes: bool,
2329    pub comments: bool,
2330}
2331
2332#[derive(Debug, Clone, PartialEq)]
2333pub struct CreateTableStatement {
2334    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2335    /// creating session's own namespace: it shadows a permanent table of the
2336    /// same name, other sessions never see it, and it is dropped when the
2337    /// session ends. A `bool` here lands in the struct's existing padding.
2338    pub temporary: bool,
2339    pub name: String,
2340    pub columns: Vec<ColumnDef>,
2341    /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2342    /// the order written. Empty for a table that has none.
2343    pub like_specs: Vec<LikeSpec>,
2344    /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2345    /// Empty for a table that inherits from nothing. Order matters:
2346    /// the child takes each parent's columns in this order before its
2347    /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2348    pub inherits: Vec<String>,
2349    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2350    /// table name already exists, instead of raising `DuplicateTable`.
2351    pub if_not_exists: bool,
2352    /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2353    /// constraints. Column-level `REFERENCES` (single-column inline
2354    /// form) is normalised into this vec at parse time so the engine
2355    /// sees one uniform list.
2356    pub foreign_keys: Vec<ForeignKeyConstraint>,
2357    /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2358    /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2359    /// Engine resolves each into a BTree index named after the
2360    /// constraint's leading column at CREATE TABLE time; INSERT
2361    /// path enforces composite uniqueness via row scan on the
2362    /// leading column index.
2363    pub table_constraints: Vec<TableConstraint>,
2364    /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2365    /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2366    /// the engine creates a parent table whose own rows stay
2367    /// empty and routes INSERT/SELECT through children. Mutually
2368    /// exclusive with `partition_of` (parser enforces).
2369    pub partition_by: Option<PartitionBySpec>,
2370    /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2371    /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2372    /// the table inherits its column list from `parent` (the
2373    /// parser rejects an explicit column list when this is set);
2374    /// engine routes child rows back to the parent at INSERT.
2375    pub partition_of: Option<PartitionOfSpec>,
2376}
2377
2378/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2379/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2380/// future LIST / HASH without breaking the public AST shape.
2381#[derive(Debug, Clone, PartialEq)]
2382pub struct PartitionBySpec {
2383    pub kind: PartitionKindAst,
2384    /// One or more ident references into the parent's column list.
2385    /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2386    /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2387    /// shape PG-compatible.
2388    pub key_columns: Vec<String>,
2389}
2390
2391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2392pub enum PartitionKindAst {
2393    Range,
2394    /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2395    /// `FOR VALUES IN (lit, lit, …)`.
2396    List,
2397    /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2398    /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2399    Hash,
2400}
2401
2402/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2403/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2404/// or the catch-all `DEFAULT` partition.
2405#[derive(Debug, Clone, PartialEq)]
2406pub struct PartitionOfSpec {
2407    pub parent_name: String,
2408    pub bounds: PartitionOfBoundsAst,
2409}
2410
2411#[derive(Debug, Clone, PartialEq)]
2412pub enum PartitionOfBoundsAst {
2413    /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2414    /// (lits include vector bodies), so we box both bounds to keep
2415    /// the variant size in line with `Default` for clippy and to
2416    /// minimise per-statement footprint when the partition shape
2417    /// isn't in use.
2418    Range {
2419        lower: Box<Expr>,
2420        upper: Box<Expr>,
2421    },
2422    /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2423    /// expr resolves to a typed literal at child-create time.
2424    List {
2425        values: Vec<Expr>,
2426    },
2427    /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2428    /// PG enforces `0 ≤ r < m`; m must be positive.
2429    Hash {
2430        modulus: u32,
2431        remainder: u32,
2432    },
2433    Default,
2434}
2435
2436/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2437/// column list. Either a composite PRIMARY KEY or a UNIQUE
2438/// (single- or multi-column).
2439#[derive(Debug, Clone, PartialEq)]
2440pub enum TableConstraint {
2441    /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2442    /// referenced column. Engine builds a BTree index named
2443    /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2444    PrimaryKey {
2445        name: Option<String>,
2446        columns: Vec<String>,
2447        /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2448        /// Round 621 consumed the clauses; these carry them.
2449        deferrable: bool,
2450        initially_deferred: bool,
2451    },
2452    /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2453    /// named `<table>_<leading_col>_key` (single-column) or
2454    /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2455    /// uniqueness on INSERT.
2456    Unique {
2457        name: Option<String>,
2458        columns: Vec<String>,
2459        /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2460        /// G10). PG 15+ flips the NULL handling so any number of
2461        /// NULL rows collide on the constraint. Default is
2462        /// `false` (NULLS DISTINCT, standard SQL behaviour).
2463        nulls_not_distinct: bool,
2464        /// v7.39 (round 711) — see PrimaryKey.
2465        deferrable: bool,
2466        initially_deferred: bool,
2467    },
2468    /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2469    /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2470    /// this same variant at parse time. Engine evaluates the
2471    /// predicate against each INSERT/UPDATE candidate row; a
2472    /// false / NULL result rejects the mutation.
2473    /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2474    /// PG adds such a constraint without scanning the existing rows: new
2475    /// rows are checked, the ones already there are grandfathered in, and
2476    /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2477    /// scans and flips it. pg_dump emits the suffix for exactly those, so
2478    /// validating them on restore would refuse a dump PG itself produced.
2479    Check {
2480        name: Option<String>,
2481        expr: Expr,
2482        not_valid: bool,
2483    },
2484    /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2485    /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2486    /// every element (the booking/scheduling non-overlap constraint,
2487    /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2488    /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2489    /// enforcement doesn't build the index yet). Each element pairs a
2490    /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2491    Exclude {
2492        name: Option<String>,
2493        method: Option<String>,
2494        elements: Vec<(String, String)>,
2495    },
2496    /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2497    /// non-unique secondary-index declaration inline in CREATE
2498    /// TABLE. Engine builds a BTree index on the leading column
2499    /// (composite columns parse but only the leading column is
2500    /// honoured at v7.15 — matches the existing
2501    /// `CreateIndexStatement::extra_columns` semantics). Useful
2502    /// for `mysql/blog`-style schemas that lean on routine
2503    /// secondary indexes for ORM lookups.
2504    Index {
2505        name: Option<String>,
2506        columns: Vec<String>,
2507    },
2508    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2509    /// (cols)` inline declaration. Pre-v7.17 the parser
2510    /// silently dropped these so MyISAM-imported FULLTEXT
2511    /// indexes vanished; v7.17 routes them through the
2512    /// existing tsvector-GIN engine path so MATCH AGAINST
2513    /// queries get a real inverted index instead of falling
2514    /// back to a full scan. Multi-column FULLTEXT KEYs build
2515    /// one GIN per column at v7.17 (per-column posting lists);
2516    /// the leading column drives query planning.
2517    FulltextIndex {
2518        name: Option<String>,
2519        columns: Vec<String>,
2520    },
2521}
2522
2523#[derive(Debug, Clone, PartialEq)]
2524#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2525pub struct ColumnDef {
2526    pub name: String,
2527    pub ty: ColumnTypeName,
2528    pub nullable: bool,
2529    /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2530    /// evaluates this once (with an empty row) and caches the resulting
2531    /// `Value` on the column schema.
2532    pub default: Option<Expr>,
2533    /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2534    /// per such column and fills the slot when INSERT leaves it
2535    /// unbound (omitted from a column-list INSERT or explicitly NULL).
2536    pub auto_increment: bool,
2537    /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2538    /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2539    /// an implicit BTree index named `<table>_pkey` over this
2540    /// column at CREATE TABLE time, satisfying the parent-side
2541    /// index requirement for any FOREIGN KEY pointing at it.
2542    pub is_primary_key: bool,
2543    /// v7.13.0 — inline `UNIQUE` column constraint
2544    /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2545    /// into a single-column `TableConstraint::Unique` so the
2546    /// engine path stays uniform with table-level UNIQUE.
2547    pub is_unique: bool,
2548    /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2549    /// inline column constraint: treat NULL keys as equal so only one NULL
2550    /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2551    /// `TableConstraint::Unique { nulls_not_distinct }`.
2552    pub unique_nulls_not_distinct: bool,
2553    /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2554    /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2555    /// since this round so the fold into the table-level constraint keeps it.
2556    pub constraint_deferrable: bool,
2557    pub constraint_initially_deferred: bool,
2558    /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2559    /// (mailrs round-5 G3). Stored alongside the column so the
2560    /// CREATE TABLE handler can fold these into table-level
2561    /// CHECK constraints. Multiple inline CHECKs on the same
2562    /// column are concatenated with AND at the table level.
2563    pub check: Option<Expr>,
2564    /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2565    /// parser sees an unknown column-type ident (anything not in
2566    /// the built-in `parse_column_type_name` table), it sets
2567    /// `ty = ColumnTypeName::Text` and records the original name
2568    /// here. The engine resolves at CREATE TABLE time: if a
2569    /// catalog enum/domain with this name exists, the column is
2570    /// bound to it (label-checked on INSERT for enums; CHECK-
2571    /// constrained for domains); otherwise the CREATE TABLE
2572    /// errors with "unknown type".
2573    pub user_type_ref: Option<String>,
2574    /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2575    /// CURRENT_TIMESTAMP` column attribute. When set, an
2576    /// UPDATE that does NOT explicitly bind this column
2577    /// overrides the new value with `now()` (engine clock).
2578    /// Pre-v7.17 SPG silently accepted the syntax and never
2579    /// fired the override — `updated_at` columns from mysqldump
2580    /// stayed pinned at their initial DEFAULT forever, an
2581    /// audit Tier-S silent-failure. Generalised as a stored
2582    /// expression source so future shapes (`ON UPDATE
2583    /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2584    /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2585    pub on_update_runtime: Option<Expr>,
2586    /// v7.17.0 Phase 2.5 — text collation derived from the
2587    /// post-fix `COLLATE <name>` clause (and / or the table-level
2588    /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2589    /// per column). Pre-2.5 SPG accepted the clause and
2590    /// discarded the name, leaving every column byte-compared
2591    /// — a Tier-S silent failure when the customer expected
2592    /// `_ci` / `case_insensitive` semantics. Parser normalises
2593    /// the raw collation name into the variants in `Collation`.
2594    /// Default `Binary` preserves the legacy compare path.
2595    pub collation: Collation,
2596    /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2597    /// explicit `COLLATE <name>` clause rather than the default. Under the
2598    /// MySQL dialect a text column with NO explicit clause takes the
2599    /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2600    /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2601    /// flag is the only thing that tells them apart.
2602    pub collation_explicit: bool,
2603    /// v7.39 (round 676) — the collation name AS WRITTEN, because
2604    /// `collation` above cannot carry it: `Collation` is a two-variant
2605    /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2606    /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2607    /// tell them apart.
2608    pub collation_name: Option<String>,
2609    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2610    /// 4.4 SPG accepted and discarded the keyword, leaving
2611    /// negative values silently accepted on a column the
2612    /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2613    /// rejects negative INSERT / UPDATE values on UNSIGNED int
2614    /// columns. SPG widening to `u64`-shaped storage is out of
2615    /// v7.17 scope; the upper bound remains the signed-type max
2616    /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2617    /// exceeds what every mailrs / Rails app actually uses.
2618    pub is_unsigned: bool,
2619    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2620    /// value list captured at parse time. When `Some`, the parser
2621    /// recognised `ENUM(...)` in the type slot; the engine
2622    /// validates INSERT cells against this list at
2623    /// column_def_to_schema time and persists the variants on
2624    /// `ColumnSchema.inline_enum_variants`. None for all
2625    /// non-ENUM columns.
2626    pub inline_enum_variants: Option<Vec<String>>,
2627    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2628    /// value list. Distinct from ENUM (subset semantics rather
2629    /// than pick-one). None for all non-SET columns.
2630    pub inline_set_variants: Option<Vec<String>>,
2631    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2632    /// STORED` computed-column source. When `Some`, the engine
2633    /// stores the Display-form of the parsed expression on
2634    /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2635    /// and re-evaluates the expression against every INSERT /
2636    /// UPDATE candidate row, overwriting whatever the caller
2637    /// supplied for this column. Boxed to keep `ColumnDef` from
2638    /// blowing past the `large_enum_variant` clippy ceiling
2639    /// (`Expr` widens with vector literals).
2640    pub generated_stored_expr: Option<Box<Expr>>,
2641    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2642    /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2643    /// `auto_increment`; this additionally marks the ALWAYS one, whose
2644    /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2645    /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2646    /// VALUE`. Only meaningful when the column is also an identity column.
2647    pub identity_always: bool,
2648    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2649    /// integer width (TINYINT / MEDIUMINT), captured before the type
2650    /// collapses to SmallInt / Int. The engine copies it to
2651    /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2652    /// path can enforce the real range. None for every other column and
2653    /// under the PG dialect.
2654    pub mysql_int_width: Option<MysqlIntWidth>,
2655    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2656    /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2657    /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2658    /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2659    /// CREATE TABLE time so the write path can truncate and the render path
2660    /// can pad. None under the PG dialect, where temporal columns keep full
2661    /// microseconds.
2662    pub mysql_fsp: Option<u8>,
2663}
2664
2665/// v7.17.0 Phase 2.5 — text collation classification surfaced
2666/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2667/// engine bridges between the two at CREATE TABLE time.
2668///
2669/// Recognised collation-name patterns (case-insensitive):
2670///   * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase`         → CaseInsensitive
2671///   * Everything else (`C`, `POSIX`, `default`,
2672///     `pg_catalog.default`, `*_cs`, `*_bin`, unknown names)   → Binary
2673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2674pub enum Collation {
2675    Binary,
2676    CaseInsensitive,
2677}
2678
2679/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2680/// integer width for a column whose `ColumnTypeName` is too wide to carry
2681/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2682/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2683/// TABLE time. Only recorded under the MySQL dialect.
2684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2685pub enum MysqlIntWidth {
2686    Tiny,
2687    Small,
2688    Medium,
2689    Int,
2690    /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2691    Big,
2692}
2693
2694#[allow(clippy::derivable_impls)]
2695impl Default for Collation {
2696    fn default() -> Self {
2697        Self::Binary
2698    }
2699}
2700
2701impl Collation {
2702    /// Classify a `COLLATE <name>` ident into one of the supported
2703    /// variants. Empty / unknown names fall back to `Binary` —
2704    /// matches the pre-2.5 silent-accept behaviour for snapshots
2705    /// that load through but don't actually depend on the
2706    /// collation semantics.
2707    #[must_use]
2708    pub fn from_collation_name(name: &str) -> Self {
2709        let lc = name.trim().to_ascii_lowercase();
2710        // Strip any quotes / schema-qualifier the parser left on
2711        // (e.g. `pg_catalog.default`).
2712        let bare = lc
2713            .trim_matches(|c: char| c == '"' || c == '\'')
2714            .rsplit('.')
2715            .next()
2716            .unwrap_or("");
2717        if bare.is_empty() {
2718            return Self::Binary;
2719        }
2720        if bare == "case_insensitive" || bare == "nocase" {
2721            return Self::CaseInsensitive;
2722        }
2723        // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2724        // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2725        if bare.ends_with("_ci") {
2726            return Self::CaseInsensitive;
2727        }
2728        Self::Binary
2729    }
2730}
2731
2732/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2733/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2734/// parse into this shape — the column-level form has a single-entry
2735/// `columns` / `parent_columns`.
2736#[derive(Debug, Clone, PartialEq)]
2737pub struct ForeignKeyConstraint {
2738    /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2739    /// today but parses + stores it so a future ALTER TABLE DROP
2740    /// CONSTRAINT can target by name (v7.6.8).
2741    pub name: Option<String>,
2742    /// Local columns participating in the FK (≥ 1).
2743    pub columns: Vec<String>,
2744    /// Referenced parent table.
2745    pub parent_table: String,
2746    /// Referenced parent columns. Must have the same arity as
2747    /// `columns`; engine validates parent has a PK / UNIQUE index
2748    /// on exactly this column set (v7.6.1).
2749    pub parent_columns: Vec<String>,
2750    /// `ON DELETE` action. Defaults to `Restrict` if absent.
2751    pub on_delete: FkAction,
2752    /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2753    pub on_update: FkAction,
2754    /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2755    pub match_type: MatchType,
2756    /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2757    /// dropped on the floor, so a constraint declared DEFERRABLE was
2758    /// enforced immediately and a circular-FK migration could not load.
2759    pub deferrable: bool,
2760    /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2761    /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2762    pub initially_deferred: bool,
2763}
2764
2765/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2766/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2767/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2768#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2769pub enum MatchType {
2770    #[default]
2771    Simple,
2772    Full,
2773}
2774
2775/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2777pub enum FkAction {
2778    /// Reject the parent mutation if any child row references it.
2779    /// SQL spec default; SPG default when no clause is given.
2780    Restrict,
2781    /// Recursively propagate the parent's delete / update to the
2782    /// child rows. Same TX.
2783    Cascade,
2784    /// Set the child FK column(s) to NULL. Requires the FK columns
2785    /// to be NULL-able.
2786    SetNull,
2787    /// Set the child FK column(s) to their declared DEFAULT.
2788    /// Requires the child column(s) to have DEFAULT.
2789    SetDefault,
2790    /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2791    /// `Restrict` because the single-writer model has no deferred
2792    /// constraint window; the keyword is accepted for compatibility.
2793    NoAction,
2794}
2795
2796/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2797/// optional `USING <encoding>` clause; omitting it keeps the
2798/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2799/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2800/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2801/// binary16 (2× compression, ~3 decimal digits of precision).
2802#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2803pub enum VecEncoding {
2804    /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
2805    /// uncompressed `vector` type wire / storage layout.
2806    #[default]
2807    F32,
2808    /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
2809    /// `spg_storage::quantize::Sq8Vector` for the math + recall
2810    /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
2811    /// dim ≥ 32).
2812    Sq8,
2813    /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
2814    /// per-element. DDL keyword `HALF` (pgvector convention).
2815    /// Bit-exact dequantise to f32 at the storage layer; no
2816    /// rerank pass needed for kNN search.
2817    F16,
2818}
2819
2820impl fmt::Display for VecEncoding {
2821    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2822        match self {
2823            Self::F32 => f.write_str("F32"),
2824            Self::Sq8 => f.write_str("SQ8"),
2825            // pgvector convention: DDL keyword is `HALF`, not `F16`.
2826            Self::F16 => f.write_str("HALF"),
2827        }
2828    }
2829}
2830
2831/// SQL-level type names. The mapping to the storage runtime's `DataType`
2832/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
2833#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2834pub enum ColumnTypeName {
2835    /// v7.39 (round 291) — PG's `name`, the identifier type its
2836    /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
2837    /// answered `type "name" does not exist` to.
2838    Name,
2839    /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
2840    /// 32-bit wrapping counter the row header carries; `xid8` is the
2841    /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
2842    /// SPG answered `type "xid" does not exist` to.
2843    Xid,
2844    Xid8,
2845    /// v7.39 (round 667) — `OID`. `XID` was already a column type here
2846    /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
2847    /// `type "oid" does not exist` while `t(x XID)` built fine.
2848    Oid,
2849    SmallInt,
2850    Int,
2851    BigInt,
2852    Float,
2853    /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
2854    /// IEEE. It used to map to [`Self::Float`] on the theory that a
2855    /// wider float is harmless, but the width is observable: a `real`
2856    /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
2857    /// answered false where PG answers true.
2858    Real,
2859    Text,
2860    /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
2861    Varchar(u32),
2862    /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
2863    Char(u32),
2864    Bool,
2865    /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
2866    /// `USING <encoding>` clause; omitting it surfaces as
2867    /// `encoding = VecEncoding::F32` (the pre-v6 default).
2868    Vector {
2869        dim: u32,
2870        encoding: VecEncoding,
2871    },
2872    /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
2873    /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
2874    /// v7.39 (round 271) — scale widened to u16 alongside the value's.
2875    /// v7.39 (round 272) — precision too: PG's runs to 1000.
2876    /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
2877    /// a negative one rounds to tens / hundreds. A VALUE's display scale
2878    /// stays unsigned.
2879    Numeric(u16, i16),
2880    /// `DATE` — calendar day, no time-of-day component.
2881    Date,
2882    /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
2883    /// precision.
2884    Timestamp,
2885    /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
2886    /// stores all timestamps as UTC microseconds-since-epoch and
2887    /// does not carry per-row offset (PG's internal representation
2888    /// is the same — TZ is a display convention). The distinction
2889    /// from `TIMESTAMP` exists for the PG-wire layer to advertise
2890    /// OID 1184 so sqlx-style clients decode into
2891    /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
2892    Timestamptz,
2893    /// v4.9 `JSON` — text-backed JSON document. No parse-time
2894    /// validation; the engine round-trips the literal verbatim.
2895    /// PG OID 114 on the wire.
2896    Json,
2897    /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
2898    /// PG OID 3802 on the wire so sqlx-style binary-typed clients
2899    /// decode without a custom type registration.
2900    Jsonb,
2901    /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
2902    /// Literal forms (decoded by the engine at coercion time):
2903    ///   - PG hex form: `'\xDEADBEEF'`
2904    ///   - Escape form: `'foo\\000bar'` (backslash octal triples)
2905    Bytes,
2906    /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
2907    /// OID 1009. Literal forms accepted by the parser:
2908    ///   - `ARRAY['a', 'b', NULL]`
2909    ///   - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
2910    ///     form at coerce time)
2911    TextArray,
2912    /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
2913    /// 1007. Same literal forms as TEXT[] (substituting integer
2914    /// elements).
2915    IntArray,
2916    /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
2917    /// OID 1016.
2918    BigIntArray,
2919    /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
2920    /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
2921    /// external form). G-CRIT-3.
2922    TsVector,
2923    /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
2924    /// wire OID 3615.
2925    TsQuery,
2926    /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
2927    /// Literal input accepts canonical hyphenated, unhyphenated,
2928    /// uppercase, and `{...}`-braced forms; display normalises to
2929    /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
2930    /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
2931    /// gen_random_uuid()`.
2932    Uuid,
2933    /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
2934    /// microseconds since 00:00:00. PG wire OID 1083. Literal
2935    /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
2936    /// (6-digit microsecond precision). Display normalises to
2937    /// the canonical `HH:MM:SS[.ffffff]`.
2938    Time,
2939    /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
2940    /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
2941    /// PG OID; advertised as INT4 on the wire. Display always
2942    /// 4 digits zero-padded.
2943    Year,
2944    /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
2945    /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
2946    /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
2947    /// Offset range: ±14 hours.
2948    TimeTz,
2949    /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
2950    /// (locale-independent storage). Wire OID 790. Literal input
2951    /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
2952    /// major units), optional leading `-`. Display: en_US locale.
2953    Money,
2954    /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
2955    /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
2956    /// — the engine bridges to `DataType::Range(RangeKind)`.
2957    Range(RangeKindAst),
2958    /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
2959    /// `text => text` map with NULL value support.
2960    Hstore,
2961    /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
2962    IntArray2D,
2963    BigIntArray2D,
2964    TextArray2D,
2965    /// v7.39 (read01 round 75) — `bool[][]`.
2966    BoolArray2D,
2967    /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
2968    /// three-field {months, days, micros} struct (PG-byte-equal),
2969    /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
2970    /// β-P2 `INTERVAL` was runtime-only — literal in expression
2971    /// position but rejected at CREATE TABLE.
2972    Interval,
2973    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
2974    /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
2975    /// PG external form quotes each non-NULL element because
2976    /// interval text contains spaces / colons
2977    /// (`{"1 day","24:00:00",NULL}`).
2978    IntervalArray,
2979    /// v7.37.5 γ — full PG array-of-scalar family. Each variant
2980    /// mirrors a scalar `ColumnTypeName` that already existed.
2981    BoolArray,
2982    SmallIntArray,
2983    FloatArray,
2984    NumericArray,
2985    DateArray,
2986    TimestampArray,
2987    TimestamptzArray,
2988    UuidArray,
2989    JsonArray,
2990    JsonbArray,
2991    BytesArray,
2992    VarcharArray,
2993    CharArray,
2994    /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
2995    /// as `Range(RangeKindAst)` — one column type variant covers
2996    /// all six builtin multiranges, kind pins the element type.
2997    /// Wire OIDs in pgwire.
2998    Multirange(RangeKindAst),
2999    /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3000    /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3001    /// Wire OIDs in pgwire.
3002    Point,
3003    Lseg,
3004    Path,
3005    PgBox,
3006    Polygon,
3007    Line,
3008    Circle,
3009    /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3010    Inet,
3011    Cidr,
3012    Macaddr,
3013    Macaddr8,
3014    /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3015    Bit(u32),
3016    /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3017    BitVarying(u32),
3018    Xml,
3019    Char1,
3020    MoneyArray,
3021}
3022
3023/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3024/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3025/// crate doesn't depend on storage. Bridged at engine boundary.
3026#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3027pub enum RangeKindAst {
3028    Int4,
3029    Int8,
3030    Num,
3031    Ts,
3032    TsTz,
3033    Date,
3034}
3035
3036impl fmt::Display for ColumnTypeName {
3037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3038        match self {
3039            Self::SmallInt => f.write_str("SMALLINT"),
3040            Self::Int => f.write_str("INT"),
3041            Self::BigInt => f.write_str("BIGINT"),
3042            Self::Float => f.write_str("FLOAT"),
3043            Self::Real => f.write_str("REAL"),
3044            Self::Text => f.write_str("TEXT"),
3045            Self::Name => f.write_str("name"),
3046            Self::Xid => f.write_str("xid"),
3047            Self::Xid8 => f.write_str("xid8"),
3048            Self::Oid => f.write_str("oid"),
3049            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3050            Self::Char(n) => write!(f, "CHAR({n})"),
3051            Self::Bool => f.write_str("BOOL"),
3052            Self::Vector { dim, encoding } => match encoding {
3053                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3054                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3055                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3056            },
3057            Self::Json => f.write_str("JSON"),
3058            Self::Jsonb => f.write_str("JSONB"),
3059            Self::Bytes => f.write_str("BYTEA"),
3060            Self::TextArray => f.write_str("TEXT[]"),
3061            Self::IntArray => f.write_str("INT[]"),
3062            Self::BigIntArray => f.write_str("BIGINT[]"),
3063            Self::TsVector => f.write_str("TSVECTOR"),
3064            Self::TsQuery => f.write_str("TSQUERY"),
3065            Self::Uuid => f.write_str("UUID"),
3066            Self::Numeric(p, s) => {
3067                if *s == 0 {
3068                    write!(f, "NUMERIC({p})")
3069                } else {
3070                    write!(f, "NUMERIC({p}, {s})")
3071                }
3072            }
3073            Self::Date => f.write_str("DATE"),
3074            Self::Timestamp => f.write_str("TIMESTAMP"),
3075            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3076            Self::Time => f.write_str("TIME"),
3077            Self::Year => f.write_str("YEAR"),
3078            Self::TimeTz => f.write_str("TIMETZ"),
3079            Self::Money => f.write_str("MONEY"),
3080            Self::Range(k) => f.write_str(match k {
3081                RangeKindAst::Int4 => "INT4RANGE",
3082                RangeKindAst::Int8 => "INT8RANGE",
3083                RangeKindAst::Num => "NUMRANGE",
3084                RangeKindAst::Ts => "TSRANGE",
3085                RangeKindAst::TsTz => "TSTZRANGE",
3086                RangeKindAst::Date => "DATERANGE",
3087            }),
3088            Self::Hstore => f.write_str("HSTORE"),
3089            Self::Interval => f.write_str("INTERVAL"),
3090            Self::IntervalArray => f.write_str("INTERVAL[]"),
3091            Self::BoolArray => f.write_str("BOOL[]"),
3092            Self::SmallIntArray => f.write_str("SMALLINT[]"),
3093            Self::FloatArray => f.write_str("FLOAT[]"),
3094            Self::NumericArray => f.write_str("NUMERIC[]"),
3095            Self::DateArray => f.write_str("DATE[]"),
3096            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3097            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3098            Self::UuidArray => f.write_str("UUID[]"),
3099            Self::JsonArray => f.write_str("JSON[]"),
3100            Self::JsonbArray => f.write_str("JSONB[]"),
3101            Self::BytesArray => f.write_str("BYTEA[]"),
3102            Self::VarcharArray => f.write_str("VARCHAR[]"),
3103            Self::CharArray => f.write_str("CHAR[]"),
3104            Self::Multirange(k) => f.write_str(match k {
3105                RangeKindAst::Int4 => "INT4MULTIRANGE",
3106                RangeKindAst::Int8 => "INT8MULTIRANGE",
3107                RangeKindAst::Num => "NUMMULTIRANGE",
3108                RangeKindAst::Ts => "TSMULTIRANGE",
3109                RangeKindAst::TsTz => "TSTZMULTIRANGE",
3110                RangeKindAst::Date => "DATEMULTIRANGE",
3111            }),
3112            Self::Point => f.write_str("POINT"),
3113            Self::Lseg => f.write_str("LSEG"),
3114            Self::Path => f.write_str("PATH"),
3115            Self::PgBox => f.write_str("BOX"),
3116            Self::Polygon => f.write_str("POLYGON"),
3117            Self::Line => f.write_str("LINE"),
3118            Self::Circle => f.write_str("CIRCLE"),
3119            Self::Inet => f.write_str("INET"),
3120            Self::Cidr => f.write_str("CIDR"),
3121            Self::Macaddr => f.write_str("MACADDR"),
3122            Self::Macaddr8 => f.write_str("MACADDR8"),
3123            Self::Bit(0) => f.write_str("BIT"),
3124            Self::Bit(n) => write!(f, "BIT({n})"),
3125            Self::BitVarying(0) => f.write_str("VARBIT"),
3126            Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3127            Self::Xml => f.write_str("XML"),
3128            Self::Char1 => f.write_str("\"char\""),
3129            Self::MoneyArray => f.write_str("MONEY[]"),
3130            Self::IntArray2D => f.write_str("INT[][]"),
3131            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3132            Self::TextArray2D => f.write_str("TEXT[][]"),
3133            Self::BoolArray2D => f.write_str("BOOL[][]"),
3134        }
3135    }
3136}
3137
3138/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3139/// engine evaluates `expr` per matched row in the table's row order
3140/// and rewrites cells in place. Indexed columns are dropped + re-
3141/// inserted into the affected B-tree on each row change.
3142/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3143/// tail on a DML statement. Boxed off the statement struct so the PG-only
3144/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3145/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3146/// the identical meaning, so both share this one payload rather than each
3147/// growing its own.
3148#[derive(Debug, Clone, PartialEq)]
3149pub struct DmlOrderLimit {
3150    pub order_by: Vec<OrderBy>,
3151    pub limit: Option<u32>,
3152}
3153
3154/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3155/// FROM, kept so the engine can finish the job.
3156///
3157/// The parser rewrites the statement onto correlated subqueries, and it
3158/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3159/// name belongs to the target or to a source needs their column lists,
3160/// which parse time does not have. Carrying the clause lets the engine
3161/// — which has the catalog — resolve the rest.
3162#[derive(Debug, Clone, PartialEq)]
3163pub struct UpdateFromSources {
3164    pub from: FromClause,
3165    pub sub_where: Option<Expr>,
3166}
3167
3168#[derive(Debug, Clone, PartialEq)]
3169pub struct UpdateStatement {
3170    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3171    /// level UPDATE. Empty for a plain UPDATE.
3172    pub ctes: Vec<Cte>,
3173    pub table: String,
3174    /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3175    /// to `t`'s own rows and not to anything that descends from it.
3176    ///
3177    /// Round 644 taught the FROM clause the keyword and left DML behind
3178    /// because it needed a field here, and this struct carries a warning
3179    /// that round 413 measured widening it in place overflowing the
3180    /// parser's nesting stack. That warning was about `from_sources`, a
3181    /// struct wide enough to need boxing; a `bool` lands in the padding
3182    /// already present — same as `CreateTableStatement::temporary`.
3183    ///
3184    /// It also earns its keep beyond the spelling: the inheritance
3185    /// fan-out needs a way to say "the parent's own rows" as a
3186    /// statement, or running one on the parent recurses forever.
3187    pub only: bool,
3188    /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3189    /// statement's expressions refer to the target row by. PG allows the
3190    /// bare spelling here (unlike INSERT, which requires AS).
3191    pub alias: Option<String>,
3192    pub assignments: Vec<(String, Expr)>,
3193    /// v7.39 (round 533) — boxed: round 413 measured that widening this
3194    /// struct in place overflows the parser's nesting stack.
3195    pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3196    pub where_: Option<Expr>,
3197    /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3198    /// mutate the first `limit` rows in the given order. PG has no such
3199    /// clause; the parser accepts it only under the MySQL dialect. Boxed
3200    /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3201    /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3202    /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3203    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3204    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3205    /// clause (legacy CommandComplete path). Some = engine
3206    /// evaluates the projection over each mutated row and
3207    /// streams the result as a Rows QueryResult.
3208    pub returning: Option<Vec<SelectItem>>,
3209}
3210
3211/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3212/// from the active catalog and prunes them from every index.
3213#[derive(Debug, Clone, PartialEq)]
3214pub struct DeleteStatement {
3215    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3216    /// level DELETE. Empty for a plain DELETE.
3217    pub ctes: Vec<Cte>,
3218    pub table: String,
3219    /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3220    /// to `t`'s own rows and not to anything that descends from it.
3221    ///
3222    /// Round 644 taught the FROM clause the keyword and left DML behind
3223    /// because it needed a field here, and this struct carries a warning
3224    /// that round 413 measured widening it in place overflowing the
3225    /// parser's nesting stack. That warning was about `from_sources`, a
3226    /// struct wide enough to need boxing; a `bool` lands in the padding
3227    /// already present — same as `CreateTableStatement::temporary`.
3228    ///
3229    /// It also earns its keep beyond the spelling: the inheritance
3230    /// fan-out needs a way to say "the parent's own rows" as a
3231    /// statement, or running one on the parent recurses forever.
3232    pub only: bool,
3233    /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3234    /// the WHERE / RETURNING expressions refer to the target row by.
3235    pub alias: Option<String>,
3236    pub where_: Option<Expr>,
3237    /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3238    /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3239    /// form (round 413), so it shares that payload — and it is boxed for
3240    /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3241    /// statement tipped the parser's 512 KiB nesting stack.
3242    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3243    /// v7.9.4 — `RETURNING <projection>`.
3244    pub returning: Option<Vec<SelectItem>>,
3245}
3246
3247/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3248/// One WHEN clause fires per source row depending on whether the
3249/// `on` condition matched any target row(s); the executor walks
3250/// `clauses` in declaration order and fires the first whose
3251/// `matched` kind and optional `condition` are both satisfied.
3252#[derive(Debug, Clone, PartialEq)]
3253pub struct MergeStatement {
3254    /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3255    /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3256    /// in PG). Each CTE materialises before the merge runs and its alias
3257    /// resolves as a source relation.
3258    pub ctes: Vec<Cte>,
3259    pub target: String,
3260    pub target_alias: Option<String>,
3261    pub source: String,
3262    pub source_alias: Option<String>,
3263    /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3264    /// the engine materialises this SELECT for the source rows and `source`
3265    /// is empty; the alias (required by PG for a subquery source) is in
3266    /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3267    pub source_select: Option<Box<SelectStatement>>,
3268    /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3269    /// positional column-alias list after the source alias. Empty when
3270    /// the statement carries none; the engine renames the materialised
3271    /// source columns positionally (PG's rule).
3272    pub source_column_aliases: Vec<String>,
3273    pub on: Expr,
3274    pub clauses: Vec<MergeWhenClause>,
3275    /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3276    /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3277    /// target/source aliases. `None` = no RETURNING (the common form).
3278    pub returning: Option<Vec<SelectItem>>,
3279}
3280
3281#[derive(Debug, Clone, PartialEq)]
3282pub struct MergeWhenClause {
3283    pub matched: MergeMatched,
3284    /// Optional `AND <expr>` filter — when present, the clause
3285    /// only fires for the source rows whose match-pair satisfies
3286    /// the predicate.
3287    pub condition: Option<Expr>,
3288    pub action: MergeAction,
3289}
3290
3291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3292pub enum MergeMatched {
3293    Matched,
3294    /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3295    /// target row (the classic insert branch).
3296    NotMatched,
3297    /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3298    /// row no source row matches. Actions are UPDATE / DELETE / DO
3299    /// NOTHING only (INSERT is a syntax error, as in PG).
3300    NotMatchedBySource,
3301}
3302
3303#[derive(Debug, Clone, PartialEq)]
3304pub enum MergeAction {
3305    /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3306    /// explicit column list (the bare `INSERT VALUES (vals)`
3307    /// shape lands later).
3308    Insert {
3309        columns: Vec<String>,
3310        values: Vec<Expr>,
3311    },
3312    /// `UPDATE SET col = expr [, …]` — applied to every matched
3313    /// target row for the firing source row.
3314    Update { assignments: Vec<(String, Expr)> },
3315    /// `DELETE` — drop every matched target row.
3316    Delete,
3317    /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3318    /// the clause and SPG mirrors so a customer-side MERGE that
3319    /// uses it for branch-control doesn't error).
3320    DoNothing,
3321}
3322
3323#[derive(Debug, Clone, PartialEq)]
3324pub struct InsertStatement {
3325    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3326    /// level INSERT (writable CTE outer body). Empty for a plain
3327    /// INSERT. PG semantics: each CTE materialises before the
3328    /// outer INSERT runs, sharing the same transaction.
3329    pub ctes: Vec<Cte>,
3330    pub table: String,
3331    /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3332    /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3333    /// row by. PG requires the AS keyword in this position.
3334    pub alias: Option<String>,
3335    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3336    /// `None`, every tuple is positional and must match the table arity.
3337    /// When `Some`, the engine maps each tuple slot to the named column and
3338    /// fills the rest with NULL (must be nullable).
3339    pub columns: Option<Vec<String>>,
3340    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3341    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3342    /// `select_source` is `Some` (the engine builds rows from the
3343    /// inner SELECT result set instead).
3344    pub rows: Vec<Vec<Expr>>,
3345    /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3346    /// round-5 G4). When present, `rows` is empty and the engine
3347    /// materialises the SELECT result, coerces each output tuple to
3348    /// the target column types, and inserts as a single batch.
3349    pub select_source: Option<Box<SelectStatement>>,
3350    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3351    /// upsert clause. None = legacy INSERT (conflict raises a
3352    /// DuplicateKey error). mailrs migration blocker #2.
3353    pub on_conflict: Option<OnConflictClause>,
3354    /// v7.9.4 — `RETURNING <projection>`.
3355    pub returning: Option<Vec<SelectItem>>,
3356    /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3357    /// between the column list and VALUES. Governs how explicitly-supplied
3358    /// values interact with `GENERATED … AS IDENTITY` columns:
3359    ///   * `None` — default. A `GENERATED ALWAYS` identity column rejects
3360    ///     an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3361    ///   * `System` — override the ALWAYS restriction: the explicit value
3362    ///     is used verbatim, as for a `BY DEFAULT` column.
3363    ///   * `User` — ignore any explicit value on a `BY DEFAULT` identity
3364    ///     column and generate from the sequence instead (no effect on
3365    ///     non-identity columns).
3366    pub overriding: Overriding,
3367    /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3368    /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3369    /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3370    /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3371    /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3372    /// into a NOT NULL column becomes the type's default), and the engine
3373    /// cannot recover that intent from the conflict clause alone. A plain
3374    /// `bool` lands in this struct's existing padding, so the AST does not
3375    /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3376    pub mysql_ignore: bool,
3377}
3378
3379/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3380#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3381pub enum Overriding {
3382    /// No `OVERRIDING` clause.
3383    #[default]
3384    None,
3385    /// `OVERRIDING SYSTEM VALUE`.
3386    System,
3387    /// `OVERRIDING USER VALUE`.
3388    User,
3389}
3390
3391/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3392#[derive(Debug, Clone, PartialEq)]
3393pub struct OnConflictClause {
3394    /// Local columns that identify the conflict (must match a
3395    /// UNIQUE / PRIMARY KEY index on the target table). Empty
3396    /// list means the user wrote `ON CONFLICT DO …` without a
3397    /// target — the engine arbitrates on every unique constraint
3398    /// (round 240).
3399    pub target_columns: Vec<String>,
3400    /// v7.39 (round 240) — the index predicate after the target list
3401    /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3402    /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3403    /// which satisfy any predicate, so it is parsed and carried but not
3404    /// consulted (recorded residual: partial-unique-index arbiters).
3405    pub index_where: Option<Expr>,
3406    /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3407    /// <name>`: the pg_dump conflict-target form. The engine
3408    /// resolves the name to the constraint's columns.
3409    pub constraint_name: Option<String>,
3410    /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3411    /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3412    /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3413    /// `ON CONFLICT DO UPDATE` is refused (42601).
3414    pub mysql_lowered: bool,
3415    /// The action on conflict.
3416    pub action: OnConflictAction,
3417}
3418
3419/// v7.9.7 — action on conflict.
3420#[derive(Debug, Clone, PartialEq)]
3421pub enum OnConflictAction {
3422    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3423    /// silently skips conflicting ones.
3424    Nothing,
3425    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3426    /// may reference `EXCLUDED.col` to read the incoming row's
3427    /// value (engine wires `EXCLUDED` as a virtual table).
3428    Update {
3429        assignments: Vec<(String, Expr)>,
3430        where_: Option<Expr>,
3431    },
3432}
3433
3434/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3435///
3436/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3437/// policies are spelled again here and mapped at the engine boundary.
3438#[derive(Debug, Clone, PartialEq, Eq)]
3439pub struct LockingClause {
3440    pub strength: LockStrength,
3441    /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3442    pub of_tables: Vec<String>,
3443    pub policy: LockWait,
3444}
3445
3446/// PG's four tuple-lock strengths, weakest first.
3447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3448pub enum LockStrength {
3449    KeyShare,
3450    Share,
3451    NoKeyUpdate,
3452    Update,
3453}
3454
3455/// What to do when the row is already locked.
3456#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3457pub enum LockWait {
3458    /// Block until it is free — PG's default.
3459    #[default]
3460    Wait,
3461    /// `NOWAIT` — fail the statement with 55P03.
3462    NoWait,
3463    /// `SKIP LOCKED` — leave the row out of the result.
3464    SkipLocked,
3465}
3466
3467#[derive(Debug, Clone, PartialEq, Default)]
3468pub struct SelectStatement {
3469    /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3470    /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3471    /// whole syntax and locked nothing: two workers running the classic
3472    /// `SKIP LOCKED` queue take both took the same row.
3473    /// v7.39 (round 305) — boxed. A locking clause appears on a
3474    /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3475    /// cost every `SelectStatement` 32 bytes, and this struct sits in
3476    /// recursive evaluation frames where the engine already runs close to
3477    /// its stack budget (a 512 KB depth guard is the canary).
3478    pub locking: Option<alloc::boxed::Box<LockingClause>>,
3479    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3480    /// expressions, materialised once at query start before the
3481    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3482    /// only — no `WITH RECURSIVE` for v4.x.
3483    pub ctes: Vec<Cte>,
3484    pub distinct: bool,
3485    /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3486    /// keep the first row (per ORDER BY) of each group the
3487    /// expressions define. Empty = no DISTINCT ON.
3488    pub distinct_on: Vec<Expr>,
3489    pub items: Vec<SelectItem>,
3490    pub from: Option<FromClause>,
3491    pub where_: Option<Expr>,
3492    pub group_by: Option<Vec<Expr>>,
3493    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3494    /// expands `group_by` to every non-aggregate SELECT-list item
3495    /// before the executor runs. Mutually exclusive with an
3496    /// explicit `group_by` list (the parser sets exactly one).
3497    pub group_by_all: bool,
3498    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3499    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3500    /// aggregate executor resolves them through the same synthetic
3501    /// schema used for the SELECT items.
3502    pub having: Option<Expr>,
3503    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3504    /// itself a `SelectStatement` with `order_by = None` and `limit =
3505    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3506    /// top of the chain).
3507    pub unions: Vec<(UnionKind, SelectStatement)>,
3508    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3509    /// Keys are matched left-to-right: first key decides, ties break
3510    /// to the second, etc.
3511    pub order_by: Vec<OrderBy>,
3512    /// `LIMIT <n>` — bound on row output. `n` is an integer
3513    /// literal **or** (v7.9.24) a placeholder `$N` resolved
3514    /// against the prepared-statement Bind values. mailrs
3515    /// migration follow-up H2.
3516    pub limit: Option<LimitExpr>,
3517    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3518    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3519    pub offset: Option<LimitExpr>,
3520    /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3521    /// (SQL:2008). When true and an ORDER BY is present, the
3522    /// executor extends past the LIMIT-truncated tail to include
3523    /// every row whose ORDER BY key equals the last-kept row's
3524    /// key. Requires an ORDER BY; the executor errors otherwise
3525    /// (matching PG's `WITH TIES` rule). The parser was already
3526    /// accepting `WITH TIES` since Phase 5.1; this field captures
3527    /// the choice so the executor can act on it.
3528    pub limit_with_ties: bool,
3529    /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3530    /// that NOTHING referenced. PG analyses every definition whether
3531    /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3532    /// and silently succeeded here — the referenced ones get their columns
3533    /// resolved through the WindowFunction nodes they were inlined into,
3534    /// and the unreferenced ones used to be dropped at parse, unexamined.
3535    /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3536    ///
3537    /// Not part of `Display`: an unreferenced definition has no effect on
3538    /// the result, so a deparsed body (a stored view) omits it.
3539    pub window_check_exprs: Vec<Expr>,
3540}
3541
3542impl Expr {
3543    /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3544    /// directly inside this expression to `f`. `f` receives each nested
3545    /// statement once; descending further (into that statement's own
3546    /// clauses) is the caller's job, which keeps this walk finite and
3547    /// lets the caller order the recursion.
3548    ///
3549    /// The match is deliberately **wildcard-free**: a new `Expr` variant
3550    /// does not compile until it says whether it can carry a subquery.
3551    /// The row-count resolution pass is built on this, and a shape it
3552    /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3553    /// which every row-count reader would take as "no limit", i.e. the
3554    /// whole table. Compile-time exhaustiveness is what rules that out.
3555    /// Iterative on purpose. Expression trees here get deep (long
3556    /// boolean chains, big IN lists), and this walk is on the path of
3557    /// every statement; recursing would add a frame per node to a stack
3558    /// budget the engine already runs close to — a depth guard that runs
3559    /// on a deliberately small stack caught exactly that. Depth costs
3560    /// heap here instead.
3561    pub fn for_each_subquery_mut<E>(
3562        &mut self,
3563        f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3564    ) -> Result<(), E> {
3565        let mut stack: Vec<&mut Self> = alloc::vec![self];
3566        while let Some(e) = stack.pop() {
3567            match e {
3568                Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3569                Self::NamedArg { expr, .. }
3570                | Self::Variadic(expr)
3571                | Self::Unary { expr, .. }
3572                | Self::Cast { expr, .. }
3573                | Self::FieldAccess { base: expr, .. }
3574                | Self::IsNull { expr, .. }
3575                | Self::BoolTest { expr, .. }
3576                | Self::Extract { source: expr, .. } => stack.push(expr),
3577                Self::Binary { lhs, rhs, .. } => {
3578                    stack.push(lhs);
3579                    stack.push(rhs);
3580                }
3581                Self::Like { expr, pattern, .. } => {
3582                    stack.push(expr);
3583                    stack.push(pattern);
3584                }
3585                Self::ArraySubscript { target, index } => {
3586                    stack.push(target);
3587                    stack.push(index);
3588                }
3589                Self::ArraySlice { target, lo, hi } => {
3590                    stack.push(target);
3591                    stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
3592                }
3593                Self::AnyAll { expr, array, .. } => {
3594                    stack.push(expr);
3595                    stack.push(array);
3596                }
3597                Self::FunctionCall { args, .. } | Self::Array(args) => {
3598                    stack.extend(args.iter_mut());
3599                }
3600                Self::AggregateOrdered {
3601                    call,
3602                    order_by,
3603                    filter,
3604                    ..
3605                } => {
3606                    stack.push(call);
3607                    stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
3608                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3609                }
3610                Self::WindowFunction {
3611                    args,
3612                    partition_by,
3613                    order_by,
3614                    filter,
3615                    ..
3616                } => {
3617                    // `frame` bounds hold folded numbers / interval
3618                    // parts, never expressions — nothing to visit there.
3619                    stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
3620                    stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
3621                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3622                }
3623                Self::InList { expr, list, .. } => {
3624                    stack.push(expr);
3625                    stack.extend(list.iter_mut());
3626                }
3627                Self::Case {
3628                    operand,
3629                    branches,
3630                    else_branch,
3631                } => {
3632                    stack.extend(
3633                        operand
3634                            .iter_mut()
3635                            .chain(else_branch.iter_mut())
3636                            .map(|b| &mut **b),
3637                    );
3638                    for (when, then) in branches.iter_mut() {
3639                        stack.push(when);
3640                        stack.push(then);
3641                    }
3642                }
3643                Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
3644                Self::InSubquery { expr, subquery, .. } => {
3645                    stack.push(expr);
3646                    f(subquery)?;
3647                }
3648                Self::RowInSubquery { row, subquery, .. }
3649                | Self::RowCmpSubquery { row, subquery, .. } => {
3650                    stack.extend(row.iter_mut());
3651                    f(subquery)?;
3652                }
3653            }
3654        }
3655        Ok(())
3656    }
3657}
3658
3659/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
3660/// time or a placeholder `$N` resolved during extended-query
3661/// Bind. mailrs migration follow-up H2.
3662///
3663/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
3664/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
3665/// made the compiler point at every site that used to duplicate a
3666/// row-count out of the AST, which is exactly the set that must not
3667/// bypass the resolution pre-pass.
3668#[derive(Debug, Clone, PartialEq)]
3669pub enum LimitExpr {
3670    /// `LIMIT 10` — value known at parse time.
3671    Literal(u32),
3672    /// `LIMIT $N` — the 1-based parameter index, resolved against
3673    /// the bind values when the prepared statement executes.
3674    Placeholder(u16),
3675    /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
3676    /// greatest(2,3)`: a row-count expression that isn't constant, so
3677    /// it can't be folded at parse time. Evaluated once, before
3678    /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
3679    /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
3680    /// "no limit"). **No execution path may see this variant** —
3681    /// `as_literal` would report `None`, which every row-count reader
3682    /// takes to mean "unlimited", i.e. the whole table.
3683    Expr(alloc::boxed::Box<Expr>),
3684}
3685
3686impl fmt::Display for LimitExpr {
3687    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3688        match self {
3689            Self::Literal(n) => write!(f, "{n}"),
3690            Self::Placeholder(n) => write!(f, "${n}"),
3691            // Parenthesised so the round-trip text re-parses as one
3692            // row-count expression (`LIMIT (SELECT 4)`), which is also
3693            // the only spelling `FETCH FIRST` accepts.
3694            Self::Expr(e) => write!(f, "({e})"),
3695        }
3696    }
3697}
3698
3699impl LimitExpr {
3700    /// Convenience for the simple-query path where no placeholders
3701    /// can possibly exist. Returns the literal value or `None` if
3702    /// this is a placeholder (caller must surface as Unsupported).
3703    ///
3704    /// v7.39 (round 305) — `None` is read by every row-count consumer as
3705    /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
3706    /// therefore silently return the whole table, so the engine's
3707    /// `resolve_limit_exprs` pre-pass rewrites the variant away before
3708    /// dispatch. The assertion makes a missed nesting site fail loudly
3709    /// in every test build rather than quietly widening a result set.
3710    #[must_use]
3711    pub fn as_literal(&self) -> Option<u32> {
3712        match self {
3713            Self::Literal(n) => Some(*n),
3714            Self::Placeholder(_) => None,
3715            Self::Expr(_) => {
3716                debug_assert!(
3717                    false,
3718                    "LimitExpr::Expr reached execution — resolve_limit_exprs \
3719                     missed a nesting site; treating it as `no limit` would \
3720                     return every row"
3721                );
3722                None
3723            }
3724        }
3725    }
3726}
3727
3728/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
3729/// the engine's `substitute_placeholders` pass these are
3730/// always Literal; in the simple-query path a Placeholder
3731/// shape returns None (executor surfaces as
3732/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
3733impl SelectStatement {
3734    #[must_use]
3735    pub fn limit_literal(&self) -> Option<u32> {
3736        self.limit.as_ref().and_then(LimitExpr::as_literal)
3737    }
3738    #[must_use]
3739    pub fn offset_literal(&self) -> Option<u32> {
3740        self.offset.as_ref().and_then(LimitExpr::as_literal)
3741    }
3742}
3743
3744#[derive(Debug, Clone, PartialEq)]
3745pub struct Cte {
3746    pub name: String,
3747    /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
3748    /// classical case) or a data-modifying statement
3749    /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
3750    /// CTE semantics. The modifying body's RETURNING projection
3751    /// becomes the materialised CTE table the outer query can
3752    /// reference; the modifying statement runs once before the
3753    /// outer query, within the same transaction.
3754    pub body: CteBody,
3755    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
3756    /// RECURSIVE keyword. Applies to every CTE in the clause per
3757    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
3758    /// allowed; the engine just runs it once.
3759    pub recursive: bool,
3760    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
3761    /// non-empty, these override the body's output column names
3762    /// position-by-position; the engine errors out if the count
3763    /// doesn't match the body's projection width.
3764    pub column_overrides: Vec<String>,
3765    /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
3766    /// SET seqcol` on a recursive CTE. Desugared at parse time into an
3767    /// extra ordering column on the body (see `rewrite_search_and_cycle`).
3768    pub search: Option<SearchClause>,
3769    /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
3770    /// USING pathcol` cycle detection, desugared at parse time.
3771    pub cycle: Option<CycleClause>,
3772}
3773
3774/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
3775#[derive(Debug, Clone, PartialEq)]
3776pub struct SearchClause {
3777    /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
3778    pub depth_first: bool,
3779    /// The CTE output columns the search orders by.
3780    pub by_columns: Vec<String>,
3781    /// The new column holding the ordering key (a row-array for depth,
3782    /// a `(depth, keys…)` row for breadth).
3783    pub set_column: String,
3784}
3785
3786/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
3787#[derive(Debug, Clone, PartialEq)]
3788pub struct CycleClause {
3789    /// Columns whose repetition along a path marks a cycle.
3790    pub columns: Vec<String>,
3791    /// The new boolean-ish column set to `mark_value` on a cycle.
3792    pub mark_column: String,
3793    /// Value written to `mark_column` when a cycle is detected (default
3794    /// `true`); `default_value` otherwise. PG allows any type; SPG carries
3795    /// them as literals.
3796    pub mark_value: Option<Literal>,
3797    pub default_value: Option<Literal>,
3798    /// The new column accumulating the visited-row path array.
3799    pub path_column: String,
3800}
3801
3802/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
3803/// (Insert / Update / Delete with optional RETURNING). The
3804/// data-modifying variants must carry a RETURNING projection for the
3805/// outer query to reference the CTE alias by; an empty RETURNING is
3806/// only valid if no outer reference materialises (rare — typically
3807/// caught at planning).
3808#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
3809#[derive(Debug, Clone, PartialEq)]
3810pub enum CteBody {
3811    Select(SelectStatement),
3812    Insert(Box<InsertStatement>),
3813    Update(Box<UpdateStatement>),
3814    Delete(Box<DeleteStatement>),
3815    /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
3816    /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
3817    Merge(Box<MergeStatement>),
3818}
3819
3820impl CteBody {
3821    /// Convenience accessor used by classical (read-only) CTE
3822    /// callsites that still expect a SELECT body. Returns None for
3823    /// data-modifying CTEs; callers must explicitly route those
3824    /// through `exec_with_ctes`'s modifying branch.
3825    #[must_use]
3826    pub fn as_select(&self) -> Option<&SelectStatement> {
3827        match self {
3828            Self::Select(s) => Some(s),
3829            _ => None,
3830        }
3831    }
3832
3833    #[must_use]
3834    pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
3835        match self {
3836            Self::Select(s) => Some(s),
3837            _ => None,
3838        }
3839    }
3840
3841    #[must_use]
3842    pub fn is_modifying(&self) -> bool {
3843        !matches!(self, Self::Select(_))
3844    }
3845}
3846
3847#[derive(Debug, Clone, PartialEq)]
3848pub struct OrderBy {
3849    pub expr: Expr,
3850    /// `false` = ASC (default), `true` = DESC.
3851    pub desc: bool,
3852    /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
3853    /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
3854    /// NULLS FIRST for DESC); the engine resolves the effective
3855    /// value via `nulls_first.unwrap_or(desc)`.
3856    pub nulls_first: Option<bool>,
3857    /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
3858    /// It lives here rather than in the expression for the same reason
3859    /// `desc` does: at an ORDER BY key a collation is ordering
3860    /// information, and nothing downstream of the sort needs it. A new
3861    /// `Expr` variant would instead put a new arm on `eval_expr`, which
3862    /// this repo has measured to overflow the debug stack.
3863    ///
3864    /// `None` means none was written, and the key falls back to whatever
3865    /// its COLUMN declares — which is every key that existed before this.
3866    pub collation: Option<String>,
3867}
3868
3869#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3870pub enum UnionKind {
3871    /// `UNION` — dedupes the combined set.
3872    Distinct,
3873    /// `UNION ALL` — concatenates without dedup.
3874    All,
3875    /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
3876    /// present on both sides.
3877    Intersect,
3878    /// `INTERSECT ALL` — multiset intersection (min per-row count).
3879    IntersectAll,
3880    /// `EXCEPT` — distinct left rows absent from the right.
3881    Except,
3882    /// `EXCEPT ALL` — multiset subtraction.
3883    ExceptAll,
3884}
3885
3886#[derive(Debug, Clone, PartialEq)]
3887pub enum SelectItem {
3888    Wildcard,
3889    /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
3890    /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
3891    /// `NEW` pseudo-relation).
3892    QualifiedWildcard(String),
3893    Expr {
3894        expr: Expr,
3895        alias: Option<String>,
3896    },
3897}
3898
3899#[derive(Debug, Clone, PartialEq)]
3900pub struct TableRef {
3901    pub name: String,
3902    pub alias: Option<String>,
3903    /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
3904    /// children.
3905    ///
3906    /// The keyword used to be absorbed at parse time, on the reasoning
3907    /// that SPG's inheritance children are separate relations a plain
3908    /// scan does not descend into — so ONLY already described what the
3909    /// scan did. That stopped being true when a partition parent
3910    /// started unioning its children: measured, `SELECT count(*) FROM
3911    /// ONLY <partitioned parent>` answered 2 where PG answers 0.
3912    pub only: bool,
3913    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
3914    /// When `Some(id)`, the scan restricts to rows that live in
3915    /// segment `<id>` only — useful for forensic inspection of a
3916    /// specific freezer-emitted segment without exposing the hot
3917    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
3918    /// is STABILITY carve-out for v6.10 — needs the freezer to
3919    /// stamp each segment with a wall-clock at creation time.
3920    pub as_of_segment: Option<u32>,
3921    /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
3922    /// source. When `Some`, `name` is the alias (defaulting to
3923    /// `"unnest"` when no `AS` is given) and the engine builds a
3924    /// synthetic single-column table by evaluating the expression
3925    /// once at SELECT entry. Each TEXT[] element becomes one row;
3926    /// NULL elements become NULL cells. v7.11 supported
3927    /// uncorrelated UNNEST only as the FROM primary; v7.13.2
3928    /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
3929    /// position (cross-join with regular tables).
3930    pub unnest_expr: Option<Box<Expr>>,
3931    /// v7.13.2 — mailrs round-6 S5. PG-standard
3932    /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
3933    /// when non-empty, the first entry overrides the projected
3934    /// column name for the unnested column. Empty = fall back to
3935    /// the table alias (pre-v7.13.2 behaviour).
3936    pub unnest_column_aliases: Vec<String>,
3937    /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
3938    /// row-stream gains a trailing BIGINT column counting rows
3939    /// from 1 in element order. PG names it `ordinality`; a second
3940    /// entry in the column-alias list renames it.
3941    pub with_ordinality: bool,
3942    /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
3943    /// [, step])` set-returning source. When `Some`, the engine
3944    /// materialises a single-column virtual table by stepping
3945    /// `start` to `stop` inclusive. Args are the literal arg list
3946    /// (2 for default-step, 3 for explicit-step). Supports:
3947    ///   * SmallInt / Int / BigInt with integer step (default = 1)
3948    ///   * Timestamp with INTERVAL step (PG date-range pattern)
3949    /// Mutually exclusive with `unnest_expr` — both populate the
3950    /// same downstream dispatch slot. `name` defaults to
3951    /// `"generate_series"` when no alias is provided.
3952    pub generate_series_args: Option<Vec<Expr>>,
3953    /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
3954    /// table. When `Some`, the TableRef is a parenthesised SELECT
3955    /// that may reference columns from the preceding FROM items
3956    /// (correlated derived table). The executor materialises the
3957    /// subquery per left-row, substituting outer-column references
3958    /// against the current join row's values before running the
3959    /// inner SELECT, then cross-joins the result back.
3960    /// Mutually exclusive with `name` / `unnest_expr` /
3961    /// `generate_series_args`.
3962    pub lateral_subquery: Option<Box<SelectStatement>>,
3963    /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
3964    /// function as a FROM item. PG semantics: for each key/value
3965    /// pair in the JSONB object argument, emit one (key TEXT,
3966    /// value TEXT) row. When prefixed by `LATERAL` and joined via
3967    /// `CROSS JOIN LATERAL`, the argument may reference columns
3968    /// from a preceding FROM item, in which case the executor
3969    /// evaluates `<expr>` per outer row.
3970    /// Mutually exclusive with `unnest_expr` / `generate_series_args`
3971    /// / `lateral_subquery`. The optional `LATERAL` keyword does not
3972    /// require a separate flag — the executor evaluates per-row
3973    /// whenever the join sits in a JoinKind context.
3974    ///
3975    /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
3976    /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
3977    /// `json_each` / `json_each_text`) so the executor picks the
3978    /// value-column rendering (JSON text vs unwrapped text).
3979    pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
3980    /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
3981    /// function channel: `(lowercase fn name, args)`. Carries
3982    /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
3983    /// dispatches by name.
3984    pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
3985    /// v7.39 (read01 round 78) — this FROM item is a call to a function that
3986    /// returns a BASE type, so the item's row type IS that scalar: a whole-row
3987    /// reference to it yields the value, not a one-field composite
3988    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
3989    /// desugared shape is indistinguishable from a hand-written
3990    /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
3991    /// only the parser knows which one it built, so it says so here.
3992    pub scalar_fn_item: bool,
3993    /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
3994    /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
3995    /// target-list SRFs follow — see round 67). The array-returning family keeps
3996    /// its own lowering; this channel carries the ones that have no array form
3997    /// (`generate_series`, a user `RETURNS SETOF` function).
3998    pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
3999    /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4000    /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4001    /// tables (implicit LATERAL, like every SRF channel). Executed by
4002    /// walking the row path over the parsed doc, then each column's
4003    /// path per row-item; NESTED expands as a per-parent outer join.
4004    pub json_table: Option<Box<JsonTable>>,
4005}
4006
4007/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4008#[derive(Debug, Clone, PartialEq)]
4009pub struct JsonTable {
4010    /// The document expression (jsonb/json/text). May reference outer
4011    /// columns → implicit LATERAL.
4012    pub doc: Box<Expr>,
4013    /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4014    /// match is one row's context item.
4015    pub row_path: String,
4016    /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4017    pub columns: Vec<JsonTableColumn>,
4018    /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4019    pub passing: Vec<(String, Expr)>,
4020}
4021
4022/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4023#[derive(Debug, Clone, PartialEq)]
4024pub enum JsonTableColumn {
4025    /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4026    Ordinality { name: String },
4027    /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4028    /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4029    /// `<name> <type> EXISTS [PATH '<p>']`.
4030    Regular {
4031        name: String,
4032        ty: ColumnTypeName,
4033        /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4034        path: String,
4035        /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4036        exists: bool,
4037        /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4038        format_json: bool,
4039        /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4040        wrapper: bool,
4041        /// Behaviour when the path matches nothing (default NULL).
4042        on_empty: JsonTableOnBehavior,
4043        /// Behaviour when coercion fails (default NULL).
4044        on_error: JsonTableOnBehavior,
4045    },
4046    /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4047    /// row like a LEFT JOIN (a parent with no nested match still emits one
4048    /// row, nested cols NULL).
4049    Nested {
4050        path: String,
4051        columns: Vec<JsonTableColumn>,
4052    },
4053}
4054
4055/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4056#[derive(Debug, Clone, PartialEq)]
4057pub enum JsonTableOnBehavior {
4058    /// Default: the column value is NULL.
4059    Null,
4060    /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4061    Error,
4062    /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4063    Default(Box<Expr>),
4064}
4065
4066/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4067/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4068/// joins evaluate left-associatively in nested-loop order.
4069#[derive(Debug, Clone, PartialEq)]
4070pub struct FromClause {
4071    pub primary: TableRef,
4072    pub joins: Vec<FromJoin>,
4073}
4074
4075#[derive(Debug, Clone, PartialEq)]
4076pub struct FromJoin {
4077    pub kind: JoinKind,
4078    pub table: TableRef,
4079    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4080    pub on: Option<Expr>,
4081    /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4082    /// USING column list so the executor can perform PG's column-merge
4083    /// (the join columns collapse to a single unqualified output column,
4084    /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4085    /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4086    /// USING into an equivalent `on` predicate so the join filter/count
4087    /// path works unchanged; `using_cols` drives only the output-shape
4088    /// rewrite. Empty/`None` for `ON` and CROSS joins.
4089    pub using_cols: Option<Vec<String>>,
4090    /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4091    /// column names are not known until the table schemas are available
4092    /// (parse time is schema-less), so the parser only sets this flag and
4093    /// leaves `on`/`using_cols` empty; the engine resolves the common
4094    /// columns at execution time, synthesises the `on` predicate + the
4095    /// USING column-merge, and clears the flag. If there are no common
4096    /// columns PG treats it as a CROSS join.
4097    pub natural: bool,
4098}
4099
4100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4101pub enum JoinKind {
4102    Inner,
4103    Left,
4104    Cross,
4105    /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4106    /// NULL-filling the left (drive) columns on unmatched right rows.
4107    /// The executor runs the LEFT algorithm's mirror: it tracks which
4108    /// peer rows matched and emits the unmatched ones with a NULL-left
4109    /// tuple after the probe loop. Output column order is unchanged
4110    /// (left-table cols then right-table cols).
4111    Right,
4112    /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4113    /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4114    FullOuter,
4115    /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4116    /// once, paired with the first peer row that satisfies the ON. Not
4117    /// reachable from SQL — the EXISTS pull-up emits it, which is what
4118    /// frees positive EXISTS from the round-721 uniqueness gate (an
4119    /// INNER join would multiply the outer rows; a semi join cannot).
4120    Semi,
4121}
4122
4123#[derive(Debug, Clone, PartialEq)]
4124pub enum Expr {
4125    Literal(Literal),
4126    Column(ColumnName),
4127    /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4128    /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4129    /// callee's declared parameter names, and a user function's live in the
4130    /// catalog — which the parser cannot see. So the name rides along in the
4131    /// tree and the evaluator, which has the catalog, does the reordering.
4132    /// Appears only inside a `FunctionCall`'s argument list.
4133    NamedArg {
4134        name: String,
4135        expr: Box<Expr>,
4136    },
4137    /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4138    /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4139    /// expression evaluates to an array whose elements the evaluator splices
4140    /// into the call as individual trailing arguments. Appears only inside a
4141    /// `FunctionCall`'s argument list.
4142    Variadic(Box<Expr>),
4143    /// v6.1.1 — `$N` parameter placeholder for the extended query
4144    /// protocol. The number is 1-based per PostgreSQL convention.
4145    /// Evaluation looks up `params[N-1]` from the prepared-statement
4146    /// bind buffer; out-of-range indices raise a runtime error
4147    /// (same shape as a column-not-found miss).
4148    Placeholder(u16),
4149    Binary {
4150        lhs: Box<Expr>,
4151        op: BinOp,
4152        rhs: Box<Expr>,
4153    },
4154    Unary {
4155        op: UnOp,
4156        expr: Box<Expr>,
4157    },
4158    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4159    /// TEXT, BOOL targets; engine coerces at evaluation time.
4160    Cast {
4161        expr: Box<Expr>,
4162        target: CastTarget,
4163    },
4164    /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4165    /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4166    /// whole-row reference, or a composite-returning function); `field` names
4167    /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4168    /// column names for a whole-row). Only the parenthesised form reaches
4169    /// here — a bare `a.b` is parsed as a qualified column reference.
4170    FieldAccess {
4171        base: Box<Expr>,
4172        field: String,
4173    },
4174    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4175    IsNull {
4176        expr: Box<Expr>,
4177        negated: bool,
4178    },
4179    /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4180    /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4181    /// `Some(false)` for FALSE and `None` for UNKNOWN.
4182    ///
4183    /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4184    /// The semantics were right, but the AST then had no way to say what
4185    /// the user wrote, so every renderer printed the lowering:
4186    /// `CHECK ((a > 1) IS TRUE)` came back as
4187    /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4188    /// dumped view lost the form too.
4189    BoolTest {
4190        expr: Box<Expr>,
4191        value: Option<bool>,
4192        negated: bool,
4193    },
4194    /// Function call `name(args...)`. v1.4 supports a small built-in set
4195    /// (length, upper, lower, abs, coalesce); unknown names error at eval
4196    /// time so the parser stays open for v1.5 aggregates.
4197    FunctionCall {
4198        name: String,
4199        args: Vec<Expr>,
4200    },
4201    /// v7.24 (mailrs round-16 A) — an aggregate call with an
4202    /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4203    /// Wraps the plain [`Expr::FunctionCall`] so every existing
4204    /// FunctionCall consumer stays untouched; only the aggregate
4205    /// executor (and the expression walkers) know the wrapper.
4206    /// Non-aggregate evaluation contexts reject it at eval time.
4207    AggregateOrdered {
4208        call: Box<Expr>,
4209        order_by: Vec<OrderBy>,
4210        /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4211        /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4212        /// aggregate modifier so plain FunctionCall stays untouched.
4213        distinct: bool,
4214        /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4215        /// Only the rows where `cond` is true contribute to this
4216        /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4217        /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4218        /// END)`, which is faithful for NULL-ignoring aggregates but
4219        /// WRONG for `array_agg` (it would collect a NULL per excluded
4220        /// row). The executor instead skips excluded rows before
4221        /// accumulation, which is correct for every aggregate.
4222        filter: Option<Box<Expr>>,
4223    },
4224    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4225    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4226    /// the next char (so `\%` matches a literal `%`).
4227    Like {
4228        expr: Box<Expr>,
4229        pattern: Box<Expr>,
4230        negated: bool,
4231        /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4232        /// match. PG folds both operands.
4233        case_insensitive: bool,
4234    },
4235    /// v4.12 window function call: `name(args) OVER (PARTITION BY
4236    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4237    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4238    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4239    /// unordered windows and "from start of partition through
4240    /// current row" for ordered windows — no explicit ROWS /
4241    /// RANGE clause in v4.12 MVP.
4242    WindowFunction {
4243        name: String,
4244        args: Vec<Expr>,
4245        partition_by: Vec<Expr>,
4246        /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4247        /// (None = PG default, same contract as [`OrderBy`]).
4248        order_by: Vec<(
4249            Expr,
4250            bool,         /* desc */
4251            Option<bool>, /* nulls_first */
4252        )>,
4253        /// v4.20 explicit frame. `None` means "use the default":
4254        /// whole-partition when unordered, running aggregate from
4255        /// partition start through current row when ordered.
4256        frame: Option<WindowFrame>,
4257        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4258        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4259        /// `Respect` (PG / ANSI default — NULLs participate). Other
4260        /// window functions ignore this flag.
4261        null_treatment: NullTreatment,
4262        /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4263        /// = no FILTER. Only aggregate window functions honor it; the
4264        /// predicate restricts which peer rows contribute within the frame.
4265        filter: Option<Box<Expr>>,
4266    },
4267    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4268    /// position. Must return exactly one row × one column at eval
4269    /// time; the engine errors out otherwise. Uncorrelated only —
4270    /// the inner SELECT cannot reference outer columns.
4271    ScalarSubquery(Box<SelectStatement>),
4272    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4273    /// projection is ignored; only row-count matters.
4274    Exists {
4275        subquery: Box<SelectStatement>,
4276        negated: bool,
4277    },
4278    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4279    /// project exactly one column; membership is tested by Eq
4280    /// against each row's value (NULL handling follows ANSI:
4281    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4282    InSubquery {
4283        expr: Box<Expr>,
4284        subquery: Box<SelectStatement>,
4285        negated: bool,
4286    },
4287    /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4288    /// against a multi-column subquery. Row comparisons against a *list*
4289    /// decompose to OR-of-AND at parse time, but the subquery form can't
4290    /// (its rows are only known at runtime), so this survives as its own
4291    /// node evaluated with PG's row-comparison three-valued logic.
4292    RowInSubquery {
4293        row: Vec<Expr>,
4294        subquery: Box<SelectStatement>,
4295        negated: bool,
4296    },
4297    /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4298    /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4299    /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4300    /// subquery form can't, so it survives as its own node. The subquery
4301    /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4302    RowCmpSubquery {
4303        row: Vec<Expr>,
4304        op: BinOp,
4305        subquery: Box<SelectStatement>,
4306    },
4307    /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4308    /// list. Both the parser's literal-list path and the engine's
4309    /// IN-subquery materialisation used to desugar into a left-deep
4310    /// OR-Eq chain, so expression depth scaled with the element count
4311    /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4312    /// (recursive eval AND recursive Box drop) and aborted embedding
4313    /// host processes. The flat node keeps depth constant: eval is an
4314    /// iterative scan with PG three-valued logic, drop is a Vec drop.
4315    InList {
4316        expr: Box<Expr>,
4317        list: Vec<Expr>,
4318        negated: bool,
4319    },
4320    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4321    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4322    /// because the `FROM` keyword is what separates the two halves,
4323    /// not a comma.
4324    Extract {
4325        field: ExtractField,
4326        source: Box<Expr>,
4327    },
4328    /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4329    /// element is evaluated independently; NULLs are allowed.
4330    /// v7.10 supports only single-dimension TEXT[] semantically;
4331    /// non-text elements coerce at engine evaluation time when
4332    /// the surrounding context (column type / cast) makes the
4333    /// target clear.
4334    Array(Vec<Expr>),
4335    /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4336    /// engine returns NULL for out-of-range indices.
4337    ArraySubscript {
4338        target: Box<Expr>,
4339        index: Box<Expr>,
4340    },
4341    /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4342    /// inclusive; a missing bound extends to that end of the
4343    /// array and out-of-range bounds clamp. Returns an array of
4344    /// the same element type.
4345    ArraySlice {
4346        target: Box<Expr>,
4347        lo: Option<Box<Expr>>,
4348        hi: Option<Box<Expr>>,
4349    },
4350    /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4351    /// operator is the comparison binary op (Eq / Ne / Lt / …);
4352    /// the engine desugars: `ANY` returns true if any element
4353    /// satisfies; `ALL` returns true only if every element does.
4354    /// NULL handling follows PG's three-valued logic.
4355    AnyAll {
4356        expr: Box<Expr>,
4357        op: BinOp,
4358        array: Box<Expr>,
4359        /// `true` = ANY, `false` = ALL.
4360        is_any: bool,
4361    },
4362    /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4363    /// (searched form, `operand` is None) and
4364    /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4365    /// `operand` is the lead expression compared against each
4366    /// branch's match). Each `(when_expr, then_expr)` branch
4367    /// stays as written; engine short-circuits on the first match.
4368    /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4369    /// mailrs round-5 G9.
4370    Case {
4371        operand: Option<Box<Expr>>,
4372        branches: Vec<(Expr, Expr)>,
4373        else_branch: Option<Box<Expr>>,
4374    },
4375}
4376
4377/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4378/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4379/// in the offset walk. `Ignore` causes the function to skip NULL
4380/// values in the argument expression, returning the next non-NULL.
4381#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4382pub enum NullTreatment {
4383    #[default]
4384    Respect,
4385    Ignore,
4386}
4387
4388/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4389/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4390/// where end implicitly = CURRENT ROW.
4391#[derive(Debug, Clone, PartialEq, Eq)]
4392pub struct WindowFrame {
4393    pub kind: FrameKind,
4394    pub start: FrameBound,
4395    pub end: Option<FrameBound>,
4396    /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4397    /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4398    /// no-op; CURRENT ROW drops the current row from the frame.
4399    pub exclude: FrameExclusion,
4400}
4401
4402#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4403pub enum FrameExclusion {
4404    /// Default — exclude nothing.
4405    #[default]
4406    NoOthers,
4407    /// Drop the current row from the frame.
4408    CurrentRow,
4409    /// Drop the current row's whole peer group.
4410    Group,
4411    /// Drop the current row's peers but keep the current row.
4412    Ties,
4413}
4414
4415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4416pub enum FrameKind {
4417    Rows,
4418    Range,
4419    /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4420    /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4421    /// bounds (no explicit integer offsets) GROUPS behaves identically
4422    /// to RANGE — both consult the peer-group of the current row.
4423    /// Integer offsets are not yet supported; the executor rejects
4424    /// them at run time.
4425    Groups,
4426}
4427
4428#[derive(Debug, Clone, PartialEq, Eq)]
4429pub enum FrameBound {
4430    UnboundedPreceding,
4431    OffsetPreceding(u64),
4432    CurrentRow,
4433    OffsetFollowing(u64),
4434    UnboundedFollowing,
4435    /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4436    /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4437    /// interval is folded to its (months, days, micros) components at
4438    /// parse time.
4439    IntervalPreceding {
4440        months: i32,
4441        days: i32,
4442        micros: i64,
4443    },
4444    IntervalFollowing {
4445        months: i32,
4446        days: i32,
4447        micros: i64,
4448    },
4449}
4450
4451impl fmt::Display for FrameBound {
4452    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4453        match self {
4454            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4455            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4456            Self::CurrentRow => f.write_str("CURRENT ROW"),
4457            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4458            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4459            Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4460            Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4461        }
4462    }
4463}
4464
4465#[derive(Debug, Clone, PartialEq, Eq)]
4466pub enum ExtractField {
4467    Year,
4468    Month,
4469    Day,
4470    Hour,
4471    Minute,
4472    Second,
4473    Microsecond,
4474    /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4475    /// SPG keeps the integer convention — truncated seconds).
4476    Epoch,
4477    /// Day of week, 0 = Sunday … 6 = Saturday.
4478    Dow,
4479    /// ISO day of week, 1 = Monday … 7 = Sunday.
4480    Isodow,
4481    /// Day of year, 1-366.
4482    Doy,
4483    /// ISO 8601 week number, 1-53.
4484    Week,
4485    /// ISO 8601 week-numbering year (pairs with `Week`).
4486    Isoyear,
4487    /// Quarter, 1-4.
4488    Quarter,
4489    /// Year divided by 10 (floor).
4490    Decade,
4491    /// Century — 2001-2100 is century 21.
4492    Century,
4493    /// Millennium — 2001-3000 is millennium 3.
4494    Millennium,
4495    /// Julian day number (truncated for timestamps).
4496    Julian,
4497    /// Seconds and fraction in milliseconds (ss·1000 + frac).
4498    Millisecond,
4499    /// UTC offset in seconds — SPG sessions run UTC, so 0.
4500    Timezone,
4501    /// Hour component of the UTC offset — 0.
4502    TimezoneHour,
4503    /// Minute component of the UTC offset — 0.
4504    TimezoneMinute,
4505    /// v7.39 (round 253) — a field name the parser does not know. PG
4506    /// resolves EXTRACT fields at RUNTIME and reports them with the
4507    /// source type (`unit "nosuch" not recognized for type timestamp
4508    /// without time zone`, 22023), so the parser carries the raw name
4509    /// instead of rejecting.
4510    Other(String),
4511}
4512
4513impl fmt::Display for ExtractField {
4514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4515        f.write_str(match self {
4516            Self::Year => "YEAR",
4517            Self::Month => "MONTH",
4518            Self::Day => "DAY",
4519            Self::Hour => "HOUR",
4520            Self::Minute => "MINUTE",
4521            Self::Second => "SECOND",
4522            Self::Microsecond => "MICROSECOND",
4523            Self::Epoch => "EPOCH",
4524            Self::Dow => "DOW",
4525            Self::Isodow => "ISODOW",
4526            Self::Doy => "DOY",
4527            Self::Week => "WEEK",
4528            Self::Isoyear => "ISOYEAR",
4529            Self::Quarter => "QUARTER",
4530            Self::Decade => "DECADE",
4531            Self::Century => "CENTURY",
4532            Self::Millennium => "MILLENNIUM",
4533            Self::Julian => "JULIAN",
4534            Self::Millisecond => "MILLISECOND",
4535            Self::Timezone => "TIMEZONE",
4536            Self::TimezoneHour => "TIMEZONE_HOUR",
4537            Self::TimezoneMinute => "TIMEZONE_MINUTE",
4538            Self::Other(name) => return f.write_str(name),
4539        })
4540    }
4541}
4542
4543#[derive(Debug, Clone, PartialEq, Eq)]
4544pub enum CastTarget {
4545    Int,
4546    BigInt,
4547    Float,
4548    Text,
4549    Bool,
4550    Vector,
4551    Date,
4552    Timestamp,
4553    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4554    /// H3a. Engine reuses the existing runtime-interval / timestamp
4555    /// paths (parse the text input, return the matching Value).
4556    Interval,
4557    Timestamptz,
4558    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4559    /// types (v7.9.0); the cast just routes Text→Json with the
4560    /// requested OID for the wire layer.
4561    Json,
4562    Jsonb,
4563    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4564    /// compatibility; engine surfaces as Unsupported with a
4565    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4566    RegType,
4567    RegClass,
4568    /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
4569    /// the PG external array form `{a,b,NULL}`.
4570    TextArray,
4571    /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
4572    /// `{1,2,3}` or widens a `TextArray` whose elements are
4573    /// integer-shaped.
4574    IntArray,
4575    BigIntArray,
4576    /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
4577    /// external form text representation. Used by pg_dump output
4578    /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
4579    TsVector,
4580    TsQuery,
4581    /// v7.17.0 — `::uuid`. Decodes the LHS Text via
4582    /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
4583    /// unhyphenated, uppercase, and brace-wrapped forms); malformed
4584    /// input is a SQL error.
4585    Uuid,
4586    /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
4587    /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
4588    /// inputs pass through unchanged. Closes the mailrs D-pre #3
4589    /// reverse-acceptance gap — anywhere a PG schema writes
4590    /// `expr::bytea`, SPG now matches.
4591    Bytea,
4592    /// v7.37.5 ship triage — generic cast target for the long tail
4593    /// of PG type names the parser meets in `expr::TYPE` shapes that
4594    /// don't deserve their own enum variant. The engine routes these
4595    /// through `column_type_to_data_type` + the existing typed
4596    /// `coerce_value` dispatch, so adding a new PG type to SPG
4597    /// implicitly adds its cast-target form too — no parser change
4598    /// per type. The string carries the lowercase PG type ident
4599    /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
4600    /// a clear message when the type isn't known.
4601    Named(String),
4602}
4603
4604impl fmt::Display for CastTarget {
4605    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4606        f.write_str(match self {
4607            Self::Int => "int",
4608            Self::BigInt => "bigint",
4609            Self::Float => "float",
4610            Self::Text => "text",
4611            Self::Bool => "bool",
4612            Self::Vector => "vector",
4613            Self::Interval => "interval",
4614            Self::Timestamptz => "timestamptz",
4615            Self::Json => "json",
4616            Self::Jsonb => "jsonb",
4617            Self::RegType => "regtype",
4618            Self::RegClass => "regclass",
4619            Self::Date => "date",
4620            Self::Timestamp => "timestamp",
4621            Self::TextArray => "TEXT[]",
4622            Self::IntArray => "INT[]",
4623            Self::BigIntArray => "BIGINT[]",
4624            Self::TsVector => "tsvector",
4625            Self::TsQuery => "tsquery",
4626            Self::Uuid => "uuid",
4627            Self::Bytea => "bytea",
4628            // v7.37.5 — `Self::Named` carries its own canonical name.
4629            Self::Named(name) => return f.write_str(name),
4630        })
4631    }
4632}
4633
4634#[derive(Debug, Clone, PartialEq)]
4635pub enum Literal {
4636    Integer(i64),
4637    Float(f64),
4638    /// Exact decimal literal — a bare `12.34`-style token, kept as
4639    /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
4640    /// before it becomes a `Value::Numeric`. PG parses such literals as
4641    /// `numeric`, not `double precision`. (Scientific/huge literals stay
4642    /// `Float`.)
4643    Numeric {
4644        unscaled: i128,
4645        /// v7.39 (round 271) — widened to u16. At u8 a literal with more
4646        /// than 255 decimal places could not be represented, and the
4647        /// conversion's `.expect("lexer-validated decimal")` aborted the
4648        /// query with an internal error on SQL PG accepts.
4649        scale: u16,
4650    },
4651    /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
4652    /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
4653    /// `Value::NumericBig` at eval; previously such literals fell back to double.
4654    NumericBig(String),
4655    String(String),
4656    Bool(bool),
4657    Null,
4658    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
4659    Vector(Vec<f32>),
4660    /// TEXT[] value carried through the prepared-bind path
4661    /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
4662    /// text form, so the array rides the AST natively).
4663    TextArray(Vec<Option<String>>),
4664    /// INT[] value carried through the prepared-bind path.
4665    IntArray(Vec<Option<i32>>),
4666    /// BIGINT[] value carried through the prepared-bind path.
4667    BigIntArray(Vec<Option<i64>>),
4668    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
4669    /// Three independent dimensions: `months` (variable-length;
4670    /// year/month), `days` (fixed 86400 seconds at non-DST, but
4671    /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
4672    /// stays distinguishable), and `micros` (sub-day; can carry).
4673    /// `text` keeps the original spelling so Display round-trips
4674    /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
4675    Interval {
4676        months: i32,
4677        days: i32,
4678        micros: i64,
4679        text: String,
4680    },
4681}
4682
4683#[derive(Debug, Clone, PartialEq, Eq)]
4684pub struct ColumnName {
4685    pub qualifier: Option<String>,
4686    pub name: String,
4687}
4688
4689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4690pub enum BinOp {
4691    Or,
4692    And,
4693    Eq,
4694    NotEq,
4695    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
4696    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
4697    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
4698    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
4699    /// PG-style JOIN ON predicates and pg_dump output.
4700    IsDistinctFrom,
4701    IsNotDistinctFrom,
4702    /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
4703    /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
4704    /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
4705    /// is a real division (round 351).
4706    IntDiv,
4707    Lt,
4708    LtEq,
4709    Gt,
4710    GtEq,
4711    Add,
4712    Sub,
4713    Mul,
4714    Div,
4715    /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
4716    /// precedence as Mul/Div; result type follows left operand.
4717    Mod,
4718    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
4719    /// operands of equal dimension; engine returns `Value::Float(d)`.
4720    L2Distance,
4721    /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
4722    GeomParallel,
4723    /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
4724    OverLeft,
4725    OverRight,
4726    /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
4727    GeomPerp,
4728    /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
4729    GeomSameAs,
4730    /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
4731    /// object to the left-hand one.
4732    ClosestPoint,
4733    /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
4734    GeomHoriz,
4735    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
4736    /// more similar" remains true (matches pgvector's published convention).
4737    InnerProduct,
4738    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
4739    CosineDistance,
4740    /// SQL string concatenation `||`. NULL propagates.
4741    Concat,
4742    /// Bitwise OR `|` on integers.
4743    BitOr,
4744    /// Bitwise AND `&` on integers.
4745    BitAnd,
4746    /// Bitwise XOR `#` on integers and equal-length bit strings.
4747    BitXor,
4748    /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
4749    /// sides as truth values and returns their exclusive-or (`1 XOR 0`
4750    /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
4751    /// MySQL dialect produces it; PG has no logical XOR. Its precedence
4752    /// sits between OR (loosest) and AND.
4753    LogicalXor,
4754    /// v4.14 `json -> key` — element access by string key (object)
4755    /// or integer index (array). Returns a JSON value.
4756    JsonGet,
4757    /// v4.14 `json ->> key` — same access, returns the result as
4758    /// TEXT (unwraps a top-level JSON string; renders other scalars
4759    /// as their canonical text).
4760    JsonGetText,
4761    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
4762    /// text array literal like `'{a,0,b}'`. Returns JSON.
4763    JsonGetPath,
4764    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
4765    JsonGetPathText,
4766    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
4767    /// when every key/value in `sub_json` is structurally present in
4768    /// the left side. Matches PG semantics (top-level + recursive).
4769    JsonContains,
4770    /// `@?` — jsonb path existence (jsonb_path_exists).
4771    JsonPathExists,
4772    /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
4773    /// `a <@ b` is defined as `b @> a` (same semantics, swapped
4774    /// sides). Eval dispatch reuses `JsonContains` with swapped args.
4775    JsonContainedBy,
4776    /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
4777    /// returns BOOL. For an object, true if `key` is an existing
4778    /// member name; for an array, true if any element is the string
4779    /// `key` (PG semantics).
4780    JsonKeyExists,
4781    /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
4782    /// returns BOOL.
4783    JsonKeysAny,
4784    /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
4785    /// returns BOOL.
4786    JsonKeysAll,
4787    /// `jsonb #- path_text[]` — delete the value at a nested path.
4788    /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
4789    JsonDeletePath,
4790    /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
4791    /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
4792    /// tsvector` and engine eval normalises either ordering.
4793    TsMatch,
4794    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
4795    /// `<<`. LHS network is strictly inside RHS network (no equality).
4796    InetContainedBy,
4797    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
4798    /// `<<=`. LHS network ⊆ RHS network.
4799    InetContainedByEq,
4800    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
4801    /// LHS network strictly contains RHS network.
4802    InetContains,
4803    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
4804    /// LHS network ⊇ RHS network.
4805    InetContainsEq,
4806    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
4807    /// True iff either network contains any address of the other.
4808    InetOverlap,
4809    /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
4810    /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
4811    Intersects,
4812    /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
4813    /// (point, box).
4814    IsBelow,
4815    IsAbove,
4816    /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
4817    /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
4818    /// where `'A' < 'a'` is false under a non-C collation, which is the
4819    /// whole reason the operator family exists — it is what makes a LIKE
4820    /// prefix index-usable. pg_dump writes these into index definitions.
4821    PatternLt,
4822    PatternLtEq,
4823    PatternGt,
4824    PatternGtEq,
4825}
4826
4827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4828pub enum UnOp {
4829    Not,
4830    Neg,
4831    /// Bitwise NOT `~` on integers.
4832    BitNot,
4833    /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
4834    /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
4835    /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
4836    /// while PG18 and MariaDB accept every one of them.
4837    ///
4838    /// It is not a no-op to drop at parse time — PG refuses it on
4839    /// non-numeric operands ("operator does not exist: + boolean"), so the
4840    /// operand's type has to be seen at eval.
4841    Plus,
4842}
4843
4844// --- Display impls (round-trip-safe) --------------------------------------
4845
4846impl Statement {
4847    /// v7.18 — classify whether the statement is read-only at
4848    /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
4849    /// route SELECT-shaped traffic through the fan-out
4850    /// `AsyncReadHandle` (no writer-lock contention) while
4851    /// keeping DML / DDL / TX-control on the single-writer path.
4852    ///
4853    /// The classification matches what
4854    /// `Engine::execute_readonly_with_cancel` accepts: anything
4855    /// that does NOT mutate catalog, statistics, session state,
4856    /// or transaction state. WaitForWalPosition is included
4857    /// (engine returns `Unsupported`, but the classification is
4858    /// semantically read-only — no mutation). Empty is excluded
4859    /// out of an abundance of caution — the no-op routes
4860    /// through the writer so any future side effect lands
4861    /// uniformly.
4862    ///
4863    /// **Not connection-state aware**. `SET LOCAL` / `RESET`
4864    /// affect session parameters and must run on the writer
4865    /// engine that owns the session state; they classify as
4866    /// writer-path here. Same for `BEGIN` / `COMMIT` /
4867    /// `ROLLBACK` / `SAVEPOINT` — transaction control is
4868    /// always writer-path.
4869    /// v7.39 (round 435) — does this statement implicitly COMMIT an open
4870    /// transaction under MySQL?
4871    ///
4872    /// PG runs DDL inside the transaction; MySQL commits before (and after)
4873    /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
4874    /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
4875    /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
4876    /// nested START TRANSACTION; and measured NOT to fire for `CREATE
4877    /// TEMPORARY TABLE`, `SET`, or a SELECT.
4878    ///
4879    /// A positive list, not "everything that is not DML": a statement
4880    /// wrongly listed here commits a client's data early, which is as bad as
4881    /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
4882    /// COMPACT) are left out — a MySQL session never sends them.
4883    #[must_use]
4884    pub fn mysql_implicit_commit(&self) -> bool {
4885        match self {
4886            // MySQL's documented exception, measured on MariaDB 11: a
4887            // TEMPORARY table is not DDL for this purpose and does not
4888            // commit. (Round 435 got this for free because the parser then
4889            // lowered that spelling to `Statement::Empty`; round 436 made it
4890            // a real CREATE TABLE, and the round-435 pin caught it.)
4891            Self::CreateTable(c) => !c.temporary,
4892            // MySQL commits the open transaction and opens a fresh one.
4893            Self::Begin { .. }
4894            | Self::DropTable { .. }
4895            | Self::DropIndex { .. }
4896            | Self::CreateIndex(_)
4897            | Self::AlterIndex { .. }
4898            | Self::AlterTable(_)
4899            | Self::Truncate { .. }
4900            | Self::Analyze { .. }
4901            | Self::CreateStatistics { .. }
4902            | Self::DropStatistics { .. }
4903            | Self::CreateView { .. }
4904            | Self::DropView { .. }
4905            | Self::CreateMaterializedView { .. }
4906            | Self::RefreshMaterializedView { .. }
4907            | Self::DropMaterializedView { .. }
4908            | Self::CreateSequence(_)
4909            | Self::AlterSequence { .. }
4910            | Self::DropSequence { .. }
4911            | Self::CreateFunction(_)
4912            | Self::DropFunction { .. }
4913            | Self::CreateTrigger(_)
4914            | Self::DropTrigger { .. }
4915            | Self::CreateRule(_)
4916            | Self::DropRule { .. }
4917            | Self::CreateType(_)
4918            | Self::DropType { .. }
4919            | Self::AlterTypeAddValue { .. }
4920            | Self::AlterTypeRenameValue { .. }
4921            | Self::CreateDomain(_)
4922            | Self::AlterDomain { .. }
4923            | Self::DropDomain { .. }
4924            | Self::CreateSchema { .. }
4925            | Self::DropSchema { .. }
4926            | Self::CreateUser { .. }
4927            | Self::DropUser { .. }
4928            | Self::Grant { .. }
4929            | Self::Revoke { .. }
4930            | Self::CreatePolicy(_)
4931            | Self::AlterPolicy(_)
4932            | Self::DropPolicy { .. }
4933            | Self::CommentOn { .. }
4934            | Self::CreateExtension { .. } => true,
4935            _ => false,
4936        }
4937    }
4938
4939    #[must_use]
4940    pub fn is_readonly(&self) -> bool {
4941        match self {
4942            // v7.39 (round 288) — SET CONSTRAINTS changes transaction
4943            // state, and IMMEDIATE can run the deferred checks there and
4944            // then; writer-path.
4945            Statement::SetConstraints { .. } => false,
4946            // v7.39 (round 695) — it writes nothing (SPG has no
4947            // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
4948            // writer and a read-only session refuses it there too.
4949            Statement::AlterSystem { .. } => false,
4950            // Same shape: a no-op here, a writer to PG, so a read-only
4951            // session refuses it as PG's would.
4952            Statement::NoOpPreventedInTransaction { .. } => false,
4953            Statement::DropDatabase { .. } => false,
4954            // v7.39 (round 696) — they perform nothing, so nothing is
4955            // written; PG classes LOCK and the OWNED BY pair as writers and
4956            // a read-only session refuses them there.
4957            Statement::ValidateOnly { .. } => false,
4958            // v7.39 (round 750) — a credential rotation persists.
4959            Statement::AlterRolePassword { .. } => true,
4960            Statement::DropAggregate { .. } => false,
4961            // v7.39 (round 547) — records a GUC default in the catalog.
4962            Statement::SetDbRoleSetting(_) => false,
4963            // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
4964            // but they name a relation and PG refuses one that is not
4965            // there, so they are not read-only in the sense this asks.
4966            Statement::Maintain { .. } => false,
4967            // v7.39 (round 277) — the prepared-statement surface is
4968            // session state, like SET; writer-path so it lands on the
4969            // engine that owns the session. EXECUTE may also run a
4970            // write, and its body is only known at execution time.
4971            Statement::Prepare { .. }
4972            | Statement::Execute { .. }
4973            | Statement::Deallocate(_)
4974            | Statement::Call(_)
4975            | Statement::PrepareTransaction(_)
4976            | Statement::CreateStatistics { .. }
4977            | Statement::DropStatistics { .. }
4978            // v7.39 (round 318, V51) — KILL signals another connection;
4979            // it must run on the writer path that owns the registry hook.
4980            | Statement::Kill { .. }
4981            // v7.39 (round 320, V53) — DISCARD throws session state away;
4982            // writer path, like SET / RESET.
4983            | Statement::Discard(_) => false,
4984            // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
4985            // locks MUTATES the lock table, so it is not a read. Left as
4986            // a read it went to the read-only executor and the locking
4987            // pre-pass never ran at all — the clause was honoured only
4988            // inside an explicit transaction, and silently ignored in
4989            // autocommit, which is where a queue worker runs it.
4990            Statement::Select(s) if s.locking.is_some() => false,
4991            Statement::Select(_)
4992            | Statement::CopyTo { .. }
4993            | Statement::CopyToFile { .. }
4994            | Statement::Explain(_)
4995            | Statement::ShowTables
4996            | Statement::ShowDatabases
4997            | Statement::ShowCreateTable(_)
4998            | Statement::ShowIndexes(_)
4999            | Statement::ShowStatus
5000            | Statement::ShowVariables
5001            | Statement::ShowProcesslist
5002            | Statement::ShowColumns(_)
5003            | Statement::ShowUsers
5004            | Statement::ShowPublications
5005            | Statement::ShowSubscriptions
5006            | Statement::WaitForWalPosition { .. } => true,
5007            // Everything else mutates catalog, statistics,
5008            // session state, or transaction state — writer path.
5009            // Listed explicitly so a new Statement variant fails
5010            // the match exhaustiveness check and forces a
5011            // classification decision at add-site.
5012            Statement::Empty
5013            // v7.39 (round 169) — VACUUM mutates storage (reclaims
5014            // tombstoned versions): writer path.
5015            | Statement::Vacuum { .. }
5016            | Statement::DropTable { .. }
5017            | Statement::DropIndex { .. }
5018            | Statement::CreateTable(_)
5019            | Statement::CreateExtension(_)
5020            | Statement::DoBlock(_)
5021            | Statement::CreateIndex(_)
5022            | Statement::Insert(_)
5023            | Statement::Update(_)
5024            | Statement::Delete(_)
5025            | Statement::Merge(_)
5026            | Statement::Begin(_)
5027            | Statement::Commit
5028            | Statement::Rollback
5029            | Statement::Savepoint(_)
5030            | Statement::RollbackToSavepoint(_)
5031            | Statement::ReleaseSavepoint(_)
5032            | Statement::CreateUser(_)
5033            | Statement::DropUser { .. }
5034            | Statement::SetRole(_)
5035            | Statement::Grant(_)
5036            | Statement::Revoke(_)
5037            | Statement::CreatePolicy(_)
5038            | Statement::AlterPolicy(_)
5039            | Statement::DropPolicy(_)
5040            | Statement::AlterIndex(_)
5041            | Statement::AlterTable(_)
5042            | Statement::CreatePublication(_)
5043            | Statement::DropPublication { .. }
5044            | Statement::CreateSubscription(_)
5045            | Statement::DropSubscription { .. }
5046            | Statement::Analyze(_)
5047            | Statement::Truncate { .. }
5048            | Statement::CompactColdSegments
5049            | Statement::SetParameter { .. }
5050            | Statement::SetParameterList(_)
5051            | Statement::SetUserVars(..)
5052            | Statement::SetTransaction { .. }
5053            | Statement::ShowParameter(_)
5054            | Statement::ResetParameter(_)
5055            | Statement::CreateFunction(_)
5056            | Statement::CreateTrigger(_)
5057            | Statement::DropTrigger { .. }
5058            | Statement::CreateRule(_)
5059            | Statement::DropRule { .. }
5060            | Statement::DropFunction { .. }
5061            | Statement::CreateSequence(_)
5062            | Statement::AlterSequence(_)
5063            | Statement::DropSequence { .. }
5064            | Statement::CreateView(_)
5065            | Statement::DropView { .. }
5066            | Statement::CreateMaterializedView(_)
5067            | Statement::RefreshMaterializedView { .. }
5068            | Statement::DropMaterializedView { .. }
5069            | Statement::CreateType(_)
5070            | Statement::AlterTypeAddValue { .. }
5071            | Statement::AlterTypeRenameValue { .. }
5072            | Statement::CommentOn { .. }
5073            | Statement::DropType { .. }
5074            | Statement::CreateDomain(_)
5075            | Statement::DropDomain { .. }
5076            | Statement::CreateSchema { .. }
5077            | Statement::DropSchema { .. }
5078            // v7.39 (round 218) — cursors mutate per-session cursor state
5079            // (open/position/close) on the writer engine: writer path.
5080            | Statement::DeclareCursor { .. }
5081            | Statement::FetchCursor { .. }
5082            | Statement::MoveCursor { .. }
5083            | Statement::CloseCursor { .. }
5084            // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5085            // state / the notification queue: writer path.
5086            | Statement::Listen(_)
5087            | Statement::Notify { .. }
5088            | Statement::Unlisten(_)
5089            | Statement::CopyFromFile { .. }
5090            | Statement::AlterDomain { .. } => false,
5091        }
5092    }
5093}
5094
5095/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5096/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5097#[derive(Debug, Clone, PartialEq, Eq)]
5098pub struct GrantStatement {
5099    /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5100    /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5101    /// is why they keep the case the user typed.
5102    pub privileges: Vec<GrantPriv>,
5103    /// What the privileges are on.
5104    pub object: GrantObject,
5105    /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5106    pub grantees: Vec<String>,
5107    /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5108    /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5109    /// privilege itself).
5110    pub grant_option: bool,
5111}
5112
5113/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5114/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5115/// An empty column list means the privilege is table-wide.
5116#[derive(Debug, Clone, PartialEq, Eq)]
5117pub struct GrantPriv {
5118    pub word: String,
5119    pub columns: Vec<String>,
5120}
5121
5122/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5123/// privileges; every other object class parses and is accepted as a no-op, so
5124/// a pg_dump that grants on schemas / sequences / functions still restores.
5125#[derive(Debug, Clone, PartialEq, Eq)]
5126pub enum GrantObject {
5127    /// `ON [TABLE] a, b` — the enforced case.
5128    Tables(Vec<String>),
5129    /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5130    /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5131    /// granted roles; the grantees are the members.
5132    Roles(Vec<String>),
5133    /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5134    /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5135    Sequences(Vec<String>),
5136    /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5137    Schemas(Vec<String>),
5138    /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5139    Databases(Vec<String>),
5140    /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5141    /// (SPG keys functions by name); the argument list parses and is dropped.
5142    Functions(Vec<(String, Option<Vec<String>>)>),
5143    /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5144    /// every table at GRANT time, exactly like PG.
5145    AllTablesInSchema,
5146    /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5147    /// message.
5148    Other(String),
5149}
5150
5151impl GrantStatement {
5152    /// Round-trip text. `grant = false` renders the REVOKE form.
5153    fn render(&self, grant: bool) -> alloc::string::String {
5154        use core::fmt::Write as _;
5155        let mut s = alloc::string::String::new();
5156        let privs = if self.privileges.is_empty() {
5157            alloc::string::String::from("ALL")
5158        } else {
5159            let parts: Vec<_> = self
5160                .privileges
5161                .iter()
5162                .map(|p| {
5163                    if p.columns.is_empty() {
5164                        p.word.clone()
5165                    } else {
5166                        let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5167                        alloc::format!("{} ({})", p.word, cols.join(", "))
5168                    }
5169                })
5170                .collect();
5171            parts.join(", ")
5172        };
5173        let obj = match &self.object {
5174            GrantObject::Tables(t) => {
5175                let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5176                alloc::format!("TABLE {}", names.join(", "))
5177            }
5178            GrantObject::Roles(r) => {
5179                let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5180                names.join(", ")
5181            }
5182            GrantObject::Sequences(n) => {
5183                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5184                alloc::format!("SEQUENCE {}", names.join(", "))
5185            }
5186            GrantObject::Schemas(n) => {
5187                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5188                alloc::format!("SCHEMA {}", names.join(", "))
5189            }
5190            GrantObject::Databases(n) => {
5191                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5192                alloc::format!("DATABASE {}", names.join(", "))
5193            }
5194            GrantObject::Functions(n) => {
5195                let names: Vec<_> = n
5196                    .iter()
5197                    .map(|(name, args)| match args {
5198                        Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5199                        None => quote_ident(name),
5200                    })
5201                    .collect();
5202                alloc::format!("FUNCTION {}", names.join(", "))
5203            }
5204            GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5205            GrantObject::Other(k) => k.clone(),
5206        };
5207        let who: Vec<_> = self
5208            .grantees
5209            .iter()
5210            .map(|g| {
5211                if g.is_empty() {
5212                    "PUBLIC".into()
5213                } else {
5214                    quote_ident(g)
5215                }
5216            })
5217            .collect();
5218        if let GrantObject::Roles(_) = &self.object {
5219            let _ = if grant {
5220                write!(s, "GRANT {obj} TO {}", who.join(", "))
5221            } else {
5222                write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5223            };
5224            return s;
5225        }
5226        if grant {
5227            let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5228            if self.grant_option {
5229                s.push_str(" WITH GRANT OPTION");
5230            }
5231        } else {
5232            s.push_str("REVOKE ");
5233            if self.grant_option {
5234                s.push_str("GRANT OPTION FOR ");
5235            }
5236            let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5237        }
5238        s
5239    }
5240}
5241
5242impl fmt::Display for Statement {
5243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5244        match self {
5245            Self::Empty => Ok(()),
5246            // v7.39 (round 695) — deparsed the way PG writes it.
5247            // v7.39 (round 696) — never deparsed into a dump (nothing is
5248            // stored), so the shortest faithful spelling of what it was.
5249            Self::DropAggregate { if_exists, items } => {
5250                f.write_str("DROP AGGREGATE ")?;
5251                if *if_exists {
5252                    f.write_str("IF EXISTS ")?;
5253                }
5254                for (i, (name, args)) in items.iter().enumerate() {
5255                    if i > 0 {
5256                        f.write_str(", ")?;
5257                    }
5258                    match args {
5259                        Some(a) => write!(f, "{name}({})", a.join(", "))?,
5260                        None => write!(f, "{name}(*)")?,
5261                    }
5262                }
5263                Ok(())
5264            }
5265            Self::AlterRolePassword { name, password } => {
5266                write!(f, "ALTER ROLE {}", quote_ident(name))?;
5267                match password {
5268                    Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5269                    None => f.write_str(" PASSWORD NULL"),
5270                }
5271            }
5272            Self::ValidateOnly { kind, names } => match kind {
5273                ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5274                ValidateOnlyKind::RoleName => {
5275                    write!(f, "DROP OWNED BY {}", names.join(", "))
5276                }
5277                ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5278                ValidateOnlyKind::ExtensionAvailable => {
5279                    write!(f, "CREATE EXTENSION {}", names.join(", "))
5280                }
5281                ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5282                ValidateOnlyKind::CollationName => {
5283                    write!(f, "DROP COLLATION {}", names.join(", "))
5284                }
5285                ValidateOnlyKind::TsConfigName => {
5286                    write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5287                }
5288                ValidateOnlyKind::EventTriggerName => {
5289                    write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5290                }
5291                ValidateOnlyKind::TablespaceName => {
5292                    write!(f, "DROP TABLESPACE {}", names.join(", "))
5293                }
5294                ValidateOnlyKind::LargeObjectOid => {
5295                    write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5296                }
5297                ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5298                ValidateOnlyKind::AggregateName => {
5299                    write!(f, "ALTER AGGREGATE {}", names.join(", "))
5300                }
5301                ValidateOnlyKind::ConversionName => {
5302                    write!(f, "DROP CONVERSION {}", names.join(", "))
5303                }
5304                ValidateOnlyKind::LanguageName => {
5305                    write!(f, "DROP LANGUAGE {}", names.join(", "))
5306                }
5307                ValidateOnlyKind::ExtensionInstalled => {
5308                    write!(f, "DROP EXTENSION {}", names.join(", "))
5309                }
5310            },
5311            Self::AlterSystem { parameter } => match parameter {
5312                Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5313                None => f.write_str("ALTER SYSTEM RESET ALL"),
5314            },
5315            // v7.39 (round 547) — round-trips as PG writes it.
5316            Self::SetDbRoleSetting(st) => {
5317                match (&st.database, &st.role) {
5318                    (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5319                    (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5320                    (None, None) => f.write_str("ALTER ROLE ALL")?,
5321                }
5322                if let (Some(d), Some(_)) = (&st.database, &st.role) {
5323                    write!(f, " IN DATABASE {d}")?;
5324                }
5325                match (&st.param, &st.value) {
5326                    (None, _) => f.write_str(" RESET ALL"),
5327                    (Some(p), None) => write!(f, " RESET {p}"),
5328                    (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5329                }
5330            }
5331            Self::Maintain {
5332                kind,
5333                concurrently,
5334                target,
5335            } => {
5336                f.write_str(match kind {
5337                    crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5338                    _ => "REINDEX ",
5339                })?;
5340                if *concurrently {
5341                    f.write_str("CONCURRENTLY ")?;
5342                }
5343                if let Some(t) = target {
5344                    f.write_str(t)?;
5345                }
5346                Ok(())
5347            }
5348            Self::DropDatabase { name, if_exists } => {
5349                f.write_str("DROP DATABASE ")?;
5350                if *if_exists {
5351                    f.write_str("IF EXISTS ")?;
5352                }
5353                f.write_str(name)
5354            }
5355            Self::NoOpPreventedInTransaction { what } => f.write_str(what),
5356            Self::SetConstraints { names, deferred } => {
5357                f.write_str("SET CONSTRAINTS ")?;
5358                if names.is_empty() {
5359                    f.write_str("ALL")?;
5360                } else {
5361                    for (i, n) in names.iter().enumerate() {
5362                        if i > 0 {
5363                            f.write_str(", ")?;
5364                        }
5365                        f.write_str(n)?;
5366                    }
5367                }
5368                f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5369            }
5370            // v7.39 (round 277) — the source text is kept verbatim so
5371            // `pg_prepared_statements.statement` can report it the way
5372            // PG does (the whole PREPARE statement, not just the body).
5373            Self::Prepare { source, .. } => f.write_str(source),
5374            Self::Execute { name, args } => {
5375                write!(f, "EXECUTE {}", quote_ident(name))?;
5376                if !args.is_empty() {
5377                    f.write_str("(")?;
5378                    for (i, a) in args.iter().enumerate() {
5379                        if i > 0 {
5380                            f.write_str(", ")?;
5381                        }
5382                        write!(f, "{a}")?;
5383                    }
5384                    f.write_str(")")?;
5385                }
5386                Ok(())
5387            }
5388            Self::CreateStatistics {
5389                name,
5390                if_not_exists,
5391                kinds,
5392                columns,
5393                table,
5394            } => {
5395                f.write_str("CREATE STATISTICS ")?;
5396                if *if_not_exists {
5397                    f.write_str("IF NOT EXISTS ")?;
5398                }
5399                write!(f, "{}", quote_ident(name))?;
5400                if !kinds.is_empty() {
5401                    write!(f, " ({})", kinds.join(", "))?;
5402                }
5403                write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5404            }
5405            Self::DropStatistics { name, if_exists } => {
5406                f.write_str("DROP STATISTICS ")?;
5407                if *if_exists {
5408                    f.write_str("IF EXISTS ")?;
5409                }
5410                write!(f, "{}", quote_ident(name))
5411            }
5412            Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5413            Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5414            Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5415            Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5416            Self::DeclareCursor {
5417                name,
5418                scroll,
5419                hold,
5420                query,
5421            } => {
5422                write!(f, "DECLARE {} ", quote_ident(name))?;
5423                match scroll {
5424                    Some(true) => f.write_str("SCROLL ")?,
5425                    Some(false) => f.write_str("NO SCROLL ")?,
5426                    None => {}
5427                }
5428                f.write_str("CURSOR ")?;
5429                if *hold {
5430                    f.write_str("WITH HOLD ")?;
5431                }
5432                write!(f, "FOR {query}")
5433            }
5434            Self::FetchCursor { name, direction } => {
5435                write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5436            }
5437            Self::MoveCursor { name, direction } => {
5438                write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5439            }
5440            Self::CloseCursor { name } => match name {
5441                Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5442                None => f.write_str("CLOSE ALL"),
5443            },
5444            Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5445            Self::Notify { channel, payload } => {
5446                write!(f, "NOTIFY {}", quote_ident(channel))?;
5447                if let Some(p) = payload {
5448                    write!(f, ", '{}'", p.replace('\'', "''"))?;
5449                }
5450                Ok(())
5451            }
5452            Self::Unlisten(ch) => match ch {
5453                Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5454                None => f.write_str("UNLISTEN *"),
5455            },
5456            Self::CopyTo {
5457                table,
5458                columns,
5459                query,
5460                options,
5461            } => {
5462                if let Some(q) = query {
5463                    write!(f, "COPY ({q})")?;
5464                } else {
5465                    write!(f, "COPY {table}")?;
5466                    if let Some(cols) = columns {
5467                        write!(f, " ({})", cols.join(", "))?;
5468                    }
5469                }
5470                write!(f, " TO STDOUT")?;
5471                let mut parts: Vec<String> = Vec::new();
5472                if options.format == CopyFormat::Csv {
5473                    parts.push("FORMAT csv".to_string());
5474                }
5475                if options.header {
5476                    parts.push("HEADER true".to_string());
5477                }
5478                if let Some(d) = options.delimiter {
5479                    parts.push(alloc::format!("DELIMITER '{d}'"));
5480                }
5481                if let Some(n) = &options.null_str {
5482                    parts.push(alloc::format!("NULL '{n}'"));
5483                }
5484                if let Some(q) = options.quote {
5485                    parts.push(alloc::format!("QUOTE '{q}'"));
5486                }
5487                if !parts.is_empty() {
5488                    write!(f, " WITH ({})", parts.join(", "))?;
5489                }
5490                Ok(())
5491            }
5492            Self::CopyFromFile {
5493                table,
5494                columns,
5495                path,
5496                options,
5497            } => {
5498                write!(f, "COPY {table}")?;
5499                if let Some(cols) = columns {
5500                    write!(f, " ({})", cols.join(", "))?;
5501                }
5502                write!(f, " FROM '{path}'")?;
5503                let mut parts: Vec<String> = Vec::new();
5504                if options.format == CopyFormat::Csv {
5505                    parts.push("FORMAT csv".to_string());
5506                }
5507                if options.header {
5508                    parts.push("HEADER true".to_string());
5509                }
5510                if let Some(d) = options.delimiter {
5511                    parts.push(alloc::format!("DELIMITER '{d}'"));
5512                }
5513                if let Some(n) = &options.null_str {
5514                    parts.push(alloc::format!("NULL '{n}'"));
5515                }
5516                if let Some(q) = options.quote {
5517                    parts.push(alloc::format!("QUOTE '{q}'"));
5518                }
5519                if !parts.is_empty() {
5520                    write!(f, " WITH ({})", parts.join(", "))?;
5521                }
5522                Ok(())
5523            }
5524            Self::CopyToFile {
5525                table,
5526                columns,
5527                query,
5528                path,
5529                options,
5530            } => {
5531                if let Some(q) = query {
5532                    write!(f, "COPY ({q})")?;
5533                } else {
5534                    write!(f, "COPY {table}")?;
5535                    if let Some(cols) = columns {
5536                        write!(f, " ({})", cols.join(", "))?;
5537                    }
5538                }
5539                write!(f, " TO '{path}'")?;
5540                let mut parts: Vec<String> = Vec::new();
5541                if options.format == CopyFormat::Csv {
5542                    parts.push("FORMAT csv".to_string());
5543                }
5544                if options.header {
5545                    parts.push("HEADER true".to_string());
5546                }
5547                if let Some(d) = options.delimiter {
5548                    parts.push(alloc::format!("DELIMITER '{d}'"));
5549                }
5550                if let Some(n) = &options.null_str {
5551                    parts.push(alloc::format!("NULL '{n}'"));
5552                }
5553                if let Some(q) = options.quote {
5554                    parts.push(alloc::format!("QUOTE '{q}'"));
5555                }
5556                if !parts.is_empty() {
5557                    write!(f, " WITH ({})", parts.join(", "))?;
5558                }
5559                Ok(())
5560            }
5561            Self::AlterDomain { name, action } => {
5562                write!(f, "ALTER DOMAIN {name} ")?;
5563                match action {
5564                    AlterDomainAction::AddConstraint { name: cn, check } => match cn {
5565                        Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
5566                        None => write!(f, "ADD CHECK ({check})"),
5567                    },
5568                    AlterDomainAction::DropConstraint {
5569                        name: cn,
5570                        if_exists,
5571                    } => {
5572                        if *if_exists {
5573                            write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
5574                        } else {
5575                            write!(f, "DROP CONSTRAINT {cn}")
5576                        }
5577                    }
5578                    AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
5579                    AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
5580                    AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
5581                    AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
5582                    AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
5583                }
5584            }
5585            Self::Truncate {
5586                tables,
5587                restart_identity,
5588                cascade,
5589                only,
5590            } => {
5591                f.write_str("TRUNCATE TABLE ")?;
5592                if *only {
5593                    f.write_str("ONLY ")?;
5594                }
5595                for (i, t) in tables.iter().enumerate() {
5596                    if i > 0 {
5597                        f.write_str(", ")?;
5598                    }
5599                    f.write_str(t)?;
5600                }
5601                if *restart_identity {
5602                    f.write_str(" RESTART IDENTITY")?;
5603                }
5604                if *cascade {
5605                    f.write_str(" CASCADE")?;
5606                }
5607                Ok(())
5608            }
5609            Self::DropTable { names, if_exists } => {
5610                f.write_str("DROP TABLE ")?;
5611                if *if_exists {
5612                    f.write_str("IF EXISTS ")?;
5613                }
5614                for (i, n) in names.iter().enumerate() {
5615                    if i > 0 {
5616                        f.write_str(", ")?;
5617                    }
5618                    write!(f, "{}", quote_ident(n))?;
5619                }
5620                Ok(())
5621            }
5622            Self::DropIndex { name, if_exists } => {
5623                f.write_str("DROP INDEX ")?;
5624                if *if_exists {
5625                    f.write_str("IF EXISTS ")?;
5626                }
5627                write!(f, "{}", quote_ident(name))
5628            }
5629            Self::Select(s) => s.fmt(f),
5630            Self::CreateTable(s) => s.fmt(f),
5631            Self::CreateIndex(s) => s.fmt(f),
5632            Self::Insert(s) => s.fmt(f),
5633            Self::Update(s) => s.fmt(f),
5634            Self::Delete(s) => s.fmt(f),
5635            Self::Merge(s) => s.fmt(f),
5636            Self::Vacuum { table, analyze } => {
5637                f.write_str("VACUUM")?;
5638                if *analyze {
5639                    f.write_str(" ANALYZE")?;
5640                }
5641                if let Some(t) = table {
5642                    write!(f, " {}", quote_ident(t))?;
5643                }
5644                Ok(())
5645            }
5646            Self::Begin(None) => f.write_str("BEGIN"),
5647            Self::Begin(Some(level)) => write!(f, "BEGIN ISOLATION LEVEL {level}"),
5648            Self::Commit => f.write_str("COMMIT"),
5649            Self::Rollback => f.write_str("ROLLBACK"),
5650            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
5651            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
5652            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
5653            Self::ShowTables => f.write_str("SHOW TABLES"),
5654            Self::ShowDatabases => f.write_str("SHOW DATABASES"),
5655            Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
5656            Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
5657            Self::ShowStatus => f.write_str("SHOW STATUS"),
5658            Self::ShowVariables => f.write_str("SHOW VARIABLES"),
5659            Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
5660            Self::Discard(t) => write!(f, "DISCARD {t}"),
5661            Self::Kill { query_only, id } => {
5662                if *query_only {
5663                    write!(f, "KILL QUERY {id}")
5664                } else {
5665                    write!(f, "KILL CONNECTION {id}")
5666                }
5667            }
5668            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
5669            Self::CreateUser(s) => write!(
5670                f,
5671                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
5672                quote_ident(&s.name),
5673                s.role
5674            ),
5675            Self::DropUser { name, if_exists } => {
5676                let ie = if *if_exists { "IF EXISTS " } else { "" };
5677                write!(f, "DROP USER {ie}{}", quote_ident(name))
5678            }
5679            Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
5680            Self::SetRole(None) => f.write_str("RESET ROLE"),
5681            Self::Grant(g) => write!(f, "{}", g.render(true)),
5682            Self::Revoke(g) => write!(f, "{}", g.render(false)),
5683            Self::CreatePolicy(s) => {
5684                write!(
5685                    f,
5686                    "CREATE POLICY {} ON {}",
5687                    quote_ident(&s.name),
5688                    quote_ident(&s.table)
5689                )?;
5690                if !s.permissive {
5691                    f.write_str(" AS RESTRICTIVE")?;
5692                }
5693                if !matches!(s.cmd, PolicyCmd::All) {
5694                    let w = match s.cmd {
5695                        PolicyCmd::Select => "SELECT",
5696                        PolicyCmd::Insert => "INSERT",
5697                        PolicyCmd::Update => "UPDATE",
5698                        PolicyCmd::Delete => "DELETE",
5699                        PolicyCmd::All => unreachable!(),
5700                    };
5701                    write!(f, " FOR {w}")?;
5702                }
5703                if !s.roles.is_empty() {
5704                    write!(f, " TO {}", s.roles.join(", "))?;
5705                }
5706                if let Some(u) = &s.using {
5707                    write!(f, " USING ({u})")?;
5708                }
5709                if let Some(c) = &s.with_check {
5710                    write!(f, " WITH CHECK ({c})")?;
5711                }
5712                Ok(())
5713            }
5714            Self::AlterPolicy(s) => {
5715                write!(
5716                    f,
5717                    "ALTER POLICY {} ON {}",
5718                    quote_ident(&s.name),
5719                    quote_ident(&s.table)
5720                )?;
5721                if let Some(nn) = &s.rename_to {
5722                    return write!(f, " RENAME TO {}", quote_ident(nn));
5723                }
5724                if let Some(roles) = &s.roles {
5725                    write!(f, " TO {}", roles.join(", "))?;
5726                }
5727                if let Some(u) = &s.using {
5728                    write!(f, " USING ({u})")?;
5729                }
5730                if let Some(c) = &s.with_check {
5731                    write!(f, " WITH CHECK ({c})")?;
5732                }
5733                Ok(())
5734            }
5735            Self::DropPolicy(s) => {
5736                f.write_str("DROP POLICY ")?;
5737                if s.if_exists {
5738                    f.write_str("IF EXISTS ")?;
5739                }
5740                write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
5741            }
5742            Self::ShowUsers => f.write_str("SHOW USERS"),
5743            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
5744            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
5745            Self::CreateSubscription(s) => {
5746                write!(
5747                    f,
5748                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
5749                    quote_ident(&s.name),
5750                    s.conn_str.replace('\'', "''")
5751                )?;
5752                for (i, p) in s.publications.iter().enumerate() {
5753                    if i > 0 {
5754                        f.write_str(", ")?;
5755                    }
5756                    write!(f, "{}", quote_ident(p))?;
5757                }
5758                Ok(())
5759            }
5760            Self::DropSubscription { name, if_exists } => {
5761                let opt = if *if_exists { "IF EXISTS " } else { "" };
5762                write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
5763            }
5764            Self::WaitForWalPosition { pos, timeout_ms } => {
5765                write!(f, "WAIT FOR WAL POSITION {pos}")?;
5766                if let Some(ms) = timeout_ms {
5767                    write!(f, " WITH TIMEOUT {ms}")?;
5768                }
5769                Ok(())
5770            }
5771            Self::Analyze(None) => f.write_str("ANALYZE"),
5772            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
5773            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
5774            Self::Explain(e) => {
5775                if e.suggest {
5776                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
5777                } else if e.analyze {
5778                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
5779                } else {
5780                    write!(f, "EXPLAIN {}", e.inner)
5781                }
5782            }
5783            Self::AlterIndex(a) => {
5784                write!(f, "ALTER INDEX ")?;
5785                match &a.target {
5786                    // Parameters are consumed, not stored; the shortest
5787                    // faithful spelling.
5788                    AlterIndexTarget::StorageParams => {
5789                        write!(f, "{} SET ()", quote_ident(&a.name))
5790                    }
5791                    AlterIndexTarget::Rebuild { encoding } => {
5792                        write!(f, "{} REBUILD", quote_ident(&a.name))?;
5793                        if let Some(enc) = encoding {
5794                            write!(f, " WITH (encoding = {enc})")?;
5795                        }
5796                        Ok(())
5797                    }
5798                    AlterIndexTarget::Rename { new, if_exists } => {
5799                        if *if_exists {
5800                            f.write_str("IF EXISTS ")?;
5801                        }
5802                        write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
5803                    }
5804                }
5805            }
5806            Self::AlterTable(a) => {
5807                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
5808                for (i, t) in a.targets.iter().enumerate() {
5809                    if i > 0 {
5810                        f.write_str(", ")?;
5811                    }
5812                    fmt_alter_target(f, t)?;
5813                }
5814                Ok(())
5815            }
5816            Self::CreatePublication(p) => {
5817                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
5818                match &p.scope {
5819                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
5820                    PublicationScope::ForTables(ts) => {
5821                        f.write_str(" FOR TABLE ")?;
5822                        for (i, t) in ts.iter().enumerate() {
5823                            if i > 0 {
5824                                f.write_str(", ")?;
5825                            }
5826                            write!(f, "{}", quote_ident(t))?;
5827                        }
5828                        Ok(())
5829                    }
5830                    PublicationScope::TablesInSchema(schema) => {
5831                        write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
5832                        Ok(())
5833                    }
5834                    PublicationScope::AllTablesExcept(ts) => {
5835                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
5836                        for (i, t) in ts.iter().enumerate() {
5837                            if i > 0 {
5838                                f.write_str(", ")?;
5839                            }
5840                            write!(f, "{}", quote_ident(t))?;
5841                        }
5842                        Ok(())
5843                    }
5844                }
5845            }
5846            Self::CreateExtension(name) => {
5847                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
5848            }
5849            Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
5850            Self::DropPublication { name, if_exists } => {
5851                let opt = if *if_exists { "IF EXISTS " } else { "" };
5852                write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
5853            }
5854            Self::SetParameter { name, value, local } => {
5855                write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
5856                match value {
5857                    SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
5858                    SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
5859                    SetValue::Default => f.write_str("DEFAULT"),
5860                }
5861            }
5862            Self::SetTransaction { isolation } => {
5863                write!(f, "SET TRANSACTION ISOLATION LEVEL ")?;
5864                let name = match isolation {
5865                    IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
5866                    IsolationLevel::ReadCommitted => "READ COMMITTED",
5867                    IsolationLevel::RepeatableRead => "REPEATABLE READ",
5868                    IsolationLevel::Serializable => "SERIALIZABLE",
5869                };
5870                f.write_str(name)
5871            }
5872            Self::ShowParameter(name) => write!(f, "SHOW {name}"),
5873            Self::SetUserVars(assigns, _) => {
5874                f.write_str("SET ")?;
5875                for (i, (name, value)) in assigns.iter().enumerate() {
5876                    if i > 0 {
5877                        f.write_str(", ")?;
5878                    }
5879                    write!(f, "@{name} = {value}")?;
5880                }
5881                Ok(())
5882            }
5883            Self::SetParameterList(pairs) => {
5884                f.write_str("SET ")?;
5885                for (i, (name, value)) in pairs.iter().enumerate() {
5886                    if i > 0 {
5887                        f.write_str(", ")?;
5888                    }
5889                    write!(f, "{name} = ")?;
5890                    match value {
5891                        SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
5892                        SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
5893                        SetValue::Default => f.write_str("DEFAULT")?,
5894                    }
5895                }
5896                Ok(())
5897            }
5898            Self::ResetParameter(None) => f.write_str("RESET ALL"),
5899            Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
5900            Self::CreateFunction(s) => s.fmt(f),
5901            Self::CreateTrigger(s) => s.fmt(f),
5902            Self::DropTrigger {
5903                name,
5904                table,
5905                if_exists,
5906            } => {
5907                f.write_str("DROP TRIGGER ")?;
5908                if *if_exists {
5909                    f.write_str("IF EXISTS ")?;
5910                }
5911                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
5912            }
5913            Self::DropFunction {
5914                name,
5915                args,
5916                if_exists,
5917            } => {
5918                f.write_str("DROP FUNCTION ")?;
5919                if *if_exists {
5920                    f.write_str("IF EXISTS ")?;
5921                }
5922                write!(f, "{}", quote_ident(name))?;
5923                if let Some(a) = args {
5924                    write!(f, "({})", a.join(", "))?;
5925                }
5926                Ok(())
5927            }
5928            Self::CreateSequence(s) => s.fmt(f),
5929            Self::AlterSequence(s) => s.fmt(f),
5930            Self::DropSequence { names, if_exists } => {
5931                f.write_str("DROP SEQUENCE ")?;
5932                if *if_exists {
5933                    f.write_str("IF EXISTS ")?;
5934                }
5935                for (i, n) in names.iter().enumerate() {
5936                    if i > 0 {
5937                        f.write_str(", ")?;
5938                    }
5939                    write!(f, "{}", quote_ident(n))?;
5940                }
5941                Ok(())
5942            }
5943            Self::CreateView(v) => v.fmt(f),
5944            Self::DropView { names, if_exists } => {
5945                f.write_str("DROP VIEW ")?;
5946                if *if_exists {
5947                    f.write_str("IF EXISTS ")?;
5948                }
5949                for (i, n) in names.iter().enumerate() {
5950                    if i > 0 {
5951                        f.write_str(", ")?;
5952                    }
5953                    write!(f, "{}", quote_ident(n))?;
5954                }
5955                Ok(())
5956            }
5957            Self::CreateMaterializedView(v) => v.fmt(f),
5958            Self::RefreshMaterializedView { name, with_data } => {
5959                write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
5960                if !*with_data {
5961                    f.write_str(" WITH NO DATA")?;
5962                }
5963                Ok(())
5964            }
5965            Self::DropMaterializedView { names, if_exists } => {
5966                f.write_str("DROP MATERIALIZED VIEW ")?;
5967                if *if_exists {
5968                    f.write_str("IF EXISTS ")?;
5969                }
5970                for (i, n) in names.iter().enumerate() {
5971                    if i > 0 {
5972                        f.write_str(", ")?;
5973                    }
5974                    write!(f, "{}", quote_ident(n))?;
5975                }
5976                Ok(())
5977            }
5978            Self::CreateType(t) => t.fmt(f),
5979            Self::CommentOn {
5980                kind,
5981                name,
5982                comment,
5983            } => {
5984                let body = match comment {
5985                    Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
5986                    None => "NULL".into(),
5987                };
5988                write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
5989            }
5990            Self::AlterTypeRenameValue {
5991                type_name,
5992                old,
5993                new,
5994            } => write!(
5995                f,
5996                "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
5997                quote_ident(type_name),
5998                old.replace('\'', "''"),
5999                new.replace('\'', "''")
6000            ),
6001            Self::AlterTypeAddValue {
6002                type_name,
6003                label,
6004                if_not_exists,
6005                position,
6006            } => {
6007                write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6008                if *if_not_exists {
6009                    write!(f, "IF NOT EXISTS ")?;
6010                }
6011                write!(f, "'{label}'")?;
6012                if let Some((is_before, anchor)) = position {
6013                    write!(
6014                        f,
6015                        " {} '{anchor}'",
6016                        if *is_before { "BEFORE" } else { "AFTER" }
6017                    )?;
6018                }
6019                Ok(())
6020            }
6021            Self::DropType { names, if_exists } => {
6022                f.write_str("DROP TYPE ")?;
6023                if *if_exists {
6024                    f.write_str("IF EXISTS ")?;
6025                }
6026                for (i, n) in names.iter().enumerate() {
6027                    if i > 0 {
6028                        f.write_str(", ")?;
6029                    }
6030                    write!(f, "{}", quote_ident(n))?;
6031                }
6032                Ok(())
6033            }
6034            Self::CreateDomain(d) => d.fmt(f),
6035            Self::DropDomain { names, if_exists } => {
6036                f.write_str("DROP DOMAIN ")?;
6037                if *if_exists {
6038                    f.write_str("IF EXISTS ")?;
6039                }
6040                for (i, n) in names.iter().enumerate() {
6041                    if i > 0 {
6042                        f.write_str(", ")?;
6043                    }
6044                    write!(f, "{}", quote_ident(n))?;
6045                }
6046                Ok(())
6047            }
6048            Self::CreateSchema {
6049                name,
6050                if_not_exists,
6051            } => {
6052                f.write_str("CREATE SCHEMA ")?;
6053                if *if_not_exists {
6054                    f.write_str("IF NOT EXISTS ")?;
6055                }
6056                write!(f, "{}", quote_ident(name))
6057            }
6058            Self::DropSchema { names, if_exists } => {
6059                f.write_str("DROP SCHEMA ")?;
6060                if *if_exists {
6061                    f.write_str("IF EXISTS ")?;
6062                }
6063                for (i, n) in names.iter().enumerate() {
6064                    if i > 0 {
6065                        f.write_str(", ")?;
6066                    }
6067                    write!(f, "{}", quote_ident(n))?;
6068                }
6069                Ok(())
6070            }
6071            Self::CreateRule(r) => {
6072                f.write_str("CREATE ")?;
6073                if r.or_replace {
6074                    f.write_str("OR REPLACE ")?;
6075                }
6076                write!(
6077                    f,
6078                    "RULE {} AS ON {} TO {}",
6079                    quote_ident(&r.name),
6080                    r.event,
6081                    quote_ident(&r.table)
6082                )?;
6083                if let Some(w) = &r.when_condition {
6084                    write!(f, " WHERE {w}")?;
6085                }
6086                f.write_str(if r.instead {
6087                    " DO INSTEAD "
6088                } else {
6089                    " DO ALSO "
6090                })?;
6091                if r.commands.is_empty() {
6092                    f.write_str("NOTHING")?;
6093                } else if r.commands.len() == 1 {
6094                    write!(f, "{}", r.commands[0])?;
6095                } else {
6096                    f.write_str("(")?;
6097                    for (i, c) in r.commands.iter().enumerate() {
6098                        if i > 0 {
6099                            f.write_str("; ")?;
6100                        }
6101                        write!(f, "{c}")?;
6102                    }
6103                    f.write_str(")")?;
6104                }
6105                Ok(())
6106            }
6107            Self::DropRule {
6108                name,
6109                table,
6110                if_exists,
6111            } => {
6112                f.write_str("DROP RULE ")?;
6113                if *if_exists {
6114                    f.write_str("IF EXISTS ")?;
6115                }
6116                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6117            }
6118        }
6119    }
6120}
6121
6122impl fmt::Display for CreateDomainStatement {
6123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6124        write!(
6125            f,
6126            "CREATE DOMAIN {} AS {}",
6127            quote_ident(&self.name),
6128            self.base_type
6129        )?;
6130        if let Some(d) = &self.default {
6131            write!(f, " DEFAULT {d}")?;
6132        }
6133        if self.not_null {
6134            f.write_str(" NOT NULL")?;
6135        }
6136        for c in &self.checks {
6137            write!(f, " CHECK ({c})")?;
6138        }
6139        Ok(())
6140    }
6141}
6142
6143impl fmt::Display for CreateTypeStatement {
6144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6145        write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6146        match &self.kind {
6147            TypeKind::Enum { labels } => {
6148                f.write_str("ENUM (")?;
6149                for (i, l) in labels.iter().enumerate() {
6150                    if i > 0 {
6151                        f.write_str(", ")?;
6152                    }
6153                    write!(f, "'{}'", l.replace('\'', "''"))?;
6154                }
6155                f.write_str(")")
6156            }
6157            TypeKind::Composite { fields, .. } => {
6158                f.write_str("(")?;
6159                for (i, (n, t)) in fields.iter().enumerate() {
6160                    if i > 0 {
6161                        f.write_str(", ")?;
6162                    }
6163                    write!(f, "{} {}", quote_ident(n), t)?;
6164                }
6165                f.write_str(")")
6166            }
6167        }
6168    }
6169}
6170
6171impl fmt::Display for CreateMaterializedViewStatement {
6172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6173        f.write_str("CREATE MATERIALIZED VIEW ")?;
6174        if self.if_not_exists {
6175            f.write_str("IF NOT EXISTS ")?;
6176        }
6177        write!(f, "{}", quote_ident(&self.name))?;
6178        if !self.columns.is_empty() {
6179            f.write_str(" (")?;
6180            for (i, c) in self.columns.iter().enumerate() {
6181                if i > 0 {
6182                    f.write_str(", ")?;
6183                }
6184                write!(f, "{}", quote_ident(c))?;
6185            }
6186            f.write_str(")")?;
6187        }
6188        write!(f, " AS {}", self.body)?;
6189        if !self.with_data {
6190            f.write_str(" WITH NO DATA")?;
6191        }
6192        Ok(())
6193    }
6194}
6195
6196impl fmt::Display for CreateViewStatement {
6197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6198        f.write_str("CREATE ")?;
6199        if self.or_replace {
6200            f.write_str("OR REPLACE ")?;
6201        }
6202        if self.temporary {
6203            f.write_str("TEMPORARY ")?;
6204        }
6205        f.write_str("VIEW ")?;
6206        if self.if_not_exists {
6207            f.write_str("IF NOT EXISTS ")?;
6208        }
6209        write!(f, "{}", quote_ident(&self.name))?;
6210        if !self.columns.is_empty() {
6211            f.write_str(" (")?;
6212            for (i, c) in self.columns.iter().enumerate() {
6213                if i > 0 {
6214                    f.write_str(", ")?;
6215                }
6216                write!(f, "{}", quote_ident(c))?;
6217            }
6218            f.write_str(")")?;
6219        }
6220        write!(f, " AS {}", self.body)?;
6221        match self.check_option {
6222            Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6223            Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6224            None => Ok(()),
6225        }
6226    }
6227}
6228
6229impl fmt::Display for CreateSequenceStatement {
6230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6231        f.write_str("CREATE ")?;
6232        if self.temporary {
6233            f.write_str("TEMPORARY ")?;
6234        }
6235        f.write_str("SEQUENCE ")?;
6236        if self.if_not_exists {
6237            f.write_str("IF NOT EXISTS ")?;
6238        }
6239        write!(f, "{}", quote_ident(&self.name))?;
6240        if let Some(dt) = self.data_type {
6241            write!(f, " AS {dt}")?;
6242        }
6243        write_sequence_options(f, &self.options)
6244    }
6245}
6246
6247impl fmt::Display for AlterSequenceStatement {
6248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6249        f.write_str("ALTER SEQUENCE ")?;
6250        if self.if_exists {
6251            f.write_str("IF EXISTS ")?;
6252        }
6253        write!(f, "{}", quote_ident(&self.name))?;
6254        write_sequence_options(f, &self.options)
6255    }
6256}
6257
6258impl fmt::Display for SequenceDataType {
6259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6260        f.write_str(match self {
6261            Self::SmallInt => "smallint",
6262            Self::Int => "integer",
6263            Self::BigInt => "bigint",
6264        })
6265    }
6266}
6267
6268fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6269    if let Some(n) = o.increment {
6270        write!(f, " INCREMENT BY {n}")?;
6271    }
6272    match o.min_value {
6273        Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6274        Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6275        None => {}
6276    }
6277    match o.max_value {
6278        Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6279        Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6280        None => {}
6281    }
6282    if let Some(n) = o.start {
6283        write!(f, " START WITH {n}")?;
6284    }
6285    match o.restart {
6286        Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6287        Some(None) => f.write_str(" RESTART")?,
6288        None => {}
6289    }
6290    if let Some(n) = o.cache {
6291        write!(f, " CACHE {n}")?;
6292    }
6293    match o.cycle {
6294        Some(true) => f.write_str(" CYCLE")?,
6295        Some(false) => f.write_str(" NO CYCLE")?,
6296        None => {}
6297    }
6298    if let Some(ob) = &o.owned_by {
6299        match ob {
6300            SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6301            SequenceOwnedBy::Column { table, column } => {
6302                write!(
6303                    f,
6304                    " OWNED BY {}.{}",
6305                    quote_ident(table),
6306                    quote_ident(column)
6307                )?;
6308            }
6309        }
6310    }
6311    Ok(())
6312}
6313
6314impl fmt::Display for CreateFunctionStatement {
6315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6316        f.write_str("CREATE ")?;
6317        if self.or_replace {
6318            f.write_str("OR REPLACE ")?;
6319        }
6320        write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6321        for (i, arg) in self.args.iter().enumerate() {
6322            if i > 0 {
6323                f.write_str(", ")?;
6324            }
6325            match arg.mode {
6326                FunctionArgMode::In => {}
6327                FunctionArgMode::Out => f.write_str("OUT ")?,
6328                FunctionArgMode::InOut => f.write_str("INOUT ")?,
6329            }
6330            if let Some(name) = &arg.name {
6331                write!(f, "{} ", quote_ident(name))?;
6332            }
6333            match &arg.ty {
6334                FunctionArgType::Typed(t) => write!(f, "{t}")?,
6335                FunctionArgType::Raw(s) => f.write_str(s)?,
6336            }
6337        }
6338        f.write_str(") RETURNS ")?;
6339        match &self.returns {
6340            FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6341            FunctionReturn::Void => f.write_str("VOID")?,
6342            FunctionReturn::Type(t) => write!(f, "{t}")?,
6343            FunctionReturn::Other(s) => f.write_str(s)?,
6344        }
6345        write!(f, " LANGUAGE {} AS $$", self.language)?;
6346        match &self.body {
6347            FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6348            FunctionBody::Raw(s) => f.write_str(s)?,
6349        }
6350        f.write_str("$$")
6351    }
6352}
6353
6354impl fmt::Display for PlPgSqlBlock {
6355    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6356        if !self.declarations.is_empty() {
6357            f.write_str("DECLARE\n")?;
6358            for d in &self.declarations {
6359                write!(f, "  {} ", quote_ident(&d.name))?;
6360                match &d.ty {
6361                    FunctionArgType::Typed(t) => write!(f, "{t}")?,
6362                    FunctionArgType::Raw(s) => f.write_str(s)?,
6363                }
6364                if let Some(e) = &d.default {
6365                    write!(f, " := {e}")?;
6366                }
6367                f.write_str(";\n")?;
6368            }
6369        }
6370        f.write_str("BEGIN\n")?;
6371        for stmt in &self.statements {
6372            writeln!(f, "  {stmt};")?;
6373        }
6374        // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6375        // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6376        // parsed block through it — so every exception handler a function
6377        // declared was thrown away AT STORE TIME. The block executed fine while
6378        // it was still an AST (a DO block never round-trips through text), which
6379        // is why only functions and triggers lost theirs.
6380        if !self.exception_handlers.is_empty() {
6381            f.write_str("EXCEPTION\n")?;
6382            for h in &self.exception_handlers {
6383                writeln!(f, "  WHEN {} THEN", h.conditions.join(" OR "))?;
6384                for stmt in &h.body {
6385                    writeln!(f, "    {stmt};")?;
6386                }
6387            }
6388        }
6389        f.write_str("END")
6390    }
6391}
6392
6393impl fmt::Display for PlPgSqlStmt {
6394    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6395        match self {
6396            Self::Assign { target, value } => write!(f, "{target} := {value}"),
6397            Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6398            Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6399            Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6400            Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6401            Self::Return(t) => match t {
6402                ReturnTarget::New => f.write_str("RETURN NEW"),
6403                ReturnTarget::Old => f.write_str("RETURN OLD"),
6404                ReturnTarget::Null => f.write_str("RETURN NULL"),
6405                ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6406            },
6407            Self::If {
6408                branches,
6409                else_branch,
6410            } => {
6411                for (i, (cond, body)) in branches.iter().enumerate() {
6412                    if i == 0 {
6413                        write!(f, "IF {cond} THEN ")?;
6414                    } else {
6415                        write!(f, " ELSIF {cond} THEN ")?;
6416                    }
6417                    for (j, s) in body.iter().enumerate() {
6418                        if j > 0 {
6419                            f.write_str("; ")?;
6420                        }
6421                        write!(f, "{s}")?;
6422                    }
6423                }
6424                if !else_branch.is_empty() {
6425                    f.write_str(" ELSE ")?;
6426                    for (j, s) in else_branch.iter().enumerate() {
6427                        if j > 0 {
6428                            f.write_str("; ")?;
6429                        }
6430                        write!(f, "{s}")?;
6431                    }
6432                }
6433                f.write_str(" END IF")
6434            }
6435            Self::Raise {
6436                level,
6437                message,
6438                args,
6439            } => {
6440                let lvl = match level {
6441                    RaiseLevel::Notice => "NOTICE",
6442                    RaiseLevel::Warning => "WARNING",
6443                    RaiseLevel::Info => "INFO",
6444                    RaiseLevel::Log => "LOG",
6445                    RaiseLevel::Debug => "DEBUG",
6446                    RaiseLevel::Exception => "EXCEPTION",
6447                };
6448                write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6449                for a in args {
6450                    write!(f, ", {a}")?;
6451                }
6452                Ok(())
6453            }
6454            Self::EmbeddedSql(s) => write!(f, "{s}"),
6455            Self::Assert { condition, message } => {
6456                write!(f, "ASSERT {condition}")?;
6457                if let Some(m) = message {
6458                    write!(f, ", {m}")?;
6459                }
6460                Ok(())
6461            }
6462            Self::While { condition, body } => {
6463                writeln!(f, "WHILE {condition} LOOP")?;
6464                for s in body {
6465                    writeln!(f, "  {s};")?;
6466                }
6467                f.write_str("END LOOP")
6468            }
6469            Self::ForRange {
6470                var,
6471                start,
6472                end,
6473                reverse,
6474                body,
6475            } => {
6476                write!(f, "FOR {var} IN ")?;
6477                if *reverse {
6478                    f.write_str("REVERSE ")?;
6479                }
6480                writeln!(f, "{start}..{end} LOOP")?;
6481                for s in body {
6482                    writeln!(f, "  {s};")?;
6483                }
6484                f.write_str("END LOOP")
6485            }
6486            Self::Loop { body } => {
6487                writeln!(f, "LOOP")?;
6488                for s in body {
6489                    writeln!(f, "  {s};")?;
6490                }
6491                f.write_str("END LOOP")
6492            }
6493            Self::Exit { when } => {
6494                f.write_str("EXIT")?;
6495                if let Some(c) = when {
6496                    write!(f, " WHEN {c}")?;
6497                }
6498                Ok(())
6499            }
6500            Self::Continue { when } => {
6501                f.write_str("CONTINUE")?;
6502                if let Some(c) = when {
6503                    write!(f, " WHEN {c}")?;
6504                }
6505                Ok(())
6506            }
6507            Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
6508            Self::ForQuery { var, query, body } => {
6509                writeln!(f, "FOR {var} IN ({query}) LOOP")?;
6510                for s in body {
6511                    writeln!(f, "  {s};")?;
6512                }
6513                f.write_str("END LOOP")
6514            }
6515            Self::ForExecute {
6516                var,
6517                sql_expr,
6518                body,
6519            } => {
6520                writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
6521                for s in body {
6522                    writeln!(f, "  {s};")?;
6523                }
6524                f.write_str("END LOOP")
6525            }
6526        }
6527    }
6528}
6529
6530impl fmt::Display for AssignTarget {
6531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6532        match self {
6533            Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
6534            Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
6535            Self::Local(n) => f.write_str(n),
6536        }
6537    }
6538}
6539
6540impl fmt::Display for CreateTriggerStatement {
6541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6542        f.write_str("CREATE ")?;
6543        if self.or_replace {
6544            f.write_str("OR REPLACE ")?;
6545        }
6546        write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
6547        match self.timing {
6548            TriggerTiming::Before => f.write_str("BEFORE")?,
6549            TriggerTiming::After => f.write_str("AFTER")?,
6550            TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
6551        }
6552        for (i, e) in self.events.iter().enumerate() {
6553            if i == 0 {
6554                f.write_str(" ")?;
6555            } else {
6556                f.write_str(" OR ")?;
6557            }
6558            match e {
6559                TriggerEvent::Insert => f.write_str("INSERT")?,
6560                TriggerEvent::Update => {
6561                    f.write_str("UPDATE")?;
6562                    if !self.update_columns.is_empty() {
6563                        f.write_str(" OF ")?;
6564                        for (j, col) in self.update_columns.iter().enumerate() {
6565                            if j > 0 {
6566                                f.write_str(", ")?;
6567                            }
6568                            f.write_str(&quote_ident(col))?;
6569                        }
6570                    }
6571                }
6572                TriggerEvent::Delete => f.write_str("DELETE")?,
6573                TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
6574            }
6575        }
6576        write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
6577        match self.for_each {
6578            TriggerForEach::Row => f.write_str("ROW")?,
6579            TriggerForEach::Statement => f.write_str("STATEMENT")?,
6580        }
6581        write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
6582    }
6583}
6584
6585impl fmt::Display for CreateIndexStatement {
6586    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6587        if self.is_unique {
6588            f.write_str("CREATE UNIQUE INDEX ")?;
6589        } else {
6590            f.write_str("CREATE INDEX ")?;
6591        }
6592        if self.if_not_exists {
6593            f.write_str("IF NOT EXISTS ")?;
6594        }
6595        write!(
6596            f,
6597            "{} ON {} ",
6598            quote_ident(&self.name),
6599            quote_ident(&self.table)
6600        )?;
6601        match self.method {
6602            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
6603            IndexMethod::Brin => f.write_str("USING brin ")?,
6604            IndexMethod::Gin => f.write_str("USING gin ")?,
6605            IndexMethod::BTree => {}
6606        }
6607        if let Some(expr) = &self.expression {
6608            write!(f, "({})", expr)?;
6609        } else if self.extra_columns.is_empty() {
6610            // v7.15.0 — preserve operator class on round-trip
6611            // (`(col opclass)`) so WAL replay reconstructs the
6612            // engine-routing intent (e.g. `gin_trgm_ops` →
6613            // trigram-GIN build path).
6614            if let Some(op) = &self.opclass {
6615                write!(f, "({} {})", quote_ident(&self.column), op)?;
6616            } else {
6617                write!(f, "({})", quote_ident(&self.column))?;
6618            }
6619        } else {
6620            // v7.9.14 — multi-column key. Emit each column quoted
6621            // so the round-tripped form re-parses to identical AST.
6622            f.write_str("(")?;
6623            write!(f, "{}", quote_ident(&self.column))?;
6624            for c in &self.extra_columns {
6625                write!(f, ", {}", quote_ident(c))?;
6626            }
6627            f.write_str(")")?;
6628        }
6629        if !self.included_columns.is_empty() {
6630            f.write_str(" INCLUDE (")?;
6631            for (i, c) in self.included_columns.iter().enumerate() {
6632                if i > 0 {
6633                    f.write_str(", ")?;
6634                }
6635                write!(f, "{}", quote_ident(c))?;
6636            }
6637            f.write_str(")")?;
6638        }
6639        if let Some(pred) = &self.partial_predicate {
6640            write!(f, " WHERE {}", pred)?;
6641        }
6642        Ok(())
6643    }
6644}
6645
6646impl fmt::Display for CreateTableStatement {
6647    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6648        f.write_str("CREATE TABLE ")?;
6649        if self.if_not_exists {
6650            f.write_str("IF NOT EXISTS ")?;
6651        }
6652        write!(f, "{}", quote_ident(&self.name))?;
6653        // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
6654        // no column list and no constraints; the table inherits its
6655        // columns from the parent at engine-DDL time.
6656        if let Some(spec) = &self.partition_of {
6657            write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
6658            return match &spec.bounds {
6659                PartitionOfBoundsAst::Range { lower, upper } => {
6660                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
6661                }
6662                PartitionOfBoundsAst::List { values } => {
6663                    f.write_str("FOR VALUES IN (")?;
6664                    for (i, v) in values.iter().enumerate() {
6665                        if i > 0 {
6666                            f.write_str(", ")?;
6667                        }
6668                        write!(f, "{}", v)?;
6669                    }
6670                    f.write_str(")")
6671                }
6672                PartitionOfBoundsAst::Hash { modulus, remainder } => {
6673                    write!(
6674                        f,
6675                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
6676                        modulus, remainder
6677                    )
6678                }
6679                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
6680            };
6681        }
6682        f.write_str(" (")?;
6683        for (i, col) in self.columns.iter().enumerate() {
6684            if i > 0 {
6685                f.write_str(", ")?;
6686            }
6687            write!(f, "{col}")?;
6688        }
6689        // v7.6.0 — render FK constraints in table-level form, after
6690        // the column list. WAL replay round-trips through Display, so
6691        // every FK must serialise here for replay to reconstruct the
6692        // schema bit-for-bit.
6693        for fk in &self.foreign_keys {
6694            f.write_str(", ")?;
6695            write!(f, "{fk}")?;
6696        }
6697        // v7.13.0 — render table-level constraints (PRIMARY KEY /
6698        // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
6699        // column-level UNIQUE / CHECK get lifted to this list at
6700        // parse time, so emitting only here avoids double-counting.
6701        for tc in &self.table_constraints {
6702            f.write_str(", ")?;
6703            write!(f, "{tc}")?;
6704        }
6705        f.write_str(")")?;
6706        // v7.37.6-B — partition-parent suffix renders after the
6707        // closing column-list paren, before the optional MySQL
6708        // table-options tail (which Display doesn't currently emit).
6709        if let Some(spec) = &self.partition_by {
6710            f.write_str(" PARTITION BY ")?;
6711            match spec.kind {
6712                PartitionKindAst::Range => f.write_str("RANGE ")?,
6713                PartitionKindAst::List => f.write_str("LIST ")?,
6714                PartitionKindAst::Hash => f.write_str("HASH ")?,
6715            }
6716            f.write_str("(")?;
6717            for (i, col) in spec.key_columns.iter().enumerate() {
6718                if i > 0 {
6719                    f.write_str(", ")?;
6720                }
6721                f.write_str(&quote_ident(col))?;
6722            }
6723            f.write_str(")")?;
6724        }
6725        Ok(())
6726    }
6727}
6728
6729fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
6730    match t {
6731        AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
6732        AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
6733            write!(f, "REPLICA IDENTITY USING INDEX {index}")
6734        }
6735        AlterTableTarget::Inherit { parent, detach } => {
6736            if *detach {
6737                write!(f, "NO INHERIT {parent}")
6738            } else {
6739                write!(f, "INHERIT {parent}")
6740            }
6741        }
6742        AlterTableTarget::SetHotTierBytes(n) => {
6743            write!(f, "SET hot_tier_bytes = {n}")
6744        }
6745        AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
6746        AlterTableTarget::DropForeignKey { name, if_exists } => {
6747            f.write_str("DROP CONSTRAINT ")?;
6748            if *if_exists {
6749                f.write_str("IF EXISTS ")?;
6750            }
6751            write!(f, "{}", quote_ident(name))
6752        }
6753        AlterTableTarget::DropIndex { name, if_exists } => {
6754            f.write_str("DROP INDEX ")?;
6755            if *if_exists {
6756                f.write_str("IF EXISTS ")?;
6757            }
6758            write!(f, "{}", quote_ident(name))
6759        }
6760        AlterTableTarget::AddColumn {
6761            column,
6762            if_not_exists,
6763        } => {
6764            f.write_str("ADD COLUMN ")?;
6765            if *if_not_exists {
6766                f.write_str("IF NOT EXISTS ")?;
6767            }
6768            write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
6769            if !column.nullable {
6770                f.write_str(" NOT NULL")?;
6771            }
6772            if let Some(d) = &column.default {
6773                write!(f, " DEFAULT {d}")?;
6774            }
6775            if column.auto_increment {
6776                f.write_str(" AUTO_INCREMENT")?;
6777            }
6778            if column.is_primary_key {
6779                f.write_str(" PRIMARY KEY")?;
6780            }
6781            Ok(())
6782        }
6783        AlterTableTarget::AlterColumnType {
6784            column,
6785            new_type,
6786            using,
6787            collation,
6788        } => {
6789            write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
6790            if let Some((_, name)) = collation {
6791                write!(f, " COLLATE {}", quote_ident(name))?;
6792            }
6793            if let Some(u) = using {
6794                write!(f, " USING {u}")?;
6795            }
6796            Ok(())
6797        }
6798        AlterTableTarget::DropColumn {
6799            column,
6800            if_exists,
6801            cascade,
6802        } => {
6803            f.write_str("DROP COLUMN ")?;
6804            if *if_exists {
6805                f.write_str("IF EXISTS ")?;
6806            }
6807            write!(f, "{}", quote_ident(column))?;
6808            if *cascade {
6809                f.write_str(" CASCADE")?;
6810            }
6811            Ok(())
6812        }
6813        AlterTableTarget::AddTableConstraint(tc) => {
6814            write!(f, "ADD {tc}")
6815        }
6816        AlterTableTarget::ValidateConstraint { name } => {
6817            write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
6818        }
6819        AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
6820        AlterTableTarget::ClusterOn { index } => match index {
6821            Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
6822            None => f.write_str("SET WITHOUT CLUSTER"),
6823        },
6824        AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
6825            // Round-trip-safe spelling: re-parsing this form lowers
6826            // back to SetColumnAutoIncrement (the nextval default is
6827            // how pg_dump says "serial").
6828            let seq = seq_name
6829                .clone()
6830                .unwrap_or_else(|| alloc::format!("{column}_seq"));
6831            write!(
6832                f,
6833                "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
6834                quote_ident(column)
6835            )
6836        }
6837        AlterTableTarget::RenameColumn { old, new } => {
6838            write!(
6839                f,
6840                "RENAME COLUMN {} TO {}",
6841                quote_ident(old),
6842                quote_ident(new)
6843            )
6844        }
6845        AlterTableTarget::RenameConstraint { old, new } => {
6846            write!(
6847                f,
6848                "RENAME CONSTRAINT {} TO {}",
6849                quote_ident(old),
6850                quote_ident(new)
6851            )
6852        }
6853        AlterTableTarget::RenameTable { new } => {
6854            write!(f, "RENAME TO {}", quote_ident(new))
6855        }
6856        AlterTableTarget::SetTriggerEnabled { which, enabled } => {
6857            f.write_str(if *enabled {
6858                "ENABLE TRIGGER "
6859            } else {
6860                "DISABLE TRIGGER "
6861            })?;
6862            match which {
6863                TriggerSelector::All => f.write_str("ALL"),
6864                TriggerSelector::Named(n) => f.write_str(&quote_ident(n)),
6865            }
6866        }
6867        AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
6868            (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
6869            (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
6870            (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
6871            (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
6872            (None, None) => Ok(()),
6873        },
6874        AlterTableTarget::AttachPartition { child, bounds } => {
6875            write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
6876            match bounds {
6877                PartitionOfBoundsAst::Range { lower, upper } => {
6878                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
6879                }
6880                PartitionOfBoundsAst::List { values } => {
6881                    f.write_str("FOR VALUES IN (")?;
6882                    for (i, v) in values.iter().enumerate() {
6883                        if i > 0 {
6884                            f.write_str(", ")?;
6885                        }
6886                        write!(f, "{}", v)?;
6887                    }
6888                    f.write_str(")")
6889                }
6890                PartitionOfBoundsAst::Hash { modulus, remainder } => {
6891                    write!(
6892                        f,
6893                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
6894                        modulus, remainder
6895                    )
6896                }
6897                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
6898            }
6899        }
6900        AlterTableTarget::DetachPartition {
6901            child,
6902            concurrently,
6903            finalize,
6904        } => {
6905            write!(f, "DETACH PARTITION {}", quote_ident(child))?;
6906            if *concurrently {
6907                f.write_str(" CONCURRENTLY")?;
6908            }
6909            if *finalize {
6910                f.write_str(" FINALIZE")?;
6911            }
6912            Ok(())
6913        }
6914        AlterTableTarget::AlterColumnSetDefault {
6915            column,
6916            default_expr,
6917        } => write!(
6918            f,
6919            "ALTER COLUMN {} SET DEFAULT {}",
6920            quote_ident(column),
6921            default_expr
6922        ),
6923        AlterTableTarget::AlterColumnDropDefault { column } => {
6924            write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
6925        }
6926        AlterTableTarget::AlterColumnSetNotNull { column } => {
6927            write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
6928        }
6929        AlterTableTarget::AlterColumnDropNotNull { column } => {
6930            write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
6931        }
6932        AlterTableTarget::AlterColumnRestart { column, with } => {
6933            write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
6934            if let Some(n) = with {
6935                write!(f, " WITH {n}")?;
6936            }
6937            Ok(())
6938        }
6939        AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
6940            write!(
6941                f,
6942                "ALTER COLUMN {} DROP EXPRESSION{}",
6943                quote_ident(column),
6944                if *if_exists { " IF EXISTS" } else { "" }
6945            )
6946        }
6947        AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
6948            write!(
6949                f,
6950                "ALTER COLUMN {} DROP IDENTITY{}",
6951                quote_ident(column),
6952                if *if_exists { " IF EXISTS" } else { "" }
6953            )
6954        }
6955        AlterTableTarget::AlterColumnSetExpression { column, expr } => {
6956            write!(
6957                f,
6958                "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
6959                quote_ident(column)
6960            )
6961        }
6962    }
6963}
6964
6965impl fmt::Display for TableConstraint {
6966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6967        match self {
6968            Self::PrimaryKey { name, columns, .. } => {
6969                if let Some(n) = name {
6970                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
6971                }
6972                f.write_str("PRIMARY KEY (")?;
6973                for (i, c) in columns.iter().enumerate() {
6974                    if i > 0 {
6975                        f.write_str(", ")?;
6976                    }
6977                    f.write_str(&quote_ident(c))?;
6978                }
6979                f.write_str(")")
6980            }
6981            Self::Unique {
6982                name,
6983                columns,
6984                nulls_not_distinct,
6985                ..
6986            } => {
6987                if let Some(n) = name {
6988                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
6989                }
6990                f.write_str("UNIQUE ")?;
6991                if *nulls_not_distinct {
6992                    f.write_str("NULLS NOT DISTINCT ")?;
6993                }
6994                f.write_str("(")?;
6995                for (i, c) in columns.iter().enumerate() {
6996                    if i > 0 {
6997                        f.write_str(", ")?;
6998                    }
6999                    f.write_str(&quote_ident(c))?;
7000                }
7001                f.write_str(")")
7002            }
7003            Self::Check {
7004                name,
7005                expr,
7006                not_valid,
7007            } => {
7008                if let Some(n) = name {
7009                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7010                }
7011                write!(f, "CHECK ({expr})")?;
7012                if *not_valid {
7013                    write!(f, " NOT VALID")?;
7014                }
7015                Ok(())
7016            }
7017            Self::Index { name, columns } => {
7018                f.write_str("KEY ")?;
7019                if let Some(n) = name {
7020                    write!(f, "{} ", quote_ident(n))?;
7021                }
7022                f.write_str("(")?;
7023                for (i, c) in columns.iter().enumerate() {
7024                    if i > 0 {
7025                        f.write_str(", ")?;
7026                    }
7027                    f.write_str(&quote_ident(c))?;
7028                }
7029                f.write_str(")")
7030            }
7031            Self::FulltextIndex { name, columns } => {
7032                // Mysqldump emits `FULLTEXT KEY name (cols)` —
7033                // Display rounds back to that shape so dump
7034                // replay reproduces the input verbatim.
7035                f.write_str("FULLTEXT KEY ")?;
7036                if let Some(n) = name {
7037                    write!(f, "{} ", quote_ident(n))?;
7038                }
7039                f.write_str("(")?;
7040                for (i, c) in columns.iter().enumerate() {
7041                    if i > 0 {
7042                        f.write_str(", ")?;
7043                    }
7044                    f.write_str(&quote_ident(c))?;
7045                }
7046                f.write_str(")")
7047            }
7048            Self::Exclude {
7049                name,
7050                method,
7051                elements,
7052            } => {
7053                if let Some(n) = name {
7054                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7055                }
7056                f.write_str("EXCLUDE ")?;
7057                if let Some(m) = method {
7058                    write!(f, "USING {m} ")?;
7059                }
7060                f.write_str("(")?;
7061                for (i, (col, op)) in elements.iter().enumerate() {
7062                    if i > 0 {
7063                        f.write_str(", ")?;
7064                    }
7065                    write!(f, "{} WITH {op}", quote_ident(col))?;
7066                }
7067                f.write_str(")")
7068            }
7069        }
7070    }
7071}
7072
7073impl fmt::Display for ForeignKeyConstraint {
7074    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7075        if let Some(name) = &self.name {
7076            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7077        }
7078        f.write_str("FOREIGN KEY (")?;
7079        for (i, c) in self.columns.iter().enumerate() {
7080            if i > 0 {
7081                f.write_str(", ")?;
7082            }
7083            f.write_str(&quote_ident(c))?;
7084        }
7085        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7086        if !self.parent_columns.is_empty() {
7087            f.write_str(" (")?;
7088            for (i, c) in self.parent_columns.iter().enumerate() {
7089                if i > 0 {
7090                    f.write_str(", ")?;
7091                }
7092                f.write_str(&quote_ident(c))?;
7093            }
7094            f.write_str(")")?;
7095        }
7096        // Only render non-default actions to keep Display output
7097        // close to user input. SPG's default is RESTRICT (matches
7098        // SQL spec).
7099        if self.on_delete != FkAction::Restrict {
7100            write!(f, " ON DELETE {}", self.on_delete)?;
7101        }
7102        if self.on_update != FkAction::Restrict {
7103            write!(f, " ON UPDATE {}", self.on_update)?;
7104        }
7105        Ok(())
7106    }
7107}
7108
7109impl fmt::Display for FkAction {
7110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7111        match self {
7112            Self::Restrict => f.write_str("RESTRICT"),
7113            Self::Cascade => f.write_str("CASCADE"),
7114            Self::SetNull => f.write_str("SET NULL"),
7115            Self::SetDefault => f.write_str("SET DEFAULT"),
7116            Self::NoAction => f.write_str("NO ACTION"),
7117        }
7118    }
7119}
7120
7121impl fmt::Display for ColumnDef {
7122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7123        // v7.30.1 (mailrs round-24 class audit) — the type position
7124        // must re-parse to the same ColumnDef: a user-defined type
7125        // reference and the MySQL inline ENUM / SET value lists all
7126        // lower `ty` to Text, so rendering `ty` lost them.
7127        write!(f, "{}", quote_ident(&self.name))?;
7128        if let Some(ut) = &self.user_type_ref {
7129            write!(f, " {}", quote_ident(ut))?;
7130        } else if let Some(variants) = &self.inline_enum_variants {
7131            write_variant_list(f, "ENUM", variants)?;
7132        } else if let Some(variants) = &self.inline_set_variants {
7133            write_variant_list(f, "SET", variants)?;
7134        } else {
7135            write!(f, " {}", self.ty)?;
7136        }
7137        if self.is_unsigned {
7138            f.write_str(" UNSIGNED")?;
7139        }
7140        // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7141        // DDL. Only emits when non-default so the typical output
7142        // stays unchanged.
7143        match self.collation {
7144            Collation::Binary => {}
7145            Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7146        }
7147        if let Some(d) = &self.default {
7148            write!(f, " DEFAULT {d}")?;
7149        }
7150        if self.auto_increment {
7151            f.write_str(" AUTO_INCREMENT")?;
7152        }
7153        if !self.nullable {
7154            f.write_str(" NOT NULL")?;
7155        }
7156        // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7157        // is NOT lifted to a table-level constraint at parse time
7158        // (unlike UNIQUE / CHECK), so the WAL round trip of a
7159        // prepared CREATE TABLE silently dropped the primary key.
7160        if self.is_primary_key {
7161            f.write_str(" PRIMARY KEY")?;
7162        }
7163        // The parser accepts only CURRENT_TIMESTAMP here (stored as
7164        // now()), so that spelling is the lossless round trip.
7165        if self.on_update_runtime.is_some() {
7166            f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7167        }
7168        // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7169        // replay reconstructs the computed-column declaration. The
7170        // expression sits inside a single set of parens; STORED is
7171        // the only variant the parser accepts.
7172        if let Some(gen_expr) = &self.generated_stored_expr {
7173            write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7174        }
7175        Ok(())
7176    }
7177}
7178
7179/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7180/// types (MySQL flavour; `ty` is Text underneath).
7181fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7182    write!(f, " {kw}(")?;
7183    for (i, v) in variants.iter().enumerate() {
7184        if i > 0 {
7185            f.write_str(", ")?;
7186        }
7187        write!(f, "'{}'", v.replace('\'', "''"))?;
7188    }
7189    f.write_str(")")
7190}
7191
7192impl fmt::Display for InsertStatement {
7193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7194        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7195        if let Some(cols) = &self.columns {
7196            f.write_str(" (")?;
7197            for (i, c) in cols.iter().enumerate() {
7198                if i > 0 {
7199                    f.write_str(", ")?;
7200                }
7201                f.write_str(&quote_ident(c))?;
7202            }
7203            f.write_str(")")?;
7204        }
7205        // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7206        // skipping the VALUES list (mailrs round-5 G4).
7207        if let Some(sel) = &self.select_source {
7208            write!(f, " {sel}")?;
7209        } else {
7210            f.write_str(" VALUES ")?;
7211            for (ri, row) in self.rows.iter().enumerate() {
7212                if ri > 0 {
7213                    f.write_str(", ")?;
7214                }
7215                f.write_str("(")?;
7216                for (i, v) in row.iter().enumerate() {
7217                    if i > 0 {
7218                        f.write_str(", ")?;
7219                    }
7220                    write!(f, "{v}")?;
7221                }
7222                f.write_str(")")?;
7223            }
7224        }
7225        // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7226        // Display round trip: WAL persistence renders the bind-final
7227        // AST through this impl, and a replayed bare INSERT turns a
7228        // legal upsert no-op into a UNIQUE violation that refuses to
7229        // open the catalog.
7230        if let Some(oc) = &self.on_conflict {
7231            write!(f, " {oc}")?;
7232        }
7233        write_returning(self.returning.as_deref(), f)?;
7234        Ok(())
7235    }
7236}
7237
7238/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7239/// parser produced, so the AST→SQL round trip preserves upsert
7240/// semantics (WAL replay depends on it).
7241impl fmt::Display for OnConflictClause {
7242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7243        f.write_str("ON CONFLICT")?;
7244        if let Some(name) = &self.constraint_name {
7245            write!(f, " ON CONSTRAINT {name}")?;
7246        }
7247        if !self.target_columns.is_empty() {
7248            f.write_str(" (")?;
7249            for (i, c) in self.target_columns.iter().enumerate() {
7250                if i > 0 {
7251                    f.write_str(", ")?;
7252                }
7253                f.write_str(&quote_ident(c))?;
7254            }
7255            f.write_str(")")?;
7256        }
7257        if let Some(w) = &self.index_where {
7258            write!(f, " WHERE {w}")?;
7259        }
7260        match &self.action {
7261            OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7262            OnConflictAction::Update {
7263                assignments,
7264                where_,
7265            } => {
7266                f.write_str(" DO UPDATE SET ")?;
7267                for (i, (col, expr)) in assignments.iter().enumerate() {
7268                    if i > 0 {
7269                        f.write_str(", ")?;
7270                    }
7271                    write!(f, "{} = {expr}", quote_ident(col))?;
7272                }
7273                if let Some(w) = where_ {
7274                    write!(f, " WHERE {w}")?;
7275                }
7276                Ok(())
7277            }
7278        }
7279    }
7280}
7281
7282/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7283/// tail for the three DML Display impls.
7284fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7285    let Some(items) = ret else {
7286        return Ok(());
7287    };
7288    f.write_str(" RETURNING ")?;
7289    for (i, item) in items.iter().enumerate() {
7290        if i > 0 {
7291            f.write_str(", ")?;
7292        }
7293        write!(f, "{item}")?;
7294    }
7295    Ok(())
7296}
7297
7298impl fmt::Display for UpdateStatement {
7299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7300        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7301        for (i, (col, expr)) in self.assignments.iter().enumerate() {
7302            if i > 0 {
7303                f.write_str(", ")?;
7304            }
7305            write!(f, "{} = {expr}", quote_ident(col))?;
7306        }
7307        if let Some(w) = &self.where_ {
7308            write!(f, " WHERE {w}")?;
7309        }
7310        // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7311        if let Some(ol) = self.order_limit.as_deref() {
7312            if !ol.order_by.is_empty() {
7313                f.write_str(" ORDER BY ")?;
7314                for (i, o) in ol.order_by.iter().enumerate() {
7315                    if i > 0 {
7316                        f.write_str(", ")?;
7317                    }
7318                    write!(f, "{}", o.expr)?;
7319                    if o.desc {
7320                        f.write_str(" DESC")?;
7321                    }
7322                    match o.nulls_first {
7323                        Some(true) => f.write_str(" NULLS FIRST")?,
7324                        Some(false) => f.write_str(" NULLS LAST")?,
7325                        None => {}
7326                    }
7327                }
7328            }
7329            if let Some(n) = ol.limit {
7330                write!(f, " LIMIT {n}")?;
7331            }
7332        }
7333        write_returning(self.returning.as_deref(), f)?;
7334        Ok(())
7335    }
7336}
7337
7338impl fmt::Display for DeleteStatement {
7339    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7340        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7341        if let Some(w) = &self.where_ {
7342            write!(f, " WHERE {w}")?;
7343        }
7344        write_returning(self.returning.as_deref(), f)?;
7345        Ok(())
7346    }
7347}
7348
7349impl fmt::Display for CteBody {
7350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7351        match self {
7352            Self::Select(s) => write!(f, "{s}"),
7353            Self::Insert(s) => write!(f, "{s}"),
7354            Self::Update(s) => write!(f, "{s}"),
7355            Self::Delete(s) => write!(f, "{s}"),
7356            Self::Merge(s) => write!(f, "{s}"),
7357        }
7358    }
7359}
7360
7361impl fmt::Display for MergeStatement {
7362    // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7363    // (it round-trips for the cases tests cover, not for
7364    // round-tripping every edge of the surface).
7365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7366        fmt_with_clause(&self.ctes, f)?;
7367        f.write_str("MERGE INTO ")?;
7368        write!(f, "{}", quote_ident(&self.target))?;
7369        if let Some(a) = &self.target_alias {
7370            write!(f, " {}", quote_ident(a))?;
7371        }
7372        f.write_str(" USING ")?;
7373        if let Some(sub) = &self.source_select {
7374            write!(f, "({sub})")?;
7375        } else {
7376            write!(f, "{}", quote_ident(&self.source))?;
7377        }
7378        if let Some(a) = &self.source_alias {
7379            write!(f, " {}", quote_ident(a))?;
7380        }
7381        if !self.source_column_aliases.is_empty() {
7382            f.write_str("(")?;
7383            for (i, c) in self.source_column_aliases.iter().enumerate() {
7384                if i > 0 {
7385                    f.write_str(", ")?;
7386                }
7387                write!(f, "{}", quote_ident(c))?;
7388            }
7389            f.write_str(")")?;
7390        }
7391        write!(f, " ON {}", self.on)?;
7392        for clause in &self.clauses {
7393            f.write_str(" WHEN ")?;
7394            f.write_str(match clause.matched {
7395                MergeMatched::Matched => "MATCHED",
7396                MergeMatched::NotMatched => "NOT MATCHED",
7397                MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7398            })?;
7399            if let Some(c) = &clause.condition {
7400                write!(f, " AND {c}")?;
7401            }
7402            f.write_str(" THEN ")?;
7403            match &clause.action {
7404                MergeAction::Insert { columns, values } => {
7405                    f.write_str("INSERT ")?;
7406                    // A column list is optional (round 146): the bare
7407                    // `INSERT VALUES (…)` form maps positionally.
7408                    if !columns.is_empty() {
7409                        f.write_str("(")?;
7410                        for (i, c) in columns.iter().enumerate() {
7411                            if i > 0 {
7412                                f.write_str(", ")?;
7413                            }
7414                            write!(f, "{}", quote_ident(c))?;
7415                        }
7416                        f.write_str(") ")?;
7417                    }
7418                    f.write_str("VALUES (")?;
7419                    for (i, v) in values.iter().enumerate() {
7420                        if i > 0 {
7421                            f.write_str(", ")?;
7422                        }
7423                        write!(f, "{v}")?;
7424                    }
7425                    f.write_str(")")?;
7426                }
7427                MergeAction::Update { assignments } => {
7428                    f.write_str("UPDATE SET ")?;
7429                    for (i, (c, e)) in assignments.iter().enumerate() {
7430                        if i > 0 {
7431                            f.write_str(", ")?;
7432                        }
7433                        write!(f, "{} = {e}", quote_ident(c))?;
7434                    }
7435                }
7436                MergeAction::Delete => f.write_str("DELETE")?,
7437                MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7438            }
7439        }
7440        if let Some(items) = &self.returning {
7441            f.write_str(" RETURNING ")?;
7442            for (i, it) in items.iter().enumerate() {
7443                if i > 0 {
7444                    f.write_str(", ")?;
7445                }
7446                write!(f, "{it}")?;
7447            }
7448        }
7449        Ok(())
7450    }
7451}
7452
7453/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
7454/// carry a CTE list and must round-trip it identically.
7455fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
7456    if ctes.is_empty() {
7457        return Ok(());
7458    }
7459    f.write_str("WITH ")?;
7460    if ctes.iter().any(|c| c.recursive) {
7461        f.write_str("RECURSIVE ")?;
7462    }
7463    for (i, cte) in ctes.iter().enumerate() {
7464        if i > 0 {
7465            f.write_str(", ")?;
7466        }
7467        f.write_str(&quote_ident(&cte.name))?;
7468        if !cte.column_overrides.is_empty() {
7469            f.write_str(" (")?;
7470            for (ci, c) in cte.column_overrides.iter().enumerate() {
7471                if ci > 0 {
7472                    f.write_str(", ")?;
7473                }
7474                f.write_str(&quote_ident(c))?;
7475            }
7476            f.write_str(")")?;
7477        }
7478        write!(f, " AS ({})", cte.body)?;
7479    }
7480    f.write_str(" ")
7481}
7482
7483impl fmt::Display for SelectStatement {
7484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7485        // v7.30.1 (mailrs round-24 class audit) — the WITH clause
7486        // must survive the round trip; a CTE-using statement
7487        // re-parsed without it references undefined tables.
7488        fmt_with_clause(&self.ctes, f)?;
7489        write_bare_select(self, f)?;
7490        for (kind, peer) in &self.unions {
7491            f.write_str(match kind {
7492                UnionKind::Distinct => " UNION ",
7493                UnionKind::All => " UNION ALL ",
7494                UnionKind::Intersect => " INTERSECT ",
7495                UnionKind::IntersectAll => " INTERSECT ALL ",
7496                UnionKind::Except => " EXCEPT ",
7497                UnionKind::ExceptAll => " EXCEPT ALL ",
7498            })?;
7499            write_bare_select(peer, f)?;
7500        }
7501        if !self.order_by.is_empty() {
7502            f.write_str(" ORDER BY ")?;
7503            for (i, o) in self.order_by.iter().enumerate() {
7504                if i > 0 {
7505                    f.write_str(", ")?;
7506                }
7507                write!(f, "{}", o.expr)?;
7508                if o.desc {
7509                    f.write_str(" DESC")?;
7510                }
7511                match o.nulls_first {
7512                    Some(true) => f.write_str(" NULLS FIRST")?,
7513                    Some(false) => f.write_str(" NULLS LAST")?,
7514                    None => {}
7515                }
7516            }
7517        }
7518        // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
7519        // exists in the FETCH FIRST spelling; rendering it as LIMIT
7520        // dropped the tie-extension semantics on replay. The parser
7521        // accepts OFFSET before FETCH, so keep that order here.
7522        if self.limit_with_ties {
7523            if let Some(o) = &self.offset {
7524                write!(f, " OFFSET {o}")?;
7525            }
7526            if let Some(n) = &self.limit {
7527                write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
7528            }
7529        } else {
7530            if let Some(n) = &self.limit {
7531                write!(f, " LIMIT {n}")?;
7532            }
7533            if let Some(o) = &self.offset {
7534                write!(f, " OFFSET {o}")?;
7535            }
7536        }
7537        Ok(())
7538    }
7539}
7540
7541fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7542    f.write_str("SELECT ")?;
7543    if s.distinct {
7544        f.write_str("DISTINCT ")?;
7545    }
7546    write_bare_select_body(s, f)
7547}
7548
7549fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7550    for (i, item) in s.items.iter().enumerate() {
7551        if i > 0 {
7552            f.write_str(", ")?;
7553        }
7554        write!(f, "{item}")?;
7555    }
7556    if let Some(t) = &s.from {
7557        write!(f, " FROM {t}")?;
7558    }
7559    if let Some(e) = &s.where_ {
7560        write!(f, " WHERE {e}")?;
7561    }
7562    if let Some(gs) = &s.group_by {
7563        f.write_str(" GROUP BY ")?;
7564        for (i, g) in gs.iter().enumerate() {
7565            if i > 0 {
7566                f.write_str(", ")?;
7567            }
7568            write!(f, "{g}")?;
7569        }
7570    } else if s.group_by_all {
7571        // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
7572        // shortcut parses to group_by: None + this flag; dropping
7573        // it turned an aggregate query into a bare projection on
7574        // re-parse.
7575        f.write_str(" GROUP BY ALL")?;
7576    }
7577    if let Some(h) = &s.having {
7578        write!(f, " HAVING {h}")?;
7579    }
7580    Ok(())
7581}
7582
7583impl fmt::Display for SelectItem {
7584    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7585        match self {
7586            Self::Wildcard => f.write_str("*"),
7587            Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
7588            Self::Expr { expr, alias } => {
7589                write!(f, "{expr}")?;
7590                if let Some(a) = alias {
7591                    write!(f, " AS {}", quote_ident(a))?;
7592                }
7593                Ok(())
7594            }
7595        }
7596    }
7597}
7598
7599impl fmt::Display for FromClause {
7600    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7601        write!(f, "{}", self.primary)?;
7602        for j in &self.joins {
7603            match j.kind {
7604                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
7605                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
7606                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
7607                JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
7608                JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
7609                JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
7610            }
7611            if let Some(on) = &j.on {
7612                write!(f, " ON {on}")?;
7613            }
7614        }
7615        Ok(())
7616    }
7617}
7618
7619/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
7620/// for NESTED). Kept close to the parser's grammar so it re-parses.
7621fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
7622    for (i, c) in cols.iter().enumerate() {
7623        if i > 0 {
7624            f.write_str(", ")?;
7625        }
7626        match c {
7627            JsonTableColumn::Ordinality { name } => {
7628                write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
7629            }
7630            JsonTableColumn::Nested { path, columns } => {
7631                write!(f, "NESTED PATH '{path}' COLUMNS (")?;
7632                fmt_json_table_columns(f, columns)?;
7633                f.write_str(")")?;
7634            }
7635            JsonTableColumn::Regular {
7636                name,
7637                ty,
7638                path,
7639                exists,
7640                format_json,
7641                wrapper,
7642                on_empty,
7643                on_error,
7644            } => {
7645                write!(f, "{} {ty}", quote_ident(name))?;
7646                if *format_json {
7647                    f.write_str(" FORMAT JSON")?;
7648                }
7649                if *exists {
7650                    write!(f, " EXISTS PATH '{path}'")?;
7651                } else {
7652                    write!(f, " PATH '{path}'")?;
7653                }
7654                if *wrapper {
7655                    f.write_str(" WITH WRAPPER")?;
7656                }
7657                if let JsonTableOnBehavior::Error = on_empty {
7658                    f.write_str(" ERROR ON EMPTY")?;
7659                } else if let JsonTableOnBehavior::Default(e) = on_empty {
7660                    write!(f, " DEFAULT {e} ON EMPTY")?;
7661                }
7662                if let JsonTableOnBehavior::Error = on_error {
7663                    f.write_str(" ERROR ON ERROR")?;
7664                } else if let JsonTableOnBehavior::Default(e) = on_error {
7665                    write!(f, " DEFAULT {e} ON ERROR")?;
7666                }
7667            }
7668        }
7669    }
7670    Ok(())
7671}
7672
7673impl fmt::Display for TableRef {
7674    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7675        // v7.30.1 (mailrs round-24 class audit) — the dynamic
7676        // table-ref shapes must round-trip: rendering only the
7677        // (synthetic) name turned LATERAL / unnest() /
7678        // generate_series() into references to nonexistent tables
7679        // on re-parse.
7680        // v7.39 (round 205) — JSON_TABLE round-trips through Display
7681        // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
7682        if let Some(jt) = &self.json_table {
7683            write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
7684            if !jt.passing.is_empty() {
7685                f.write_str(" PASSING ")?;
7686                for (i, (n, e)) in jt.passing.iter().enumerate() {
7687                    if i > 0 {
7688                        f.write_str(", ")?;
7689                    }
7690                    write!(f, "{e} AS {}", quote_ident(n))?;
7691                }
7692            }
7693            f.write_str(" COLUMNS (")?;
7694            fmt_json_table_columns(f, &jt.columns)?;
7695            f.write_str(")")?;
7696            if let Some(a) = &self.alias {
7697                write!(f, " AS {}", quote_ident(a))?;
7698            }
7699            return Ok(());
7700        }
7701        if let Some(inner) = &self.lateral_subquery {
7702            write!(f, "LATERAL ({inner})")?;
7703            if let Some(a) = &self.alias {
7704                write!(f, " AS {}", quote_ident(a))?;
7705                // v7.37 D.28 — a derived table on the lateral_subquery channel
7706                // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
7707                // lowers here). Rendering the alias without the column list lost
7708                // the column names on re-parse (a view body round-trips through
7709                // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
7710                if !self.unnest_column_aliases.is_empty() {
7711                    f.write_str(" (")?;
7712                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
7713                        if i > 0 {
7714                            f.write_str(", ")?;
7715                        }
7716                        f.write_str(&quote_ident(c))?;
7717                    }
7718                    f.write_str(")")?;
7719                }
7720            }
7721            return Ok(());
7722        }
7723        if let Some(expr) = &self.unnest_expr {
7724            write!(f, "UNNEST({expr})")?;
7725            if let Some(a) = &self.alias {
7726                write!(f, " AS {}", quote_ident(a))?;
7727                if !self.unnest_column_aliases.is_empty() {
7728                    f.write_str(" (")?;
7729                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
7730                        if i > 0 {
7731                            f.write_str(", ")?;
7732                        }
7733                        f.write_str(&quote_ident(c))?;
7734                    }
7735                    f.write_str(")")?;
7736                }
7737            }
7738            return Ok(());
7739        }
7740        if let Some(args) = &self.generate_series_args {
7741            f.write_str("generate_series(")?;
7742            for (i, a) in args.iter().enumerate() {
7743                if i > 0 {
7744                    f.write_str(", ")?;
7745                }
7746                write!(f, "{a}")?;
7747            }
7748            f.write_str(")")?;
7749            if let Some(a) = &self.alias {
7750                write!(f, " AS {}", quote_ident(a))?;
7751            }
7752            return Ok(());
7753        }
7754        write!(f, "{}", quote_ident(&self.name))?;
7755        if let Some(seg) = self.as_of_segment {
7756            write!(f, " AS OF SEGMENT {seg}")?;
7757        }
7758        if let Some(a) = &self.alias {
7759            write!(f, " AS {}", quote_ident(a))?;
7760        }
7761        Ok(())
7762    }
7763}
7764
7765impl fmt::Display for ColumnName {
7766    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7767        if let Some(q) = &self.qualifier {
7768            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
7769        } else {
7770            write!(f, "{}", quote_ident(&self.name))
7771        }
7772    }
7773}
7774
7775/// v7.39 (round 311) — render the left spine of an AND / OR chain
7776/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
7777/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
7778/// SAME operator flattens; anything else is an ordinary operand.
7779fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
7780    if let Expr::Binary {
7781        lhs,
7782        op: inner,
7783        rhs,
7784    } = e
7785        && *inner == op
7786    {
7787        write_bool_chain(f, lhs, op)?;
7788        return write!(f, " {op} {rhs}");
7789    }
7790    write!(f, "{e}")
7791}
7792
7793/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
7794/// form `pg_get_constraintdef(oid, true)` and friends return.
7795///
7796/// The default [`fmt::Display`] parenthesises every operator node, which
7797/// is what PG's non-pretty deparse does and what makes the text
7798/// round-trip. Pretty drops the pairs the grammar can put back, and the
7799/// rule is NOT plain precedence minimisation — measured against PG 18.4
7800/// across 37 shapes:
7801///
7802///   * the boolean layer follows precedence (NOT > AND > OR): an OR
7803///     under an AND keeps its parens, an AND under an OR does not, and a
7804///     comparison under any of them does not (`NOT a > 1`);
7805///   * an associative chain flattens completely, even where the source
7806///     nested it to the right (`a AND (b AND c)` prints as one chain);
7807///   * but an operand of a comparison or arithmetic operator keeps its
7808///     parens whenever it is itself an operator expression — so
7809///     `(a + b) > 10` and `(- a) + b`, even though precedence alone
7810///     would not require either. A cast, function call, column or
7811///     literal in that position does not (`a::text = t`,
7812///     `length(code) > 2`); a cast counts as compound exactly when the
7813///     thing it casts is (`((a + b)::text) = t`).
7814///
7815/// Anything outside that layer defers to `Display`, which is never
7816/// wrong — only more parenthesised than PG would print.
7817#[must_use]
7818pub fn pretty_expr(e: &Expr) -> String {
7819    let mut out = String::new();
7820    write_pretty(&mut out, e, PrettyParent::None, false, false);
7821    out
7822}
7823
7824/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
7825/// writes it.
7826///
7827/// MariaDB names the offending expression in its out-of-range message
7828/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
7829/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
7830/// MySQL client, for a cast the client had just written the other way.
7831#[must_use]
7832pub fn pretty_expr_mysql(e: &Expr) -> String {
7833    let mut out = String::new();
7834    write_pretty(&mut out, e, PrettyParent::None, false, true);
7835    out
7836}
7837
7838/// v7.39 (round 505) — how strongly an expression suggests its own column
7839/// name. A cast keeps its argument's name only when that name is STRONG;
7840/// otherwise the cast reports the type it casts to.
7841///
7842/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
7843/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
7844/// itself `text` — so `case` and a function name cannot be the same kind of
7845/// answer, even though a bare `CASE …` does report `case`.
7846#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
7847enum NameStrength {
7848    /// Nothing to go on — PG reports `?column?`.
7849    None,
7850    /// A name, but one a cast overrides: `case`, or a type name.
7851    Weak,
7852    /// A name a cast keeps: a column, or the function that produced it.
7853    Strong,
7854}
7855
7856/// v7.39 (round 505) — the column name PG18 gives a projected expression
7857/// that carries no `AS` alias. `None` means `?column?`.
7858///
7859/// SPG used to print the parsed expression back out, which matched neither
7860/// oracle and made name-keyed row access miss on both wires:
7861///
7862/// | query        | PG18       | SPG (before) |
7863/// |--------------|------------|--------------|
7864/// | `upper(s)`   | `upper`    | `upper(s)`   |
7865/// | `a+b`        | `?column?` | `(a + b)`    |
7866/// | `'lit'`      | `?column?` | `'lit'`      |
7867/// | `CASE …`     | `case`     | `CASE WHEN (a = 1) THEN …` |
7868///
7869/// Every rule below is one of those measurements, taken with `\gdesc`
7870/// against PG18: a call is named for its function, a cast recurses into its
7871/// argument and falls back to the type, a scalar subquery takes the name of
7872/// the column it selects, and operators have no name at all.
7873#[must_use]
7874pub fn figure_column_name(expr: &Expr) -> Option<String> {
7875    let (name, _) = figure_name_inner(expr);
7876    name
7877}
7878
7879/// The name a function reports, which is not always the name SPG parsed it
7880/// under: `count(*)` is held as `count_star` so the star arity survives the
7881/// AST, and that internal spelling must not reach a client. PG18 reports
7882/// `count`.
7883fn canonical_function_name(name: &str) -> String {
7884    match name {
7885        "count_star" => "count".to_string(),
7886        other => other.to_ascii_lowercase(),
7887    }
7888}
7889
7890fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
7891    let strong = |n: String| (Some(n), NameStrength::Strong);
7892    match expr {
7893        // A column keeps its own name, qualifier and all discarded:
7894        // `lbl.a` reports `a`.
7895        Expr::Column(c) => strong(c.name.clone()),
7896        // Calls are named for the function. This covers the shapes that
7897        // only LOOK like syntax — `EXTRACT(year FROM …)` reports
7898        // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
7899        // because PG resolves them to functions before naming them.
7900        Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
7901            strong(canonical_function_name(name))
7902        }
7903        Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
7904        Expr::Extract { .. } => strong("extract".to_string()),
7905        Expr::Exists { .. } => strong("exists".to_string()),
7906        Expr::Array(_) => strong("array".to_string()),
7907        // `(expr).field` is named for the field, as a column would be.
7908        Expr::FieldAccess { field, .. } => strong(field.clone()),
7909        // A cast prefers its argument's name and settles for the type:
7910        // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
7911        Expr::Cast {
7912            expr: inner,
7913            target,
7914        } => match figure_name_inner(inner) {
7915            (Some(n), NameStrength::Strong) => strong(n),
7916            _ => (Some(target.to_string()), NameStrength::Weak),
7917        },
7918        // A scalar subquery reports whatever its single output column
7919        // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
7920        Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
7921        // `CASE …` names itself, but weakly — a cast around it wins.
7922        Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
7923        // A literal that carries its own type names itself for that type:
7924        // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
7925        // reports nothing. Weak, like any other type name.
7926        Expr::Literal(Literal::Interval { .. }) => {
7927            (Some("interval".to_string()), NameStrength::Weak)
7928        }
7929        // A wrapper that adds no name of its own.
7930        Expr::Variadic(inner) => figure_name_inner(inner),
7931        Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
7932        // Everything else — operators, comparisons, IS NULL, LIKE, IN,
7933        // literals, placeholders — reports `?column?`.
7934        _ => (None, NameStrength::None),
7935    }
7936}
7937
7938/// The name a scalar subquery's single projected column reports.
7939fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
7940    match sel.items.as_slice() {
7941        [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
7942        [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
7943        _ => (None, NameStrength::None),
7944    }
7945}
7946
7947/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
7948fn pretty_prec(e: &Expr) -> u8 {
7949    match e {
7950        Expr::Binary { op, .. } => match op {
7951            // v7.39 (round 407) — this deparse ladder mirrors the parser's:
7952            // OR < XOR < AND < NOT < comparison < additive < multiplicative.
7953            // XOR (MySQL-only) sits between OR and AND, so AND and everything
7954            // above shifted +1 to open rung 2 for it.
7955            BinOp::Or => 1,
7956            BinOp::LogicalXor => 2,
7957            BinOp::And => 3,
7958            BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
7959            BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
7960            // Everything else in this enum is a comparison-shaped
7961            // operator; they share one level, as in the grammar.
7962            _ => 5,
7963        },
7964        Expr::Unary { op, .. } => match op {
7965            UnOp::Not => 4,
7966            UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
7967        },
7968        _ => u8::MAX,
7969    }
7970}
7971
7972/// Is this node an operator expression — the thing an arithmetic or
7973/// comparison parent keeps parentheses around? A cast inherits the
7974/// answer from what it casts.
7975fn pretty_is_compound(e: &Expr) -> bool {
7976    match e {
7977        Expr::Binary { .. } | Expr::Unary { .. } => true,
7978        Expr::Cast { expr, .. } => pretty_is_compound(expr),
7979        _ => false,
7980    }
7981}
7982
7983/// `parent` describes the enclosing operator: its binding power, and
7984/// whether it is a comparison (which keeps parens around any operator
7985/// operand) or a NOT (which keeps them at equal power too).
7986#[derive(Clone, Copy, PartialEq)]
7987enum PrettyParent {
7988    /// Nothing encloses this node.
7989    None,
7990    /// A comparison-shaped operator: an operator operand always keeps
7991    /// its parens, whatever precedence would allow.
7992    Comparison,
7993    /// Arithmetic / concatenation: precedence decides.
7994    Arith(u8),
7995    /// A boolean connective: precedence decides.
7996    Bool(u8),
7997    /// `NOT`: precedence decides, but equal power still needs parens so
7998    /// `NOT (NOT a > 1)` does not collapse.
7999    Not,
8000}
8001
8002fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8003    let prec = pretty_prec(e);
8004    let is_unary_sign = matches!(
8005        e,
8006        Expr::Unary {
8007            op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8008            ..
8009        }
8010    );
8011    let needs = match parent {
8012        PrettyParent::None => false,
8013        PrettyParent::Comparison => pretty_is_compound(e),
8014        // A sign always keeps its parens under an operator — PG writes
8015        // `(- a) + b` even though precedence would not require it.
8016        PrettyParent::Arith(p) => {
8017            is_unary_sign
8018                || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8019                    && (prec < p || (prec == p && is_rhs)))
8020        }
8021        PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8022        PrettyParent::Not => {
8023            matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8024        }
8025    };
8026    if needs {
8027        out.push('(');
8028    }
8029    match e {
8030        Expr::Binary { lhs, op, rhs } => {
8031            let child = match op {
8032                BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8033                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8034                    PrettyParent::Arith(prec)
8035                }
8036                _ => PrettyParent::Comparison,
8037            };
8038            write_pretty(out, lhs, child, false, mysql);
8039            out.push(' ');
8040            out.push_str(&alloc::format!("{op}"));
8041            out.push(' ');
8042            // AND / OR are associative, so an explicitly right-nested
8043            // chain still prints as one chain.
8044            let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8045            write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8046        }
8047        Expr::Unary { op, expr } => match op {
8048            UnOp::Not => {
8049                out.push_str("NOT ");
8050                write_pretty(out, expr, PrettyParent::Not, false, mysql);
8051            }
8052            UnOp::Neg => {
8053                out.push_str("- ");
8054                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8055            }
8056            UnOp::Plus => {
8057                out.push_str("+ ");
8058                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8059            }
8060            UnOp::BitNot => {
8061                out.push('~');
8062                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8063            }
8064        },
8065        Expr::Cast { expr, target } => {
8066            if mysql {
8067                // MySQL's own spelling, which is what its error messages
8068                // quote back.
8069                out.push_str("cast(");
8070                write_pretty(out, expr, PrettyParent::None, false, mysql);
8071                out.push_str(&alloc::format!(
8072                    " as {})",
8073                    target.to_string().to_lowercase()
8074                ));
8075            } else {
8076                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8077                out.push_str(&alloc::format!("::{target}"));
8078            }
8079        }
8080        Expr::IsNull { expr, negated } => {
8081            write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8082            out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8083        }
8084        other => out.push_str(&alloc::format!("{other}")),
8085    }
8086    if needs {
8087        out.push(')');
8088    }
8089}
8090
8091const fn pretty_prec_not() -> u8 {
8092    // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8093    // when the XOR insertion shifted the deparse ladder up by one).
8094    4
8095}
8096
8097impl fmt::Display for Expr {
8098    #[allow(clippy::too_many_lines)]
8099    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8100        match self {
8101            Self::Literal(l) => write!(f, "{l}"),
8102            Self::Column(c) => write!(f, "{c}"),
8103            Self::Placeholder(n) => write!(f, "${n}"),
8104            // Round-trips as the spelling PG's docs lead with.
8105            Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8106            Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8107            // v7.39 (round 311) — an AND / OR chain that nests to the
8108            // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8109            // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8110            // its parentheses, because that is a different grouping as
8111            // written. Both halves measured against PG 18.4's deparse,
8112            // which flattens a same-operator left chain at parse time and
8113            // leaves `a AND (b AND c)` alone.
8114            Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8115                f.write_str("(")?;
8116                write_bool_chain(f, lhs, *op)?;
8117                write!(f, " {op} {rhs}")?;
8118                f.write_str(")")
8119            }
8120            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8121            Self::Unary { op, expr } => match op {
8122                UnOp::Not => write!(f, "(NOT {expr})"),
8123                // A space after the sign, as PG's deparse writes it.
8124                UnOp::Neg => write!(f, "(- {expr})"),
8125                UnOp::Plus => write!(f, "(+ {expr})"),
8126                UnOp::BitNot => write!(f, "(~{expr})"),
8127            },
8128            // The OPERAND carries the parentheses, not the cast:
8129            // `(a)::text`, `((a + b))::text`. PG words it this way, and
8130            // it is what keeps `a::text = t` from reading as a cast of
8131            // the comparison.
8132            Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8133            Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8134            Self::AggregateOrdered {
8135                call,
8136                order_by,
8137                distinct,
8138                filter,
8139            } => {
8140                let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8141                    for (i, o) in order_by.iter().enumerate() {
8142                        if i > 0 {
8143                            f.write_str(", ")?;
8144                        }
8145                        write!(f, "{}", o.expr)?;
8146                        if o.desc {
8147                            f.write_str(" DESC")?;
8148                        }
8149                        match o.nulls_first {
8150                            Some(true) => f.write_str(" NULLS FIRST")?,
8151                            Some(false) => f.write_str(" NULLS LAST")?,
8152                            None => {}
8153                        }
8154                    }
8155                    Ok(())
8156                };
8157                // Ordered-set aggregates (`percentile_cont(f) WITHIN
8158                // GROUP (ORDER BY x)`) render the in-parens args as the
8159                // direct argument and the sort spec under WITHIN GROUP —
8160                // not as an in-argument ORDER BY.
8161                let ordered_set = matches!(
8162                    call.as_ref(),
8163                    Expr::FunctionCall { name, .. }
8164                        if matches!(
8165                            name.to_ascii_lowercase().as_str(),
8166                            "percentile_cont" | "percentile_disc" | "mode"
8167                        )
8168                );
8169                if ordered_set {
8170                    write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8171                    fmt_order_by(f)?;
8172                    f.write_str(")")?;
8173                } else {
8174                    // `name([DISTINCT ]args [ORDER BY …])` — peel the
8175                    // inner call's parens to splice modifiers.
8176                    let inner = alloc::format!("{call}");
8177                    let body = inner.strip_suffix(')').unwrap_or(&inner);
8178                    let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8179                    write!(f, "{head}(")?;
8180                    if *distinct {
8181                        f.write_str("DISTINCT ")?;
8182                    }
8183                    write!(f, "{args_part}")?;
8184                    if !order_by.is_empty() {
8185                        f.write_str(" ORDER BY ")?;
8186                        fmt_order_by(f)?;
8187                    }
8188                    f.write_str(")")?;
8189                }
8190                if let Some(cond) = filter {
8191                    write!(f, " FILTER (WHERE {cond})")?;
8192                }
8193                Ok(())
8194            }
8195            Self::IsNull { expr, negated } => {
8196                if *negated {
8197                    write!(f, "({expr} IS NOT NULL)")
8198                } else {
8199                    write!(f, "({expr} IS NULL)")
8200                }
8201            }
8202            Self::BoolTest {
8203                expr,
8204                value,
8205                negated,
8206            } => {
8207                let word = match value {
8208                    Some(true) => "TRUE",
8209                    Some(false) => "FALSE",
8210                    None => "UNKNOWN",
8211                };
8212                if *negated {
8213                    write!(f, "({expr} IS NOT {word})")
8214                } else {
8215                    write!(f, "({expr} IS {word})")
8216                }
8217            }
8218            Self::FunctionCall { name, args } => {
8219                write!(f, "{name}(")?;
8220                for (i, a) in args.iter().enumerate() {
8221                    if i > 0 {
8222                        f.write_str(", ")?;
8223                    }
8224                    write!(f, "{a}")?;
8225                }
8226                f.write_str(")")
8227            }
8228            Self::Like {
8229                expr,
8230                pattern,
8231                negated,
8232                case_insensitive,
8233            } => {
8234                let op = match (negated, case_insensitive) {
8235                    (false, false) => "LIKE",
8236                    (true, false) => "NOT LIKE",
8237                    (false, true) => "ILIKE",
8238                    (true, true) => "NOT ILIKE",
8239                };
8240                write!(f, "({expr} {op} {pattern})")
8241            }
8242            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8243            Self::WindowFunction {
8244                name,
8245                args,
8246                partition_by,
8247                order_by,
8248                frame,
8249                null_treatment,
8250                filter,
8251            } => {
8252                write!(f, "{name}(")?;
8253                for (i, a) in args.iter().enumerate() {
8254                    if i > 0 {
8255                        f.write_str(", ")?;
8256                    }
8257                    write!(f, "{a}")?;
8258                }
8259                f.write_str(")")?;
8260                // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8261                // OVER; it round-trips so a window body's Display re-parses.
8262                if let Some(cond) = filter {
8263                    write!(f, " FILTER (WHERE {cond})")?;
8264                }
8265                // v7.30.1 (mailrs round-24 class audit) — IGNORE
8266                // NULLS sits between the arg list and OVER; dropping
8267                // it reverted replayed queries to RESPECT NULLS.
8268                if matches!(null_treatment, NullTreatment::Ignore) {
8269                    f.write_str(" IGNORE NULLS")?;
8270                }
8271                f.write_str(" OVER (")?;
8272                if !partition_by.is_empty() {
8273                    f.write_str("PARTITION BY ")?;
8274                    for (i, p) in partition_by.iter().enumerate() {
8275                        if i > 0 {
8276                            f.write_str(", ")?;
8277                        }
8278                        write!(f, "{p}")?;
8279                    }
8280                }
8281                if !order_by.is_empty() {
8282                    if !partition_by.is_empty() {
8283                        f.write_str(" ")?;
8284                    }
8285                    f.write_str("ORDER BY ")?;
8286                    for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8287                        if i > 0 {
8288                            f.write_str(", ")?;
8289                        }
8290                        write!(f, "{e}")?;
8291                        if *desc {
8292                            f.write_str(" DESC")?;
8293                        }
8294                        match nulls_first {
8295                            Some(true) => f.write_str(" NULLS FIRST")?,
8296                            Some(false) => f.write_str(" NULLS LAST")?,
8297                            None => {}
8298                        }
8299                    }
8300                }
8301                if let Some(fr) = frame {
8302                    if !partition_by.is_empty() || !order_by.is_empty() {
8303                        f.write_str(" ")?;
8304                    }
8305                    let k = match fr.kind {
8306                        FrameKind::Rows => "ROWS",
8307                        FrameKind::Range => "RANGE",
8308                        FrameKind::Groups => "GROUPS",
8309                    };
8310                    if let Some(end) = &fr.end {
8311                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8312                    } else {
8313                        write!(f, "{k} {}", fr.start)?;
8314                    }
8315                }
8316                f.write_str(")")
8317            }
8318            Self::ScalarSubquery(s) => write!(f, "({s})"),
8319            Self::Exists { subquery, negated } => {
8320                if *negated {
8321                    write!(f, "NOT EXISTS ({subquery})")
8322                } else {
8323                    write!(f, "EXISTS ({subquery})")
8324                }
8325            }
8326            Self::InSubquery {
8327                expr,
8328                subquery,
8329                negated,
8330            } => {
8331                if *negated {
8332                    write!(f, "({expr} NOT IN ({subquery}))")
8333                } else {
8334                    write!(f, "({expr} IN ({subquery}))")
8335                }
8336            }
8337            Self::RowInSubquery {
8338                row,
8339                subquery,
8340                negated,
8341            } => {
8342                write!(f, "(")?;
8343                for (i, e) in row.iter().enumerate() {
8344                    if i > 0 {
8345                        write!(f, ", ")?;
8346                    }
8347                    write!(f, "{e}")?;
8348                }
8349                let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8350                write!(f, "{kw}{subquery})")
8351            }
8352            Self::RowCmpSubquery { row, op, subquery } => {
8353                write!(f, "(")?;
8354                for (i, e) in row.iter().enumerate() {
8355                    if i > 0 {
8356                        write!(f, ", ")?;
8357                    }
8358                    write!(f, "{e}")?;
8359                }
8360                write!(f, ") {op} ({subquery})")
8361            }
8362            Self::InList {
8363                expr,
8364                list,
8365                negated,
8366            } => {
8367                let kw = if *negated { " NOT IN (" } else { " IN (" };
8368                write!(f, "({expr}{kw}")?;
8369                for (i, e) in list.iter().enumerate() {
8370                    if i > 0 {
8371                        f.write_str(", ")?;
8372                    }
8373                    write!(f, "{e}")?;
8374                }
8375                f.write_str("))")
8376            }
8377            Self::Array(items) => {
8378                f.write_str("ARRAY[")?;
8379                for (i, e) in items.iter().enumerate() {
8380                    if i > 0 {
8381                        f.write_str(", ")?;
8382                    }
8383                    write!(f, "{e}")?;
8384                }
8385                f.write_str("]")
8386            }
8387            Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
8388            Self::ArraySlice { target, lo, hi } => {
8389                write!(f, "({target}[")?;
8390                if let Some(l) = lo {
8391                    write!(f, "{l}")?;
8392                }
8393                write!(f, ":")?;
8394                if let Some(h) = hi {
8395                    write!(f, "{h}")?;
8396                }
8397                write!(f, "])")
8398            }
8399            Self::AnyAll {
8400                expr,
8401                op,
8402                array,
8403                is_any,
8404            } => {
8405                let kw = if *is_any { "ANY" } else { "ALL" };
8406                write!(f, "({expr} {op} {kw}({array}))")
8407            }
8408            Self::Case {
8409                operand,
8410                branches,
8411                else_branch,
8412            } => {
8413                f.write_str("CASE")?;
8414                if let Some(op) = operand {
8415                    write!(f, " {op}")?;
8416                }
8417                for (w, t) in branches {
8418                    write!(f, " WHEN {w} THEN {t}")?;
8419                }
8420                if let Some(e) = else_branch {
8421                    write!(f, " ELSE {e}")?;
8422                }
8423                f.write_str(" END")
8424            }
8425        }
8426    }
8427}
8428
8429/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
8430/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
8431pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
8432    use alloc::string::ToString;
8433    if scale == 0 {
8434        return alloc::format!("{unscaled}");
8435    }
8436    let neg = unscaled < 0;
8437    let digits = alloc::format!("{}", unscaled.unsigned_abs());
8438    let scale = scale as usize;
8439    let (int_part, frac_part) = if digits.len() > scale {
8440        (
8441            digits[..digits.len() - scale].to_string(),
8442            digits[digits.len() - scale..].to_string(),
8443        )
8444    } else {
8445        ("0".to_string(), alloc::format!("{digits:0>scale$}"))
8446    };
8447    alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
8448}
8449
8450impl fmt::Display for Literal {
8451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8452        match self {
8453            Self::Integer(n) => write!(f, "{n}"),
8454            Self::Float(x) => {
8455                let s = format!("{x}");
8456                // Default Display for an integral f64 (e.g. 1.0) emits "1",
8457                // which would round-trip back to Integer. Force a dot.
8458                if s.contains('.') || s.contains('e') || s.contains('E') {
8459                    f.write_str(&s)
8460                } else {
8461                    write!(f, "{s}.0")
8462                }
8463            }
8464            Self::Numeric { unscaled, scale } => {
8465                // Render the exact decimal `unscaled / 10^scale`, preserving
8466                // scale (trailing zeros) — round-trips to the same literal.
8467                f.write_str(&render_exact_decimal(*unscaled, *scale))
8468            }
8469            Self::NumericBig(s) => f.write_str(s),
8470            Self::String(s) => {
8471                f.write_str("'")?;
8472                for c in s.chars() {
8473                    if c == '\'' {
8474                        f.write_str("''")?;
8475                    } else {
8476                        write!(f, "{c}")?;
8477                    }
8478                }
8479                f.write_str("'")
8480            }
8481            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
8482            Self::Null => f.write_str("NULL"),
8483            // PG external array form. Display round-trip re-enters
8484            // through the column-typed text coerce, same as pgwire.
8485            Self::TextArray(items) => {
8486                f.write_str("'{")?;
8487                for (i, it) in items.iter().enumerate() {
8488                    if i > 0 {
8489                        f.write_str(",")?;
8490                    }
8491                    match it {
8492                        None => f.write_str("NULL")?,
8493                        Some(s) => {
8494                            f.write_str("\"")?;
8495                            for c in s.chars() {
8496                                match c {
8497                                    // array-element escapes
8498                                    '"' | '\\' => write!(f, "\\{c}")?,
8499                                    // the OUTER wrapper is a SQL string
8500                                    // literal — embedded quotes must
8501                                    // double, or the rendered form
8502                                    // (WAL replay parses it back) is
8503                                    // invalid SQL
8504                                    '\'' => f.write_str("''")?,
8505                                    _ => write!(f, "{c}")?,
8506                                }
8507                            }
8508                            f.write_str("\"")?;
8509                        }
8510                    }
8511                }
8512                f.write_str("}'")
8513            }
8514            Self::IntArray(items) => {
8515                f.write_str("'{")?;
8516                for (i, it) in items.iter().enumerate() {
8517                    if i > 0 {
8518                        f.write_str(",")?;
8519                    }
8520                    match it {
8521                        None => f.write_str("NULL")?,
8522                        Some(n) => write!(f, "{n}")?,
8523                    }
8524                }
8525                f.write_str("}'")
8526            }
8527            Self::BigIntArray(items) => {
8528                f.write_str("'{")?;
8529                for (i, it) in items.iter().enumerate() {
8530                    if i > 0 {
8531                        f.write_str(",")?;
8532                    }
8533                    match it {
8534                        None => f.write_str("NULL")?,
8535                        Some(n) => write!(f, "{n}")?,
8536                    }
8537                }
8538                f.write_str("}'")
8539            }
8540            Self::Vector(v) => {
8541                f.write_str("[")?;
8542                for (i, x) in v.iter().enumerate() {
8543                    if i > 0 {
8544                        f.write_str(", ")?;
8545                    }
8546                    let s = format!("{x}");
8547                    // Mirror Float Display: force a dot so re-parse stays
8548                    // numerically literal.
8549                    if s.contains('.') || s.contains('e') || s.contains('E') {
8550                        f.write_str(&s)?;
8551                    } else {
8552                        write!(f, "{s}.0")?;
8553                    }
8554                }
8555                f.write_str("]")
8556            }
8557            Self::Interval { text, .. } => {
8558                f.write_str("INTERVAL '")?;
8559                for c in text.chars() {
8560                    if c == '\'' {
8561                        f.write_str("''")?;
8562                    } else {
8563                        write!(f, "{c}")?;
8564                    }
8565                }
8566                f.write_str("'")
8567            }
8568        }
8569    }
8570}
8571
8572impl fmt::Display for BinOp {
8573    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8574        f.write_str(match self {
8575            Self::Or => "OR",
8576            Self::And => "AND",
8577            Self::Eq => "=",
8578            Self::NotEq => "<>",
8579            Self::IsDistinctFrom => "IS DISTINCT FROM",
8580            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
8581            Self::IntDiv => "DIV",
8582            Self::Lt => "<",
8583            Self::LtEq => "<=",
8584            Self::Gt => ">",
8585            Self::GtEq => ">=",
8586            Self::Add => "+",
8587            Self::Sub => "-",
8588            Self::Mul => "*",
8589            Self::Div => "/",
8590            Self::Mod => "%",
8591            Self::L2Distance => "<->",
8592            Self::GeomParallel => "?||",
8593            Self::OverLeft => "&<",
8594            Self::OverRight => "&>",
8595            Self::GeomPerp => "?-|",
8596            Self::GeomSameAs => "~=",
8597            Self::ClosestPoint => "##",
8598            Self::GeomHoriz => "?-",
8599            Self::InnerProduct => "<#>",
8600            Self::CosineDistance => "<=>",
8601            Self::Concat => "||",
8602            Self::BitOr => "|",
8603            Self::BitAnd => "&",
8604            Self::BitXor => "#",
8605            Self::LogicalXor => "xor",
8606            Self::JsonGet => "->",
8607            Self::JsonGetText => "->>",
8608            Self::JsonGetPath => "#>",
8609            Self::JsonGetPathText => "#>>",
8610            Self::JsonContains => "@>",
8611            Self::JsonPathExists => "@?",
8612            Self::JsonContainedBy => "<@",
8613            Self::JsonKeyExists => "?",
8614            Self::JsonKeysAny => "?|",
8615            Self::JsonKeysAll => "?&",
8616            Self::JsonDeletePath => "#-",
8617            Self::TsMatch => "@@",
8618            Self::InetContainedBy => "<<",
8619            Self::InetContainedByEq => "<<=",
8620            Self::InetContains => ">>",
8621            Self::InetContainsEq => ">>=",
8622            Self::InetOverlap => "&&",
8623            Self::Intersects => "?#",
8624            Self::IsBelow => "<^",
8625            Self::IsAbove => ">^",
8626            Self::PatternLt => "~<~",
8627            Self::PatternLtEq => "~<=~",
8628            Self::PatternGt => "~>~",
8629            Self::PatternGtEq => "~>=~",
8630        })
8631    }
8632}
8633
8634/// Quote `s` as a PG double-quoted identifier when required (keyword,
8635/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
8636/// Otherwise return it as-is. Returns an owned `String` to keep the call site
8637/// uniform.
8638pub(crate) fn quote_ident(s: &str) -> String {
8639    let needs_quote = match s.chars().next() {
8640        None => true,
8641        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
8642        _ => {
8643            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
8644                || s.chars().any(|c| c.is_ascii_uppercase())
8645                || is_keyword(s)
8646        }
8647    };
8648    if !needs_quote {
8649        return s.to_string();
8650    }
8651    let mut out = String::with_capacity(s.len() + 2);
8652    out.push('"');
8653    for c in s.chars() {
8654        if c == '"' {
8655            out.push_str("\"\"");
8656        } else {
8657            out.push(c);
8658        }
8659    }
8660    out.push('"');
8661    out
8662}
8663
8664fn is_keyword(s: &str) -> bool {
8665    matches!(
8666        &*s.to_ascii_lowercase(),
8667        "select"
8668            | "from"
8669            | "where"
8670            | "as"
8671            | "null"
8672            | "true"
8673            | "false"
8674            | "and"
8675            | "or"
8676            | "not"
8677            | "create"
8678            | "table"
8679            | "insert"
8680            | "into"
8681            | "values"
8682            | "index"
8683            | "on"
8684            | "begin"
8685            | "commit"
8686            | "rollback"
8687            | "is"
8688            | "between"
8689            | "in"
8690            | "like"
8691            | "group"
8692            | "distinct"
8693            | "union"
8694            | "all"
8695            | "join"
8696            | "inner"
8697            | "left"
8698            | "cross"
8699            | "outer"
8700            | "default"
8701            | "savepoint"
8702            | "release"
8703            | "to"
8704            | "having"
8705            | "show"
8706            | "extract"
8707            | "offset"
8708            | "asc"
8709            | "desc"
8710            | "interval"
8711    )
8712}
8713
8714#[cfg(test)]
8715mod tests {
8716    use super::*;
8717    use alloc::vec;
8718
8719    #[test]
8720    fn integer_literal_renders_without_dot() {
8721        assert_eq!(Literal::Integer(42).to_string(), "42");
8722    }
8723
8724    #[test]
8725    fn integral_float_keeps_dot() {
8726        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
8727        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
8728        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
8729    }
8730
8731    #[test]
8732    fn string_literal_doubles_quote() {
8733        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
8734    }
8735
8736    #[test]
8737    fn bool_and_null_render_uppercase() {
8738        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
8739        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
8740        assert_eq!(Literal::Null.to_string(), "NULL");
8741    }
8742
8743    #[test]
8744    fn binary_op_always_parenthesised() {
8745        let e = Expr::Binary {
8746            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
8747            op: BinOp::Add,
8748            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
8749        };
8750        assert_eq!(e.to_string(), "(1 + 2)");
8751    }
8752
8753    #[test]
8754    fn select_star_from_table() {
8755        let s = SelectStatement {
8756            locking: None,
8757            items: vec![SelectItem::Wildcard],
8758            from: Some(FromClause {
8759                primary: TableRef {
8760                    name: "users".into(),
8761                    alias: None,
8762                    only: false,
8763                    as_of_segment: None,
8764                    unnest_expr: None,
8765                    unnest_column_aliases: Vec::new(),
8766                    with_ordinality: false,
8767                    generate_series_args: None,
8768                    lateral_subquery: None,
8769                    jsonb_each_text_arg: None,
8770                    table_fn_call: None,
8771                    rows_from: None,
8772                    json_table: None,
8773                    scalar_fn_item: false,
8774                },
8775                joins: vec![],
8776            }),
8777            where_: None,
8778            group_by: None,
8779            group_by_all: false,
8780            having: None,
8781            unions: vec![],
8782            order_by: Vec::new(),
8783            limit: None,
8784            offset: None,
8785            limit_with_ties: false,
8786            window_check_exprs: Vec::new(),
8787            distinct: false,
8788            distinct_on: Vec::new(),
8789            ctes: vec![],
8790        };
8791        assert_eq!(s.to_string(), "SELECT * FROM users");
8792    }
8793
8794    #[test]
8795    fn quote_ident_for_uppercase_and_keyword() {
8796        assert_eq!(quote_ident("foo"), "foo");
8797        assert_eq!(quote_ident("Foo"), "\"Foo\"");
8798        assert_eq!(quote_ident("select"), "\"select\"");
8799        assert_eq!(quote_ident(""), "\"\"");
8800        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
8801    }
8802}