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        /// v7.38.18 — `CREATE DATABASE … LC_COLLATE 'de_DE.utf8'` is in
228        /// every PostgreSQL bootstrap script there is, and SPG threw the
229        /// whole statement away. Being single-database makes the NAME a
230        /// no-op; it does not make the collation one, and a database
231        /// that quietly sorts by the container's `LANG` instead of the
232        /// one the script asked for is a silent difference in every
233        /// `ORDER BY` it will ever run.
234        ///
235        /// `LOCALE` and `LC_COLLATE` both land here; `LC_CTYPE` does
236        /// not, because SPG has no separate ctype.
237        collation: Option<String>,
238        /// v7.38.19 — the database's name, so `pg_database` can list one
239        /// that was created and can be connected to. It was thrown away
240        /// with the rest of the statement.
241        name: Option<String>,
242    },
243    /// v7.39 (round 696) — statements SPG performs nothing for, but whose
244    /// OPERAND PG validates before performing nothing either.
245    ///
246    /// All four used to be consumed whole by `is_dump_noise_statement`,
247    /// which meant `LOCK TABLE nosuch` and `DROP OWNED BY nosuchrole` were
248    /// ACCEPTED where PG18 errors. Accepting a statement that names
249    /// something that does not exist is the F29 shape: the caller is told
250    /// their intent was understood when the object it referred to is not
251    /// there.
252    ///
253    /// They share one variant because they share one rule — resolve the
254    /// name, refuse if absent, otherwise no-op — and four variants would be
255    /// four places for that rule to drift.
256    /// v7.39 (round 707) — `DROP AGGREGATE [IF EXISTS] name(argtypes)[, …]`.
257    /// Consumed whole by the dump-noise list before, so `DROP AGGREGATE
258    /// nosuch(int)` reported success. PG validates every named aggregate's
259    /// EXISTENCE first (measured: a list with one unknown fails on the
260    /// unknown even when an earlier entry exists), renders the signature
261    /// with canonical type names (`int` → `integer`), and refuses to drop a
262    /// built-in (`cannot drop function sum(integer) because it is required
263    /// by the database system`). Every SPG aggregate is a built-in, so the
264    /// outcome is one of those two errors — or the IF EXISTS no-op.
265    ///
266    /// `args` holds the argument type names as written; `None` is the
267    /// `(*)` spelling.
268    DropAggregate {
269        if_exists: bool,
270        items: Vec<(String, Option<Vec<String>>)>,
271    },
272    /// v7.39 (round 750) — `ALTER ROLE|USER <name> … PASSWORD 'x' |
273    /// PASSWORD NULL`. The one attribute of the no-op family with a
274    /// SECURITY consequence: it was silently dropped (ledgered r710),
275    /// so a rotated credential never rotated. `None` = PASSWORD NULL
276    /// (the role keeps existing but can no longer password-auth).
277    AlterRolePassword {
278        name: String,
279        password: Option<String>,
280    },
281    ValidateOnly {
282        kind: ValidateOnlyKind,
283        /// The names the statement referred to. Empty means the form names
284        /// nothing (`SECURITY LABEL`, whose refusal is unconditional).
285        names: Vec<String>,
286    },
287
288    /// v7.39 (round 547) — `ALTER ROLE … SET/RESET` and
289    /// `ALTER DATABASE … SET/RESET`: the GUC defaults a session picks up
290    /// when it starts. Both used to land in the pg_dump no-op tail, so
291    /// the statement reported success and changed nothing.
292    ///
293    /// `database` / `role` are `None` for PG's oid 0 — `ALTER ROLE ALL`
294    /// sets both to None. `param` is `None` for RESET ALL. `value` is
295    /// `None` for RESET of one parameter.
296    SetDbRoleSetting(Box<SetDbRoleSettingStatement>),
297    /// v7.39 (round 288) — `SET CONSTRAINTS { ALL | <name>… }
298    /// { DEFERRED | IMMEDIATE }`. `deferred` carries the timing; the
299    /// name list is not yet honoured (ALL is what pg_dump emits and
300    /// what a circular-FK restore needs), so a named form applies to
301    /// all deferrable constraints too rather than silently doing
302    /// nothing.
303    /// v7.39 (round 308) — `SET CONSTRAINTS { ALL | name [, …] }
304    /// { DEFERRED | IMMEDIATE }`. An empty `names` is the ALL form;
305    /// otherwise the timing applies only to the constraints listed.
306    SetConstraints {
307        names: Vec<String>,
308        deferred: bool,
309    },
310
311    /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
312    /// [CASCADE | RESTRICT]`. Engine removes the matching tables
313    /// (each one) from the catalog; IF EXISTS makes the drop
314    /// idempotent. CASCADE / RESTRICT trailers parsed silently
315    /// (SPG always cascades index drops on table drop).
316    DropTable {
317        names: Vec<String>,
318        if_exists: bool,
319    },
320    /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
321    /// matching index across whichever table holds it.
322    DropIndex {
323        name: String,
324        if_exists: bool,
325        /// v7.39.7 — the table named by MySQL's `DROP INDEX i ON t`.
326        ///
327        /// MySQL keys an index name inside its table and its statement
328        /// says so; PostgreSQL keys it in the schema and has no `ON`
329        /// clause at all. `None` is the PostgreSQL form, which searches
330        /// every table for the name, and is what the MySQL dialect
331        /// refuses — as MySQL does.
332        table: Option<String>,
333    },
334    /// v7.14.0 — empty / comment-only statement. The lexer strips
335    /// `--` line comments and `/* … */` block comments (including
336    /// the MySQL conditional `/*!NNNNN … */` form) before the
337    /// parser ever sees them; a SQL chunk that contains nothing
338    /// else lands here. Engine returns CommandOk no-op so
339    /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
340    /// wrapped in conditional comments, etc.) load cleanly.
341    /// v7.39 (round 277) — SQL-level `PREPARE <name> [(type, …)] AS
342    /// <stmt>`. Session-scoped; the body keeps its `$N` placeholders
343    /// and is substituted at EXECUTE time.
344    Prepare {
345        name: String,
346        /// Declared parameter type names, in order. Empty when the
347        /// `(type, …)` list was omitted (PG infers them).
348        param_types: Vec<String>,
349        body: alloc::boxed::Box<Statement>,
350        /// The statement's own source text, which
351        /// `pg_prepared_statements.statement` reports verbatim.
352        source: String,
353    },
354    /// v7.39 (round 277) — `EXECUTE <name> [(arg, …)]`.
355    Execute {
356        name: String,
357        args: Vec<Expr>,
358    },
359    /// v7.39 (round 277) — `DEALLOCATE {<name> | ALL}`. `None` = ALL.
360    Deallocate(Option<String>),
361    /// v7.39 (round 280) — `CREATE STATISTICS [IF NOT EXISTS] <name>
362    /// [(kind, …)] ON <col>, … FROM <table>`. SPG records the object so
363    /// dumps restore and reflection is honest; the planner does not
364    /// consult it yet.
365    CreateStatistics {
366        name: String,
367        if_not_exists: bool,
368        /// Requested kinds as PG's single letters (`d` ndistinct,
369        /// `f` dependencies, `m` mcv). Empty = PG's default set.
370        kinds: Vec<String>,
371        columns: Vec<String>,
372        table: String,
373    },
374    /// v7.39 (round 280) — `DROP STATISTICS [IF EXISTS] <name>`.
375    DropStatistics {
376        name: String,
377        if_exists: bool,
378    },
379    /// v7.39 (round 278) — `CALL <proc>(…)`. Parses; the engine
380    /// reports that the procedure does not exist, because SPG has no
381    /// procedure catalog. Carried as a statement rather than raised at
382    /// parse time so the failure is a missing OBJECT (42883), not a
383    /// syntax error.
384    Call(String),
385    /// v7.39 (round 278) — `PREPARE TRANSACTION '<gid>'`. Same shape:
386    /// 2PC is unavailable, which PG itself reports when
387    /// `max_prepared_transactions` is 0.
388    PrepareTransaction(String),
389    Empty,
390    /// v7.39 (round 218) — `DECLARE <name> [BINARY] [INSENSITIVE]
391    /// [[NO] SCROLL] CURSOR [{WITH|WITHOUT} HOLD] FOR <select>`. The
392    /// canonical driver path for streaming large result sets (psycopg2
393    /// named cursors, JDBC setFetchSize).
394    DeclareCursor {
395        name: String,
396        /// `None` = neither keyword (PG default: backward allowed when the
397        /// plan supports it — always, for SPG's materialized cursors);
398        /// `Some(true)` = SCROLL; `Some(false)` = NO SCROLL (backward
399        /// fetch errors 55000).
400        scroll: Option<bool>,
401        /// `WITH HOLD` — survives the creating transaction's COMMIT.
402        hold: bool,
403        query: Box<Statement>,
404    },
405    /// v7.39 (round 218) — `FETCH [<direction>] [FROM|IN] <name>`.
406    FetchCursor {
407        name: String,
408        direction: CursorDirection,
409    },
410    /// v7.39 (round 218) — `MOVE [<direction>] [FROM|IN] <name>`: FETCH
411    /// without returning rows; the command tag carries the move count.
412    MoveCursor {
413        name: String,
414        direction: CursorDirection,
415    },
416    /// v7.39 (round 218) — `CLOSE <name>` / `CLOSE ALL` (`None` = ALL).
417    CloseCursor {
418        name: Option<String>,
419    },
420    /// v7.39 (round 222) — `LISTEN <channel>`: subscribe this session to
421    /// async notifications on the channel.
422    Listen(String),
423    /// v7.39 (round 222) — `NOTIFY <channel> [, '<payload>']`. Delivered at
424    /// COMMIT (PG semantics: transactional, deduplicated within the tx);
425    /// immediately under autocommit.
426    Notify {
427        channel: String,
428        payload: Option<String>,
429    },
430    /// v7.39 (round 222) — `UNLISTEN <channel>` / `UNLISTEN *` (`None` = *).
431    Unlisten(Option<String>),
432    /// `COPY table [(cols)] TO STDOUT` — the engine renders the
433    /// visible rows in COPY text format (tab-separated, `\N`
434    /// nulls, backslash escapes) as a single-text-column result
435    /// set; the wire layer streams CopyData from it.
436    CopyTo {
437        table: String,
438        columns: Option<Vec<String>>,
439        /// v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT`: an
440        /// arbitrary SELECT/VALUES/CTE (a whole [`Statement`], so set-ops and
441        /// VALUES ride through unchanged) whose result set is streamed in COPY
442        /// format. `Some` overrides `table`/`columns` (which are empty then);
443        /// `None` is the classic `COPY <table> …` shape.
444        query: Option<Box<Statement>>,
445        /// v7.37.x — `WITH (FORMAT csv, HEADER, DELIMITER, NULL, QUOTE)`
446        /// and the legacy `WITH CSV HEADER …` spelling. Default =
447        /// text format, no header (bare `COPY … TO STDOUT`).
448        options: CopyOptions,
449    },
450    /// v7.39 (round 249) — `COPY table [(cols)] FROM '<path>' [(opts)]`.
451    /// The engine is no_std and cannot read the file itself: the host
452    /// (embedded / server / tooling) reads the path and hands the bytes to
453    /// `Engine::copy_from_buffer`. Dispatching this statement straight to
454    /// the engine reports that contract.
455    CopyFromFile {
456        table: String,
457        columns: Option<Vec<String>>,
458        path: String,
459        options: CopyOptions,
460    },
461    /// v7.39 (round 249/252) — `COPY <table> [(cols)] TO '<file>'` (and
462    /// the `COPY (<query>) TO '<file>'` form). The engine is no_std and
463    /// cannot write the file itself: the host renders the payload via
464    /// `Engine::copy_to_buffer` and writes the path.
465    CopyToFile {
466        table: String,
467        columns: Option<Vec<String>>,
468        query: Option<Box<Statement>>,
469        path: String,
470        options: CopyOptions,
471    },
472    Select(SelectStatement),
473    CreateTable(CreateTableStatement),
474    /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
475    /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
476    /// no-op so PG dumps that include extension declarations
477    /// (notably `pgvector`) load against SPG without splitting
478    /// init scripts. mailrs migration follow-up F3.
479    CreateExtension(String),
480    /// v7.9.27 → v7.16.2 — PG `DO $$ … $$ [LANGUAGE plpgsql];`
481    /// block. The body is now CAPTURED as a [`PlPgSqlBlock`] and
482    /// the engine executes it at top level (mailrs round-10
483    /// A.2). Pre-v7.16.2 the parser discarded the body and the
484    /// engine returned CommandOk — a SEV-1 silent no-op that
485    /// turned mailrs's `DO BEGIN IF EXISTS … THEN ALTER … END
486    /// $$` idempotent migrations into invisible no-ops.
487    DoBlock(PlPgSqlBlock),
488    CreateIndex(CreateIndexStatement),
489    Insert(InsertStatement),
490    /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
491    Update(UpdateStatement),
492    /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
493    Delete(DeleteStatement),
494    /// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ `MERGE` statement.
495    /// `MERGE INTO target [alias] USING source [alias] ON cond
496    /// WHEN MATCHED [AND cond] THEN { UPDATE SET … | DELETE | DO NOTHING }
497    /// WHEN NOT MATCHED [AND cond] THEN { INSERT (cols) VALUES (vals) | DO NOTHING }
498    /// [WHEN …]`. SPG v7.17 supports table-based source (subquery
499    /// source is a follow-up); BY SOURCE / BY TARGET and RETURNING
500    /// are also follow-ups.
501    Merge(MergeStatement),
502    /// v7.39 (round 169) — `VACUUM [(opts)] [FULL|FREEZE|VERBOSE|ANALYZE]
503    /// [<table>]`. Was a parse-time no-op from the pre-MVCC era; with the
504    /// in-place MVCC gate ON, tombstoned versions are REAL bloat and a
505    /// customer's manual VACUUM must actually reclaim. `analyze` mirrors
506    /// the `VACUUM ANALYZE` spelling.
507    Vacuum {
508        table: Option<String>,
509        analyze: bool,
510    },
511    /// `BEGIN` / `START TRANSACTION` — with an optional explicit
512    /// `ISOLATION LEVEL …` mode (`None` = use the session default). PG
513    /// applies the level for the duration of this transaction only.
514    Begin(TransactionModes),
515    Commit,
516    Rollback,
517    /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
518    /// stack so a later `ROLLBACK TO <name>` can undo just the work
519    /// since this point.
520    Savepoint(String),
521    /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
522    /// named savepoint and discard later savepoints. Does not end the
523    /// transaction.
524    RollbackToSavepoint(String),
525    /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
526    /// rolling back. Keeps the work done since then.
527    ReleaseSavepoint(String),
528    /// `SHOW TABLES` — return the list of tables in the catalog.
529    ShowTables,
530    /// v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES` /
531    /// `SHOW SCHEMAS`. SPG is single-database; the executor
532    /// returns the canonical MySQL set so the mysql / MariaDB
533    /// client populates its database selector.
534    ShowDatabases,
535    /// v7.39.2 — MySQL `USE <db>`.
536    ///
537    /// It parsed as `Empty` and did nothing at all, so `USE myapp;
538    /// SELECT DATABASE()` answered the same constant it answered before
539    /// — measured against MySQL 9.7.2, which answers `myapp`. SPG serves
540    /// ONE database and answers to any name (see `CREATE DATABASE`), so
541    /// this does not switch catalogs; it records the NAME, which is the
542    /// half a client can observe and the half the PostgreSQL wire has
543    /// tracked since v7.39 (`current_database()` names what the startup
544    /// message asked for).
545    UseDatabase(String),
546    /// v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE TABLE <t>`
547    /// returns a 2-column row `(Table, "Create Table")` carrying
548    /// the synthesized DDL. mysqldump emits this for every
549    /// table at scrape time.
550    ShowCreateTable(String),
551    /// v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES FROM <t>`
552    /// (also `SHOW INDEX`, `SHOW KEYS`).
553    ShowIndexes(String),
554    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS`.
555    ShowStatus,
556    /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW VARIABLES`.
557    ShowVariables,
558    /// r1067 — MySQL `SHOW VARIABLES LIKE 'pattern'` (sysbench-tpcc
559    /// probes isolation with it at connect).
560    ShowVariablesLike(String),
561    /// v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
562    ShowProcesslist,
563    /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
564    /// pgbouncer sends `DISCARD ALL` between pooled client sessions to make
565    /// the connection look brand new to the next client; it used to be
566    /// swallowed as dump noise, so nothing was discarded.
567    Discard(DiscardTarget),
568    /// v7.39 (round 318, V51) — MySQL `KILL [CONNECTION | QUERY] <expr>`.
569    /// The id is an expression because MariaDB accepts one
570    /// (`KILL connection_id()` is the documented way to drop your own
571    /// connection). `query_only` is the `QUERY` form: stop the target's
572    /// running statement but leave it connected.
573    Kill {
574        query_only: bool,
575        id: Box<Expr>,
576    },
577    /// `SHOW COLUMNS FROM <table>` — return one row per column with
578    /// its declared name / type / nullability.
579    ShowColumns(String),
580    /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
581    /// Role is optional; defaults to `readonly` when omitted.
582    CreateUser(CreateUserStatement),
583    /// `DROP USER 'name'` (v4.1). v7.39 (read01 round 58) — `IF EXISTS` is
584    /// carried through: PG skips with a NOTICE rather than erroring.
585    DropUser {
586        name: String,
587        if_exists: bool,
588    },
589    /// v7.39 (RLS) — `SET ROLE { name | NONE | DEFAULT }` / `RESET ROLE`.
590    /// `Some(name)` switches the session's effective role (drives
591    /// `current_user` and RLS enforcement); `None` resets to the login
592    /// identity (the Admin superuser).
593    SetRole(Option<String>),
594    /// v7.39 (read01 round 57) — `GRANT <privs> ON <object> TO <roles>`.
595    Grant(GrantStatement),
596    /// v7.39 (read01 round 57) — `REVOKE [GRANT OPTION FOR] <privs> ON
597    /// <object> FROM <roles>`.
598    Revoke(GrantStatement),
599    /// v7.39 (RLS) — `CREATE POLICY name ON table …`.
600    CreatePolicy(CreatePolicyStatement),
601    /// v7.39 (RLS) — `ALTER POLICY name ON table …`.
602    AlterPolicy(AlterPolicyStatement),
603    /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
604    DropPolicy(DropPolicyStatement),
605    /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
606    ShowUsers,
607    /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
608    /// single-column text table describing the rewritten plan tree
609    /// for `inner`. `analyze` triggers an actual exec to attach
610    /// observed row counts and elapsed micros to each node.
611    Explain(ExplainStatement),
612    /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
613    /// Synchronous rebuild of an NSW index. With the optional
614    /// encoding clause, every stored cell at the indexed column is
615    /// also re-encoded through `coerce_value` before the new graph
616    /// builds.
617    AlterIndex(AlterIndexStatement),
618    /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
619    /// The only setting in v6.7.2 is `hot_tier_bytes`, which
620    /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
621    /// for the named table.
622    AlterTable(AlterTableStatement),
623    /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
624    /// The catalog row lives in `spg_publications`. Publisher-side
625    /// WAL filtering arrives in v6.1.5.
626    CreatePublication(CreatePublicationStatement),
627    /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
628    /// no-op when the publication does not exist.
629    DropPublication {
630        name: String,
631        /// v7.39 (round 754, F31-B4) — `IF EXISTS` quietly skips a
632        /// missing publication; the bare form refuses with PG's
633        /// sentence (PG18-measured — the old "silent no-op" note on
634        /// the executor was wrong).
635        if_exists: bool,
636    },
637    /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
638    /// publication ordered by name with `(name, scope_summary,
639    /// table_count)` columns. The scope summary is the human-
640    /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
641    /// TABLES EXCEPT …`; `table_count` is `NULL` for the
642    /// `AllTables` scope and the table-list length otherwise.
643    ShowPublications,
644    /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
645    /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
646    /// in `spg_subscriptions`; when the subscription is
647    /// `enabled = true` (default) the server spawns a
648    /// background worker that connects to `conn` and drains the
649    /// requested publication(s) into the local engine.
650    CreateSubscription(CreateSubscriptionStatement),
651    /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
652    /// PUBLICATION, silent no-op when absent. Stops the
653    /// associated worker thread before removing the row.
654    DropSubscription {
655        name: String,
656        /// v7.39 (round 754, F31-B4) — same contract as
657        /// [`Statement::DropPublication`].
658        if_exists: bool,
659    },
660    /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
661    /// subscription ordered by name with `(name, conn_str,
662    /// publications, enabled, last_received_pos)`.
663    ShowSubscriptions,
664    /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
665    /// Blocks until the local server's apply position reaches
666    /// `<pos>` or `<ms>` elapses. Server-layer command: the
667    /// engine refuses it (`EngineError::Unsupported`) since
668    /// `lag_state` lives in `spg-server`'s `ServerState`.
669    WaitForWalPosition {
670        pos: u64,
671        /// `None` → wait forever; `Some(ms)` → return after `ms`
672        /// milliseconds even if the target isn't reached.
673        timeout_ms: Option<u64>,
674    },
675    /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
676    /// table; `ANALYZE <name>` re-stats just one. Populates
677    /// `spg_statistic` with per-column null_frac + n_distinct +
678    /// 100-bucket equi-depth histogram.
679    Analyze(Option<String>),
680    /// v7.39 (round 535) — `REINDEX { INDEX | TABLE | SCHEMA | DATABASE
681    /// | SYSTEM } [CONCURRENTLY] <name>` and `CLUSTER [VERBOSE]
682    /// [<table> [USING <index>]]`.
683    ///
684    /// SPG has neither index bloat nor a clustering order to rebuild, so
685    /// the work is a no-op — but PG VALIDATES the target, and both were
686    /// swallowed at parse time, so `REINDEX TABLE typo` reported success.
687    /// The name is carried now so the engine can say what PG says.
688    Maintain {
689        kind: MaintainKind,
690        /// `REINDEX … CONCURRENTLY`. Carried for the same reason as
691        /// [`CreateIndexStatement::concurrently`]: PG bars the
692        /// CONCURRENTLY form inside a transaction block and allows the
693        /// plain one.
694        concurrently: bool,
695        /// `None` for the whole-database forms, which name nothing.
696        target: Option<String>,
697    },
698    /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] [ONLY] <name>
699    /// [, ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE |
700    /// RESTRICT]`. Clears every row from each named table. SPG's
701    /// SEQUENCE identity is per-table; RESTART IDENTITY reinitializes
702    /// the associated sequence to its starting value. CASCADE
703    /// currently walks direct FK-referring tables and truncates
704    /// them too (PG's semantics). The ONLY modifier (skip partitions)
705    /// and RESTRICT (default) are accepted with no effect since
706    /// SPG's declarative partitions are always truncated together.
707    Truncate {
708        tables: Vec<String>,
709        restart_identity: bool,
710        cascade: bool,
711        /// v7.39 (round 647) — `TRUNCATE ONLY t`. Absorbed as a no-op
712        /// since v7.14 on the reasoning that SPG's children are separate
713        /// relations a truncate does not descend into. Same reasoning
714        /// round 621 applied to `FROM ONLY`, and it stopped being true
715        /// for the same reason: measured, `TRUNCATE <inheritance parent>`
716        /// leaves the children's rows where PG empties them, and
717        /// `TRUNCATE ONLY <partitioned parent>` is silently accepted
718        /// where PG refuses it outright.
719        only: bool,
720    },
721    /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
722    /// BTree-cold indices and merges small cold-tier segments
723    /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
724    /// 4 MiB) into a single larger segment per (table, index).
725    /// `WHERE` predicate filtering on which tables to compact is
726    /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
727    /// v6.7.3 only supports the bare form.
728    CompactColdSegments,
729    /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
730    /// parameter on the engine; v7.12.1 honours
731    /// `default_text_search_config` (consumed by `to_tsvector` /
732    /// `plainto_tsquery` family when called without an explicit
733    /// config arg). All other names are accepted as a no-op so PG
734    /// dumps with `SET client_encoding`, `SET search_path` etc.
735    /// load cleanly.
736    SetParameter {
737        name: String,
738        value: SetValue,
739        /// v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to the
740        /// current transaction; the engine saves the prior value and
741        /// restores it at COMMIT / ROLLBACK. Plain `SET` (and `SET
742        /// SESSION`) leave this false and persist for the session.
743        local: bool,
744    },
745    /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
746    /// multi-assignment (mysqldump preamble uses
747    /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
748    /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
749    /// source order. Pairs whose LHS is a MySQL session/user
750    /// variable (`@VAR` / `@@VAR`) are recorded with the raw
751    /// name so the engine can ignore them; pairs whose LHS is
752    /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
753    /// go through the regular `set_session_param` path.
754    SetParameterList(Vec<(String, SetValue)>),
755    /// v7.39 (round 430) — MySQL's USER-defined variables:
756    /// `SET @x = 5, @s := CONCAT('a','b')`. Distinct from
757    /// [`Self::SetParameter`] (a `@@`-style engine/session setting) in
758    /// every way that matters: the value is an arbitrary EXPRESSION, the
759    /// name lives in its own per-session namespace, and reading an unset
760    /// one answers NULL rather than raising. `:=` and `=` are the same
761    /// assignment here.
762    ///
763    /// Before this the parser stripped every `@`, so `@x` and `@@x` were
764    /// the same node: `SET @x = 5` silently landed in the session-parameter
765    /// store where nothing could read it back, and `SELECT @x` failed with
766    /// "Unknown system variable".
767    /// v7.39 (round 554) — `SET @a = …, SETTING = …`.
768    ///
769    /// `settings` is the trailing half a mysqldump preamble writes:
770    /// `SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'`
771    /// saves a value and changes it in one statement. The parser used
772    /// to refuse the mixture outright, so no mysqldump could be
773    /// restored past its preamble.
774    SetUserVars(Vec<(String, Expr)>, Vec<(String, Expr)>),
775    /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
776    /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
777    /// silently accepted). PG-standard surface for picking an
778    /// isolation level. Engine tracks the value on
779    /// `Engine::current_isolation_level()`; actual MVCC / SSI
780    /// semantics implementation lands separately. PG itself maps
781    /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
782    /// effectively every level reads as READ COMMITTED in v7.37.8.
783    SetTransaction {
784        modes: TransactionModes,
785    },
786    /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
787    /// with the parameter's current value as TEXT. Today the only
788    /// recognised param is `transaction_isolation`; further
789    /// surfaces (`search_path`, `application_name`, …) land as the
790    /// session-parameter inventory grows.
791    ShowParameter(String),
792    /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
793    /// to its default. No-op for parameters SPG does not track.
794    ResetParameter(Option<String>),
795    /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
796    /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
797    /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
798    /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
799    /// languages parse but error at exec time with a clear
800    /// unsupported message.
801    CreateFunction(CreateFunctionStatement),
802    /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
803    /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
804    /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
805    /// triggers and column-list / WHEN clauses are out of scope
806    /// for v7.12.4.
807    CreateTrigger(CreateTriggerStatement),
808    /// v7.39 (round 139) — `CREATE RULE name AS ON event TO table [WHERE cond]
809    /// DO [ALSO|INSTEAD] { NOTHING | command }` query-rewrite rule.
810    CreateRule(CreateRuleStatement),
811    /// v7.39 (round 139) — `DROP RULE [IF EXISTS] name ON table`.
812    DropRule {
813        name: String,
814        table: String,
815        if_exists: bool,
816    },
817    /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
818    /// no-op when missing if `IF EXISTS` is set.
819    DropTrigger {
820        name: String,
821        table: String,
822        if_exists: bool,
823    },
824    /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
825    /// DROP TRIGGER but global (no table scope).
826    DropFunction {
827        name: String,
828        /// v7.39 (read01 round 62) — the argument TYPES, when the statement gave
829        /// them: `DROP FUNCTION f(int)` drops that overload only. `None` = no
830        /// argument list, which PG accepts only when the name is unambiguous.
831        args: Option<Vec<String>>,
832        if_exists: bool,
833    },
834    /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
835    /// [AS data_type]
836    /// [INCREMENT [BY] n]
837    /// [MINVALUE n | NO MINVALUE]
838    /// [MAXVALUE n | NO MAXVALUE]
839    /// [START [WITH] n]
840    /// [CACHE n]
841    /// [[NO] CYCLE]
842    /// [OWNED BY {table.col | NONE}]`.
843    /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
844    /// emits + nextval/currval/setval downstream all work.
845    CreateSequence(CreateSequenceStatement),
846    /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
847    /// the same option grammar as CREATE SEQUENCE, plus
848    /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
849    AlterSequence(AlterSequenceStatement),
850    /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
851    /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
852    /// silently (no FK on sequences).
853    DropSequence {
854        names: Vec<String>,
855        if_exists: bool,
856    },
857    /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
858    /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
859    /// silent-no-op VIEW story from the v7.17 customer-readiness
860    /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
861    /// so any downstream `SELECT FROM v` errored with table-not-
862    /// found. The view body is stored verbatim; SELECT FROM <v>
863    /// rewrites at exec-time by prepending the view body as a
864    /// synthetic CTE.
865    CreateView(CreateViewStatement),
866    /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
867    /// [CASCADE | RESTRICT]`. Removes the matching view from the
868    /// catalog; CASCADE/RESTRICT parsed silently.
869    DropView {
870        names: Vec<String>,
871        if_exists: bool,
872    },
873    /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
874    /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
875    /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
876    /// model: the materialised result lives as a regular table
877    /// with the matching name + a parallel
878    /// `materialized_views` registry mapping name → body source
879    /// (used by REFRESH).
880    CreateMaterializedView(CreateMaterializedViewStatement),
881    /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
882    /// [NO] DATA]`. Re-runs the stored body and replaces the
883    /// cached rows. `WITH NO DATA` truncates without re-running.
884    RefreshMaterializedView {
885        name: String,
886        with_data: bool,
887    },
888    /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
889    /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
890    /// backing table and the source registry entry.
891    DropMaterializedView {
892        names: Vec<String>,
893        if_exists: bool,
894    },
895    /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
896    /// …)`. Closes the silent-no-op CREATE TYPE story so PG
897    /// dumps that declare enum types load with real constraints
898    /// instead of becoming free-form TEXT. Future kinds
899    /// (composite / range / domain) extend the inner `kind`
900    /// enum.
901    CreateType(CreateTypeStatement),
902    /// v7.37 D.55 — `ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
903    /// [{BEFORE | AFTER} 'existing']`. Extends an enum's label list so
904    /// enum evolution stops being a silent no-op. `position` is
905    /// `Some((is_before, anchor))`.
906    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
907    /// Used to be swallowed by the ALTER TYPE no-op tail, so the rename was
908    /// accepted and silently ignored.
909    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
910    /// Used to be swallowed as dump noise, so a comment was accepted and lost
911    /// (and obj_description / col_description always returned NULL).
912    /// `kind` is lowercase ("table" / "column" / "index" / …); for a column
913    /// `name` is the dotted `table.column`. `comment: None` = `IS NULL` = remove.
914    CommentOn {
915        kind: String,
916        name: String,
917        comment: Option<String>,
918    },
919    AlterTypeRenameValue {
920        type_name: String,
921        old: String,
922        new: String,
923    },
924    AlterTypeAddValue {
925        type_name: String,
926        label: String,
927        if_not_exists: bool,
928        position: Option<(bool, String)>,
929    },
930    /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
931    /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
932    /// from the catalog.
933    DropType {
934        names: Vec<String>,
935        if_exists: bool,
936    },
937    /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
938    /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
939    /// A DOMAIN is a named CHECK-constrained alias over a built-
940    /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
941    /// every column declared with the domain. Closes the
942    /// silent-no-op CREATE DOMAIN story so PG dumps that ship
943    /// validated identifier types (email, positive_int, …) keep
944    /// their guarantees.
945    CreateDomain(CreateDomainStatement),
946    /// v7.39 (round 260) — `ALTER DOMAIN name <action>`. Every form was
947    /// previously swallowed by the catch-all DDL arm: the statement
948    /// reported success and did nothing, so a migration that dropped a
949    /// constraint kept rejecting the data it had just been told to
950    /// accept.
951    AlterDomain {
952        name: String,
953        action: AlterDomainAction,
954    },
955    /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
956    /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
957    /// domain from the catalog.
958    DropDomain {
959        names: Vec<String>,
960        if_exists: bool,
961    },
962    /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
963    /// name [AUTHORIZATION user]`. SPG is single-database;
964    /// schemas are tracked as a namespace registry so pg_dump
965    /// multi-schema declarations land cleanly and `SELECT *
966    /// FROM information_schema.schemata` returns real entries.
967    /// Schema-qualified `schema.table` references still strip
968    /// the prefix at lookup time per PG (schemas are not
969    /// isolation boundaries in v7.17 — see project-next-docket
970    /// for the v7.18+ isolation tracking).
971    CreateSchema {
972        name: String,
973        if_not_exists: bool,
974    },
975    /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
976    /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
977    /// from the registry; built-in `public` / `pg_catalog` /
978    /// `information_schema` cannot be dropped.
979    DropSchema {
980        names: Vec<String>,
981        if_exists: bool,
982    },
983}
984
985/// v7.39 (round 260) — the `ALTER DOMAIN` actions SPG implements.
986#[derive(Debug, Clone, PartialEq)]
987pub enum AlterDomainAction {
988    AddConstraint { name: Option<String>, check: Expr },
989    DropConstraint { name: String, if_exists: bool },
990    SetDefault(Expr),
991    DropDefault,
992    SetNotNull,
993    DropNotNull,
994    RenameTo(String),
995}
996
997/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
998#[derive(Debug, Clone, PartialEq)]
999pub struct CreateDomainStatement {
1000    pub name: String,
1001    /// Base type for the domain (one of the built-in
1002    /// `ColumnTypeName` variants).
1003    pub base_type: ColumnTypeName,
1004    /// v7.39 (round 259) — `CREATE DOMAIN child AS parent …` where
1005    /// `parent` is itself a DOMAIN. The parser already captured the
1006    /// unknown type name; it just was not carried here, so the parent's
1007    /// CHECK constraints were invisible and a value violating them was
1008    /// silently accepted. `base_type` still holds the ultimate scalar
1009    /// type, which is what the storage tier stores.
1010    pub base_domain: Option<String>,
1011    /// Optional `DEFAULT <expr>`. Resolved at engine-side
1012    /// CREATE TABLE time when a column is bound to this domain.
1013    pub default: Option<Expr>,
1014    /// `NOT NULL` from the domain definition. Engine ORs this
1015    /// with the column-level nullability so the strictest of the
1016    /// two wins (i.e. the column is non-nullable if either side
1017    /// says so).
1018    pub not_null: bool,
1019    /// Zero-or-more `CHECK (expr)` predicates. Each one is
1020    /// enforced as part of the column's CHECK list at INSERT /
1021    /// UPDATE time, with `VALUE` substituted for the column's
1022    /// current cell value.
1023    pub checks: Vec<Expr>,
1024}
1025
1026/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
1027#[derive(Debug, Clone, PartialEq, Eq)]
1028pub struct CreateTypeStatement {
1029    pub name: String,
1030    pub kind: TypeKind,
1031}
1032
1033/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
1034/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
1035/// and later (COMPOSITE, RANGE) can land without an AST shape
1036/// migration.
1037///
1038/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
1039/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
1040/// stores the field list in the catalog so PG dumps that emit
1041/// `CREATE TYPE … AS (…)` don't error out; using a composite type
1042/// as a column type lands in Phase 2 (Value::Composite encoding +
1043/// ROW() literal + field-access syntax).
1044#[derive(Debug, Clone, PartialEq, Eq)]
1045pub enum TypeKind {
1046    /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
1047    /// labels are ordered).
1048    Enum { labels: Vec<String> },
1049    /// `AS (field_name field_type, …)`. Order matters; PG
1050    /// composite literals are positional.
1051    Composite {
1052        fields: Vec<(String, ColumnTypeName)>,
1053        /// v7.39 (round 264) — parallel to `fields`: the raw type NAME
1054        /// when a field's type is not a builtin (i.e. another composite).
1055        /// The parser already captures it; without carrying it here a
1056        /// nested composite field resolved to the Text placeholder and
1057        /// the inner record never became a record.
1058        field_user_types: Vec<Option<String>>,
1059    },
1060}
1061
1062/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
1063/// a string literal, an identifier (often a config name), an
1064/// integer/float, or the bare `DEFAULT` keyword.
1065#[derive(Debug, Clone, PartialEq)]
1066pub enum SetValue {
1067    String(String),
1068    Ident(String),
1069    Number(String),
1070    Default,
1071}
1072
1073/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
1074/// at parse time and tracks the selected value on the engine. The
1075/// actual semantic differentiation (REPEATABLE READ snapshot,
1076/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
1077/// today every level reads as effective READ COMMITTED (which is
1078/// also how PG treats READ UNCOMMITTED — it silently upgrades to
1079/// READ COMMITTED). Default = `ReadCommitted`.
1080#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1081pub enum IsolationLevel {
1082    ReadUncommitted,
1083    #[default]
1084    ReadCommitted,
1085    RepeatableRead,
1086    Serializable,
1087}
1088
1089impl IsolationLevel {
1090    /// Canonical PG-style display name, as `SHOW transaction_isolation`
1091    /// would return it. v7.39 (round 770, F31 tranche 6 #154) — PG
1092    /// KEEPS the "read uncommitted" label (measured: `BEGIN ISOLATION
1093    /// LEVEL READ UNCOMMITTED; SHOW transaction_isolation` answers
1094    /// `read uncommitted`) and only BEHAVES as read committed; the old
1095    /// fold renamed the label too.
1096    /// v7.39 — the MySQL display name, which is NOT the PG one: MySQL
1097    /// hyphenates and upper-cases. Measured on MySQL 9.7.2 by setting
1098    /// each level and reading `@@transaction_isolation` back:
1099    /// `READ-UNCOMMITTED` / `READ-COMMITTED` / `REPEATABLE-READ` /
1100    /// `SERIALIZABLE` (the last has no hyphen because it is one word).
1101    ///
1102    /// This exists so the two MySQL surfaces cannot drift: both
1103    /// `SHOW VARIABLES` and `@@transaction_isolation` used to carry
1104    /// their own hard-coded literal, and the literals disagreed —
1105    /// one said `REPEATABLE-READ` while the engine ran read committed.
1106    /// v7.39 — parse what `default_transaction_isolation` holds. PG
1107    /// accepts the SQL spellings and stores them lower-cased with a
1108    /// space; anything else is not a level this understands and the
1109    /// caller keeps its own default rather than guessing.
1110    #[must_use]
1111    pub fn from_pg_name(name: &str) -> Option<Self> {
1112        match name.trim().to_ascii_lowercase().as_str() {
1113            "read uncommitted" => Some(Self::ReadUncommitted),
1114            "read committed" => Some(Self::ReadCommitted),
1115            "repeatable read" => Some(Self::RepeatableRead),
1116            "serializable" => Some(Self::Serializable),
1117            _ => None,
1118        }
1119    }
1120
1121    #[must_use]
1122    pub fn as_mysql_str(self) -> &'static str {
1123        match self {
1124            Self::ReadUncommitted => "READ-UNCOMMITTED",
1125            Self::ReadCommitted => "READ-COMMITTED",
1126            Self::RepeatableRead => "REPEATABLE-READ",
1127            Self::Serializable => "SERIALIZABLE",
1128        }
1129    }
1130
1131    pub fn as_pg_str(self) -> &'static str {
1132        match self {
1133            Self::ReadUncommitted => "read uncommitted",
1134            Self::ReadCommitted => "read committed",
1135            Self::RepeatableRead => "repeatable read",
1136            Self::Serializable => "serializable",
1137        }
1138    }
1139}
1140
1141impl core::fmt::Display for IsolationLevel {
1142    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1143        f.write_str(self.as_pg_str())
1144    }
1145}
1146
1147/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
1148/// single fixed-shape DDL; the WITH-clause options PG supports
1149/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
1150/// scope for v6.1.4 — `enabled` defaults to true and there are
1151/// no other knobs to set in v6.1.x.
1152#[derive(Debug, Clone, PartialEq, Eq)]
1153pub struct CreateSubscriptionStatement {
1154    pub name: String,
1155    /// Connection string in PG keyword=value form (e.g.
1156    /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
1157    /// `host` and `port` fields; the rest is reserved for
1158    /// future v6.1.x options.
1159    pub conn_str: String,
1160    /// One or more publications on the remote side. Order is
1161    /// preserved verbatim from the DDL; the worker requests them
1162    /// in this order. v6.1.4 records the list; v6.1.5
1163    /// publisher-side filtering enforces it.
1164    pub publications: Vec<String>,
1165}
1166
1167/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
1168#[derive(Debug, Clone, PartialEq, Eq)]
1169pub struct CreateSequenceStatement {
1170    pub name: String,
1171    pub if_not_exists: bool,
1172    pub temporary: bool,
1173    /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
1174    pub data_type: Option<SequenceDataType>,
1175    pub options: SequenceOptions,
1176}
1177
1178/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
1179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1180pub enum SequenceDataType {
1181    SmallInt,
1182    Int,
1183    BigInt,
1184}
1185
1186/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
1187/// All fields are optional. `min_value`/`max_value` carry
1188/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
1189#[derive(Debug, Clone, Default, PartialEq, Eq)]
1190pub struct SequenceOptions {
1191    pub increment: Option<i64>,
1192    pub min_value: Option<SeqBound>,
1193    pub max_value: Option<SeqBound>,
1194    pub start: Option<i64>,
1195    /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
1196    /// RESTART, `Some(Some(n))` = RESTART WITH n.
1197    pub restart: Option<Option<i64>>,
1198    pub cache: Option<i64>,
1199    pub cycle: Option<bool>,
1200    pub owned_by: Option<SequenceOwnedBy>,
1201}
1202
1203/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
1204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1205pub enum SeqBound {
1206    Value(i64),
1207    NoBound,
1208}
1209
1210/// v7.17.0 — `OWNED BY {table.col | NONE}`.
1211#[derive(Debug, Clone, PartialEq, Eq)]
1212pub enum SequenceOwnedBy {
1213    None,
1214    Column { table: String, column: String },
1215}
1216
1217/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
1218#[derive(Debug, Clone, PartialEq)]
1219pub struct CreateMaterializedViewStatement {
1220    pub name: String,
1221    pub if_not_exists: bool,
1222    /// Optional `(col, col, …)` rename list. Applies to the
1223    /// backing table at CREATE / REFRESH time.
1224    pub columns: Vec<String>,
1225    /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
1226    /// the cached rows.
1227    pub body: SelectStatement,
1228    /// `WITH DATA` (default) = materialise the rows at CREATE
1229    /// time. `WITH NO DATA` = create an empty backing table;
1230    /// callers must REFRESH before SELECT returns rows.
1231    pub with_data: bool,
1232    /// v7.38 (read01 P6.49) — when true this node came from
1233    /// `CREATE TABLE … AS <select>` (CTAS) / `SELECT … INTO`, so the
1234    /// executor creates a plain table and does NOT register it in the
1235    /// materialized-view registry (no REFRESH semantics).
1236    pub as_plain_table: bool,
1237    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE … AS <select>`. Only
1238    /// meaningful together with `as_plain_table`; the executor puts the
1239    /// resulting table in the creating session's namespace.
1240    pub temporary: bool,
1241}
1242
1243/// v7.39 (read01 round 132) — `WITH [LOCAL | CASCADED] CHECK OPTION` on an
1244/// auto-updatable view. `Cascaded` is PG's default when the bare
1245/// `WITH CHECK OPTION` is written.
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247pub enum ViewCheckOption {
1248    Local,
1249    Cascaded,
1250}
1251
1252/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
1253#[derive(Debug, Clone, PartialEq)]
1254pub struct CreateViewStatement {
1255    pub name: String,
1256    pub or_replace: bool,
1257    pub if_not_exists: bool,
1258    pub temporary: bool,
1259    /// Optional `(col, col, …)` rename list. When non-empty,
1260    /// these override the body's projected column names per-
1261    /// position at SELECT-from-view time.
1262    pub columns: Vec<String>,
1263    /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
1264    /// time to materialise the view as a synthetic CTE.
1265    pub body: SelectStatement,
1266    /// v7.39 (round 132) — `WITH CHECK OPTION`. When set, a write through this
1267    /// view whose resulting row fails the view's WHERE is rejected (SQLSTATE
1268    /// 44000). `None` = no check option.
1269    pub check_option: Option<ViewCheckOption>,
1270}
1271
1272/// v7.17.0 — `ALTER SEQUENCE` AST node.
1273#[derive(Debug, Clone, PartialEq, Eq)]
1274pub struct AlterSequenceStatement {
1275    pub name: String,
1276    pub if_exists: bool,
1277    pub options: SequenceOptions,
1278    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`. Set
1279    /// instead of `options`; the two forms are mutually exclusive in PG.
1280    pub rename_to: Option<String>,
1281}
1282
1283/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
1284/// the [`PublicationScope`] shape. v6.1.2 only accepted
1285/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
1286/// variants by flipping the parser gate (no AST migration).
1287#[derive(Debug, Clone, PartialEq, Eq)]
1288pub struct CreatePublicationStatement {
1289    pub name: String,
1290    pub scope: PublicationScope,
1291}
1292
1293/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
1294/// flips the parser gate for the `ForTables` / `AllTablesExcept`
1295/// variants — the on-disk shape, snapshot serialisation, and the
1296/// AST round-trip Display path were already in place in v6.1.2
1297/// so this is a parser-only widening.
1298#[derive(Debug, Clone, PartialEq, Eq)]
1299pub enum PublicationScope {
1300    AllTables,
1301    ForTables(Vec<String>),
1302    AllTablesExcept(Vec<String>),
1303    /// v7.39 (round 754, F31-B5) — `FOR TABLES IN SCHEMA <name>`
1304    /// (PG 15+). AST-only: the executor folds `public` to
1305    /// [`PublicationScope::AllTables`] (SPG's single-schema world)
1306    /// and refuses any other schema with PG's sentence, so the
1307    /// catalog / serializer / replication filter never see it.
1308    TablesInSchema(String),
1309}
1310
1311#[derive(Debug, Clone, PartialEq, Eq)]
1312pub struct AlterIndexStatement {
1313    pub name: String,
1314    pub target: AlterIndexTarget,
1315}
1316
1317#[derive(Debug, Clone, PartialEq, Eq)]
1318pub enum AlterIndexTarget {
1319    /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
1320    /// rebuilds the existing graph in place without touching the
1321    /// column encoding; `Some(enc)` re-encodes every cell first.
1322    Rebuild { encoding: Option<VecEncoding> },
1323    /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
1324    /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
1325    /// uses it to make the migration idempotent (re-running on a
1326    /// DB where the rename already happened is a no-op rather
1327    /// than an error).
1328    Rename { new: String, if_exists: bool },
1329    /// v7.39 (round 710) — `SET ( option = value, … )` / `RESET ( … )`.
1330    /// Was a SYNTAX ERROR; PG resolves the INDEX first (`relation "x"
1331    /// does not exist`), so the index is validated and the storage
1332    /// parameters no-op (SPG engine-manages them, as ALTER TABLE's
1333    /// SET/RESET arms already record).
1334    StorageParams,
1335}
1336
1337/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
1338/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
1339/// can add more SET subjects without changing the dispatch shape.
1340#[derive(Debug, Clone, PartialEq)]
1341pub struct AlterTableStatement {
1342    pub name: String,
1343    /// v7.13.2 — mailrs round-6 S1. One or more subactions
1344    /// separated by commas in the source SQL. PG-semantic apply
1345    /// is sequential; engine bails on first error (no
1346    /// transactional rollback of completed subactions in v7.13).
1347    /// Single-subaction shape stays a 1-element vec.
1348    pub targets: Vec<AlterTableTarget>,
1349}
1350
1351#[derive(Debug, Clone, PartialEq)]
1352#[allow(clippy::large_enum_variant)]
1353pub enum AlterTableTarget {
1354    /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
1355    ///
1356    /// Both were accepted-and-ignored since v7.37.18, on the reasoning
1357    /// that SPG has no PG-style inheritance. Round 645 gave it one, and
1358    /// the reasoning went stale: `NO INHERIT` reported success while the
1359    /// child stayed attached, which is the worst kind of answer — the
1360    /// statement says it worked and the catalog disagrees.
1361    Inherit { parent: String, detach: bool },
1362    /// Per-table hot-tier byte budget override. The freezer
1363    /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
1364    SetHotTierBytes(u64),
1365    /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
1366    /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
1367    /// Engine validates existing rows against the new constraint
1368    /// before installing it.
1369    AddForeignKey(ForeignKeyConstraint),
1370    /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
1371    /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
1372    /// no-op when no FK with that name exists; otherwise raises.
1373    DropForeignKey { name: String, if_exists: bool },
1374    /// v7.39 (round 431) — MySQL's `ALTER TABLE t DROP {INDEX|KEY} name`,
1375    /// the counterpart of `ADD INDEX`. Lowers to the same catalog action
1376    /// as the standalone `DROP INDEX` statement.
1377    DropIndex { name: String, if_exists: bool },
1378    /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
1379    /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
1380    /// (20 migrate-*.sql hits). Engine appends the column to the
1381    /// schema and back-fills every existing row with the DEFAULT
1382    /// (or NULL when no DEFAULT and the column is nullable).
1383    AddColumn {
1384        column: ColumnDef,
1385        if_not_exists: bool,
1386    },
1387    /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
1388    /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
1389    /// existing row's column value by evaluating the optional
1390    /// USING expression (default `col::<ty>`) and re-coercing
1391    /// against the new column type.
1392    AlterColumnType {
1393        column: String,
1394        new_type: ColumnTypeName,
1395        using: Option<Expr>,
1396        /// v7.39 (round 713) — `COLLATE <name>` between the type and
1397        /// USING. PG re-collates the column, and an ABSENT clause RESETS
1398        /// the collation to the type default (measured round 713) — so
1399        /// `None` is not "leave it alone". The type parser consumed the
1400        /// clause all along and this surface dropped it on the floor:
1401        /// the statement succeeded and the ordering did not change, the
1402        /// silent-divergence shape. Folded variant + the name as written.
1403        collation: Option<(Collation, String)>,
1404    },
1405    /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
1406    /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
1407    /// every row's value at that position is removed; any index
1408    /// on the column is dropped. `if_exists` makes the drop a
1409    /// no-op when the column is missing. `cascade` removes
1410    /// dependents (FKs referencing the column, partial indexes
1411    /// whose predicate names the column); without it, the engine
1412    /// rejects when dependents exist.
1413    DropColumn {
1414        column: String,
1415        if_exists: bool,
1416        cascade: bool,
1417    },
1418    /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
1419    /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
1420    /// CONSTRAINT name CHECK (expr)` — table-level constraints
1421    /// installed post-CREATE-TABLE. pg_dump emits PKs as a
1422    /// separate ALTER TABLE statement, so this surface lets the
1423    /// dump load straight through.
1424    AddTableConstraint(TableConstraint),
1425    /// v7.39 (round 652) — `OWNER TO <role>`. SPG is single-owner, so
1426    /// there is nothing to record; what PG does that SPG did not is
1427    /// REFUSE a role that does not exist. The name has to reach the
1428    /// engine for that, because only the engine knows the roles.
1429    OwnerTo { role: String },
1430    /// v7.39 (round 652) — `CLUSTER ON <index>` and `SET WITHOUT
1431    /// CLUSTER` (the latter as `None`). SPG has no clustered storage, so
1432    /// the hint is still a no-op; naming an index that does not exist is
1433    /// not.
1434    ClusterOn { index: Option<String> },
1435    /// v7.39 (round 652) — `VALIDATE CONSTRAINT <name>`: scan the rows
1436    /// already in the table against a constraint added `NOT VALID` and,
1437    /// if they all pass, mark it validated. It used to be swallowed as a
1438    /// no-op on the theory that SPG validated at ADD time; SPG did not.
1439    ValidateConstraint { name: String },
1440    /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
1441    /// Renames the column in the schema and propagates the rename
1442    /// to every stored source string that references it as a
1443    /// (potentially-qualified) column identifier: CHECK predicates,
1444    /// partial-index predicates, runtime DEFAULT expressions, and
1445    /// triggers' `UPDATE OF` column lists. Function bodies and
1446    /// trigger bodies are NOT auto-rewritten — they're loose
1447    /// source text and may contain references SPG can't statically
1448    /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
1449    /// the column even if dependents exist; users renaming a
1450    /// column referenced by a function body update the function
1451    /// body separately.
1452    RenameColumn { old: String, new: String },
1453    /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
1454    /// Reachable now that the schema stores user-supplied constraint names.
1455    RenameConstraint { old: String, new: String },
1456    /// v7.22 (round-13 T2) — mark a column auto-incrementing.
1457    /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
1458    /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
1459    /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
1460    /// (identity); both lower to this. SPG's auto-increment is
1461    /// max+1-scan based, so the dump's `setval(…)` calls stay
1462    /// no-ops without losing the sequence position.
1463    SetColumnAutoIncrement {
1464        column: String,
1465        /// The implicit sequence pg_dump names for an identity
1466        /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
1467        /// nextval target for a serial default. The engine creates
1468        /// it if absent so the dump's later `setval(s, …)` lands.
1469        seq_name: Option<String>,
1470    },
1471    /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
1472    /// table itself (mailrs round-10 A.5 carve-out — mailrs's
1473    /// migrate-042 uses it). The engine moves the table entry
1474    /// in the catalog under the new name; child catalog state
1475    /// (FKs pointing at this table, triggers watching this
1476    /// table) tracks the rename through the storage layer.
1477    RenameTable { new: String },
1478    /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
1479    /// { ALL | <name> }`. Toggles whether row-level triggers
1480    /// fire on subsequent INSERT/UPDATE/DELETE on the table.
1481    /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
1482    /// ENABLE epilogue around every table's data block so the
1483    /// rows already-computed in prod don't get re-rewritten
1484    /// (and so trigger-driven side effects like
1485    /// audit/queueing don't re-fire during a bulk reload).
1486    /// `which == TriggerSelector::All` toggles every trigger
1487    /// on the table; `Named(name)` toggles one trigger. The
1488    /// engine persists the disabled state on `TriggerDef.enabled`
1489    /// (catalog FILE_VERSION 25+) and the row-write paths skip
1490    /// the trigger when `!enabled`.
1491    SetTriggerEnabled {
1492        which: TriggerSelector,
1493        enabled: bool,
1494    },
1495    /// v7.39 (RLS) — `ALTER TABLE t { ENABLE | DISABLE | FORCE | NO FORCE }
1496    /// ROW LEVEL SECURITY`. `enabled` = Some for ENABLE/DISABLE (sets
1497    /// `relrowsecurity`); `force` = Some for FORCE/NO FORCE (sets
1498    /// `relforcerowsecurity`). Exactly one is `Some` per statement.
1499    SetRowSecurity {
1500        enabled: Option<bool>,
1501        force: Option<bool>,
1502    },
1503    /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child
1504    /// <bounds>`. Promotes an existing table `child` to a partition
1505    /// of `parent` using PG-style `FOR VALUES …` / `DEFAULT` bounds.
1506    /// Engine validates that `child`'s columns are layout-compatible
1507    /// with `parent` and that every row in `child` satisfies the
1508    /// bound before installing the role.
1509    AttachPartition {
1510        child: String,
1511        bounds: PartitionOfBoundsAst,
1512    },
1513    /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
1514    /// child [CONCURRENTLY] [FINALIZE]`. Demotes a partition back
1515    /// to a standalone table (clears `partition_role`) and removes
1516    /// it from the parent's child set. v7.37.16.5: `CONCURRENTLY`
1517    /// is parser-accepted; engine performs the same atomic detach
1518    /// (single-engine, no replication lag — the PG semantics that
1519    /// require the two-phase split don't apply).
1520    DetachPartition {
1521        child: String,
1522        concurrently: bool,
1523        finalize: bool,
1524    },
1525    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col SET DEFAULT
1526    /// <expr>`. Engine re-parses + freezes the literal at this point,
1527    /// matching CREATE TABLE-side default semantics. Volatile shapes
1528    /// (`now()` / `nextval`) take the runtime-default path.
1529    AlterColumnSetDefault { column: String, default_expr: Expr },
1530    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col DROP DEFAULT`.
1531    AlterColumnDropDefault { column: String },
1532    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col SET NOT NULL`.
1533    /// Engine validates that no existing row has NULL in that column
1534    /// before flipping the flag (PG semantics — partial NOT NULL
1535    /// would surface inconsistently).
1536    AlterColumnSetNotNull { column: String },
1537    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col DROP NOT NULL`.
1538    AlterColumnDropNotNull { column: String },
1539    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN col RESTART
1540    /// [WITH n]` on an identity column (`None` = bare RESTART, from the
1541    /// column's start value = 1). Engine records a next-value floor over
1542    /// SPG's max+1 identity allocation.
1543    AlterColumnRestart { column: String, with: Option<i64> },
1544    /// v7.38 (read01 U10) — `ALTER TABLE … ALTER COLUMN col DROP
1545    /// EXPRESSION` turns a stored generated column into a plain column
1546    /// (its generation expression is removed; existing values are kept).
1547    AlterColumnDropExpression { column: String, if_exists: bool },
1548    /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
1549    /// de-generate an identity column into a plain column.
1550    AlterColumnDropIdentity { column: String, if_exists: bool },
1551    /// v7.38 (read01 U12) — `ALTER TABLE … ALTER COLUMN col SET
1552    /// EXPRESSION AS (expr)` (PG 17) changes a stored generated column's
1553    /// expression and recomputes every existing row.
1554    AlterColumnSetExpression { column: String, expr: Expr },
1555    /// v7.39 (round 710) — `OF <type>` / the type half of the typed-table
1556    /// binding. The BINDING stays a no-op (recorded); the TYPE must exist
1557    /// (PG: `type "x" does not exist`).
1558    OfType { type_name: String },
1559    /// v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`. The
1560    /// identity setting no-ops (SPG has no logical replication consumer);
1561    /// the INDEX must exist on this table (PG: `index "i" for table "t"
1562    /// does not exist`).
1563    ReplicaIdentityUsingIndex { index: String },
1564}
1565
1566/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
1567/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
1568/// modifiers; v7.16.1 ships the two shapes pg_dump actually
1569/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
1570/// shouldn't surface from a dump.
1571#[derive(Debug, Clone, PartialEq, Eq)]
1572pub enum TriggerSelector {
1573    /// Every trigger on the table.
1574    All,
1575    /// A specific trigger by name.
1576    Named(String),
1577}
1578
1579/// Each bool mirrors one independent PG `EXPLAIN (…)` option (ANALYZE,
1580/// SUGGEST, COSTS OFF, BUFFERS, TIMING OFF, …); they compose freely, so a
1581/// bitflags word or a nested options struct would only relocate the lint
1582/// while making the option each caller sets harder to read.
1583#[allow(clippy::struct_excessive_bools)]
1584#[derive(Debug, Clone, PartialEq)]
1585pub struct ExplainStatement {
1586    pub analyze: bool,
1587    /// v7.39 (round 225) — widened from SelectStatement so EXPLAIN
1588    /// INSERT/UPDATE/DELETE parses (PG explains DML); the engine renders
1589    /// `Insert on / Update on / Delete on` trees for them.
1590    pub inner: Box<Statement>,
1591    /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
1592    /// advisor pass: after the regular plan tree, the engine
1593    /// emits one suggestion line per column referenced in the
1594    /// query's WHERE / JOIN that has no covering index on the
1595    /// owning table.
1596    pub suggest: bool,
1597    /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
1598    /// `elapsed=…us` annotations from the Total line (and any
1599    /// future cost-bearing lines). PG-standard option used by
1600    /// regression suites and diff-friendly EXPLAIN output. When
1601    /// `true`, takes precedence over the per-session
1602    /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
1603    pub costs_off: bool,
1604    /// v7.37.22 (22.7) — `EXPLAIN (BUFFERS) <SELECT>`. PG-standard
1605    /// option that surfaces hot/cold/shared block counters. SPG's
1606    /// hot-tier scan path counts examined rows; the BUFFERS option
1607    /// makes that an explicit per-operator annotation.
1608    pub buffers: bool,
1609    /// v7.37.22 (22.7) — `EXPLAIN (TIMING [ON|OFF]) <SELECT>`. PG
1610    /// uses this to disable per-operator timing while still
1611    /// emitting actual-row counts (cheaper than ANALYZE). Default
1612    /// when EXPLAIN ANALYZE is set: TIMING ON. `false` strips the
1613    /// timing portion of the Total line. Decoupled from `costs_off`:
1614    /// PG's COSTS OFF strips estimated cost; TIMING OFF strips
1615    /// measured wall-clock.
1616    pub timing_off: bool,
1617    /// v7.37.22 (22.7) — `EXPLAIN (SETTINGS) <SELECT>`. PG appends
1618    /// modified GUC values to the plan output. SPG emits the
1619    /// session params that diverge from default after the main
1620    /// plan body.
1621    pub settings: bool,
1622    /// v7.37.22 (22.7) — `EXPLAIN (WAL) <SELECT>`. PG counts WAL
1623    /// bytes / records / FPI emitted by the query. SPG's
1624    /// write-side queries (INSERT/UPDATE/DELETE wrapped in EXPLAIN
1625    /// ANALYZE) report against the engine WAL counter delta.
1626    pub wal: bool,
1627    /// v7.39 (round 227) — `EXPLAIN (SUMMARY OFF)` suppresses the trailing
1628    /// `Planning Time:` / `Execution Time:` lines. PG defaults SUMMARY on
1629    /// for ANALYZE and off otherwise; SPG emits them for ANALYZE unless
1630    /// this is set.
1631    pub summary_off: bool,
1632    /// v7.37.23 (23.5) — `EXPLAIN (FORMAT text|json|xml|yaml)`.
1633    /// PG's standard format selector. Default is text. JSON / XML
1634    /// / YAML emit a single-row TEXT result whose body wraps the
1635    /// existing line-per-operator text in the chosen container —
1636    /// PG-compatible just enough for dashboards that parse those
1637    /// container shapes (pgAdmin's JSON path picker, etc.).
1638    pub format: ExplainFormat,
1639}
1640
1641#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1642pub enum ExplainFormat {
1643    #[default]
1644    Text,
1645    Json,
1646    Xml,
1647    Yaml,
1648}
1649
1650/// v7.39 (RLS) — the command a `CREATE POLICY` scopes to. `All` is the default.
1651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1652pub enum PolicyCmd {
1653    All,
1654    Select,
1655    Insert,
1656    Update,
1657    Delete,
1658}
1659
1660/// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
1661/// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`.
1662#[derive(Debug, Clone, PartialEq)]
1663pub struct CreatePolicyStatement {
1664    pub name: String,
1665    pub table: String,
1666    /// `true` = PERMISSIVE (default), `false` = RESTRICTIVE.
1667    pub permissive: bool,
1668    pub cmd: PolicyCmd,
1669    /// Empty = PUBLIC.
1670    pub roles: Vec<String>,
1671    pub using: Option<Expr>,
1672    pub with_check: Option<Expr>,
1673}
1674
1675/// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
1676/// [USING (expr)] [WITH CHECK (expr)] }`. Cannot change PERMISSIVE/RESTRICTIVE
1677/// or the command (matches PG).
1678#[derive(Debug, Clone, PartialEq)]
1679pub struct AlterPolicyStatement {
1680    pub name: String,
1681    pub table: String,
1682    pub rename_to: Option<String>,
1683    pub roles: Option<Vec<String>>,
1684    pub using: Option<Expr>,
1685    pub with_check: Option<Expr>,
1686}
1687
1688/// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
1689#[derive(Debug, Clone, PartialEq, Eq)]
1690pub struct DropPolicyStatement {
1691    pub name: String,
1692    pub table: String,
1693    pub if_exists: bool,
1694}
1695
1696#[derive(Debug, Clone, PartialEq, Eq)]
1697pub struct CreateUserStatement {
1698    pub name: String,
1699    /// Empty when the statement carried no PASSWORD — legal for a bare
1700    /// `CREATE ROLE`, which cannot log in anyway.
1701    pub password: String,
1702    /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
1703    /// the parser; the engine validates against `Role::parse` so a
1704    /// typo lands as a runtime error with a clear message rather than
1705    /// a parse failure.
1706    pub role: String,
1707    /// v7.39 (read01 round 58) — the PG role attributes. `None` = the
1708    /// statement did not say, so the default for its spelling applies:
1709    /// `CREATE USER` is `CREATE ROLE … LOGIN`, `CREATE ROLE` is NOLOGIN;
1710    /// both default to INHERIT and NOSUPERUSER.
1711    pub login: Option<bool>,
1712    pub inherit: Option<bool>,
1713    pub superuser: Option<bool>,
1714    /// `true` when spelled `CREATE USER` (LOGIN by default).
1715    pub is_user: bool,
1716}
1717
1718/// v7.39 (round 322, V46) — PG's function volatility class. Declarative:
1719/// it tells the planner how far a call may be moved or folded. SPG records
1720/// it faithfully (`pg_proc.provolatile`, `pg_get_functiondef`) and does not
1721/// yet exploit it for constant folding.
1722#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1723pub enum FunctionVolatility {
1724    Immutable,
1725    Stable,
1726    #[default]
1727    Volatile,
1728}
1729
1730impl FunctionVolatility {
1731    /// PG's one-character `pg_proc.provolatile` code.
1732    #[must_use]
1733    pub const fn as_pg_char(self) -> &'static str {
1734        match self {
1735            Self::Immutable => "i",
1736            Self::Stable => "s",
1737            Self::Volatile => "v",
1738        }
1739    }
1740
1741    #[must_use]
1742    pub const fn as_sql(self) -> &'static str {
1743        match self {
1744            Self::Immutable => "IMMUTABLE",
1745            Self::Stable => "STABLE",
1746            Self::Volatile => "VOLATILE",
1747        }
1748    }
1749}
1750
1751/// v7.39 (round 322, V46) — PG's parallel-safety class.
1752#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1753pub enum FunctionParallel {
1754    #[default]
1755    Unsafe,
1756    Restricted,
1757    Safe,
1758}
1759
1760impl FunctionParallel {
1761    /// PG's one-character `pg_proc.proparallel` code.
1762    #[must_use]
1763    pub const fn as_pg_char(self) -> &'static str {
1764        match self {
1765            Self::Unsafe => "u",
1766            Self::Restricted => "r",
1767            Self::Safe => "s",
1768        }
1769    }
1770
1771    #[must_use]
1772    pub const fn as_sql(self) -> &'static str {
1773        match self {
1774            Self::Unsafe => "PARALLEL UNSAFE",
1775            Self::Restricted => "PARALLEL RESTRICTED",
1776            Self::Safe => "PARALLEL SAFE",
1777        }
1778    }
1779}
1780
1781/// v7.39 (round 322, V46) — the attribute clauses `CREATE FUNCTION` accepts
1782/// on either side of its body. Defaults are PG's: VOLATILE, called on null
1783/// input, SECURITY INVOKER, not leakproof, PARALLEL UNSAFE, and the
1784/// language's default cost / rows.
1785#[derive(Debug, Clone, Copy, PartialEq, Default)]
1786pub struct FunctionAttrs {
1787    pub volatility: FunctionVolatility,
1788    /// `STRICT` / `RETURNS NULL ON NULL INPUT`: a call with any NULL
1789    /// argument returns NULL without running the body.
1790    pub strict: bool,
1791    pub security_definer: bool,
1792    pub leakproof: bool,
1793    pub parallel: FunctionParallel,
1794    /// `COST n` — `None` leaves PG's per-language default.
1795    pub cost: Option<f64>,
1796    /// `ROWS n` — set-returning functions only; `None` = default.
1797    pub rows: Option<f64>,
1798}
1799
1800impl FunctionAttrs {
1801    /// The attribute words `pg_get_functiondef` puts on their own line,
1802    /// in PG's order (measured on 18.4: volatility, PARALLEL, STRICT,
1803    /// SECURITY DEFINER, LEAKPROOF, COST, ROWS). Empty when everything is
1804    /// at its default — PG then emits no such line at all.
1805    #[must_use]
1806    pub fn render_words(&self) -> alloc::vec::Vec<alloc::string::String> {
1807        let mut out = alloc::vec::Vec::new();
1808        if self.volatility != FunctionVolatility::Volatile {
1809            out.push(alloc::string::String::from(self.volatility.as_sql()));
1810        }
1811        if self.parallel != FunctionParallel::Unsafe {
1812            out.push(alloc::string::String::from(self.parallel.as_sql()));
1813        }
1814        if self.strict {
1815            out.push(alloc::string::String::from("STRICT"));
1816        }
1817        if self.security_definer {
1818            out.push(alloc::string::String::from("SECURITY DEFINER"));
1819        }
1820        if self.leakproof {
1821            out.push(alloc::string::String::from("LEAKPROOF"));
1822        }
1823        if let Some(c) = self.cost {
1824            out.push(alloc::format!("COST {}", render_attr_number(c)));
1825        }
1826        if let Some(r) = self.rows {
1827            out.push(alloc::format!("ROWS {}", render_attr_number(r)));
1828        }
1829        out
1830    }
1831}
1832
1833/// PG prints a whole-numbered cost / rows without a decimal point.
1834fn render_attr_number(v: f64) -> alloc::string::String {
1835    // no_std: `f64::fract` lives in std, so compare against the truncation.
1836    let whole = v as i64;
1837    if v.abs() < 1e15 && (whole as f64) == v {
1838        alloc::format!("{whole}")
1839    } else {
1840        alloc::format!("{v}")
1841    }
1842}
1843
1844/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
1845/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
1846/// (the row-level trigger body the CREATE TRIGGER below references).
1847/// Non-trigger user-defined functions parse but error at execution
1848/// time with a clear unsupported message; that surface lands in
1849/// v7.12.5+.
1850#[derive(Debug, Clone, PartialEq)]
1851pub struct CreateFunctionStatement {
1852    pub name: String,
1853    /// `OR REPLACE` was present; an existing function with the
1854    /// same name is overwritten instead of erroring.
1855    pub or_replace: bool,
1856    /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
1857    /// list `()` (sufficient for trigger functions). Other shapes
1858    /// parse and store the args but the executor refuses to call
1859    /// them.
1860    pub args: Vec<FunctionArg>,
1861    /// `RETURNS <type>` — `trigger` is the supported shape for
1862    /// v7.12.4; arbitrary return types parse to
1863    /// [`FunctionReturn::Other`].
1864    pub returns: FunctionReturn,
1865    /// `LANGUAGE <lang>` clause. PG accepts the clause on either
1866    /// side of `AS $$...$$`; the parser canonicalises to one slot.
1867    /// `plpgsql` and `sql` are the two interesting values.
1868    pub language: String,
1869    /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
1870    /// a structured AST; non-trigger / non-plpgsql bodies stay as
1871    /// the raw source text so the v7.12.5+ executor can pick them
1872    /// up without a parser rev.
1873    pub body: FunctionBody,
1874    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
1875    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. PG accepts them
1876    /// on either side of the body; before this they were a parse error, so
1877    /// PG's own `pg_dump` output would not restore.
1878    pub attrs: FunctionAttrs,
1879}
1880
1881/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
1882#[derive(Debug, Clone, PartialEq)]
1883pub struct FunctionArg {
1884    /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
1885    /// (the default); `OUT` / `INOUT` parse but the executor
1886    /// refuses them.
1887    pub mode: FunctionArgMode,
1888    /// Optional arg name. Trigger functions traditionally don't
1889    /// name their args (they read NEW/OLD instead), so `None` is
1890    /// the common case.
1891    pub name: Option<String>,
1892    /// Declared type, normalised to the SPG `DataType` mapping
1893    /// where one exists. Unknown / extension types parse as a
1894    /// raw string under [`FunctionArgType::Raw`].
1895    pub ty: FunctionArgType,
1896}
1897
1898#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1899pub enum FunctionArgMode {
1900    In,
1901    Out,
1902    InOut,
1903}
1904
1905#[derive(Debug, Clone, PartialEq)]
1906pub enum FunctionArgType {
1907    Typed(ColumnTypeName),
1908    /// Unknown / extension types — kept as the parser-side raw
1909    /// identifier so error messages can name them precisely.
1910    Raw(String),
1911}
1912
1913#[derive(Debug, Clone, PartialEq)]
1914pub enum FunctionReturn {
1915    /// `RETURNS TRIGGER` — the row-level trigger function shape.
1916    /// v7.12.4 ships exactly this for execution.
1917    Trigger,
1918    /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
1919    /// the function is unused (since v7.12.4 doesn't ship scalar
1920    /// function invocation).
1921    Void,
1922    /// `RETURNS <type>` for any concrete data type. Reserved for
1923    /// v7.12.5+'s scalar UDF surface.
1924    Type(ColumnTypeName),
1925    /// `RETURNS <ident>` for types SPG doesn't know — extension
1926    /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
1927    Other(String),
1928}
1929
1930#[derive(Debug, Clone, PartialEq)]
1931pub enum FunctionBody {
1932    /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
1933    /// trigger-function executor walks this directly without
1934    /// re-parsing.
1935    PlPgSql(PlPgSqlBlock),
1936    /// Raw source text — parser couldn't (or didn't try to)
1937    /// structure-parse the body. Used for `LANGUAGE sql`
1938    /// functions and any PL/pgSQL body that contains v7.12.5+
1939    /// features the v7.12.4 parser doesn't yet recognise. The
1940    /// executor returns an unsupported error when invoked.
1941    Raw(String),
1942}
1943
1944/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
1945/// from assignment + return to a real-PL/pgSQL surface:
1946/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
1947/// control flow, `RAISE` diagnostics, and embedded SQL
1948/// statements that execute through the regular engine path.
1949/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
1950/// which mailrs's trigger doesn't need but other PG customers
1951/// may; deferred to a future minor release.
1952#[derive(Debug, Clone, PartialEq)]
1953pub struct PlPgSqlBlock {
1954    /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
1955    /// preceding `BEGIN`. Empty when the body opens directly with
1956    /// `BEGIN`. Declarations execute in order; each may reference
1957    /// earlier-declared locals in its init expression.
1958    pub declarations: Vec<PlPgSqlDeclare>,
1959    pub statements: Vec<PlPgSqlStmt>,
1960    /// v7.37.20 (20.10) — `EXCEPTION WHEN <cond> [OR <cond>...] THEN
1961    /// <body>` handlers appended to the block. Empty when no
1962    /// EXCEPTION clause is present. When a body statement raises
1963    /// (via RAISE EXCEPTION, ASSERT falsy, or a runtime error),
1964    /// handlers are tried in order; the first matching condition
1965    /// runs its body and the block terminates cleanly. `OTHERS`
1966    /// matches any exception. Unhandled exceptions propagate.
1967    pub exception_handlers: Vec<ExceptionHandler>,
1968}
1969
1970/// v7.37.20 (20.10) — one `WHEN <cond> [OR <cond>...] THEN <body>`
1971/// arm inside an EXCEPTION block.
1972#[derive(Debug, Clone, PartialEq)]
1973pub struct ExceptionHandler {
1974    /// Condition names (`OTHERS`, `unique_violation`, etc.). Multiple
1975    /// conditions joined by `OR` share one handler body.
1976    pub conditions: Vec<String>,
1977    /// Statements to run when a matching exception is caught.
1978    pub body: Vec<PlPgSqlStmt>,
1979}
1980
1981/// v7.12.6 — single `DECLARE` entry: variable name + declared
1982/// type + optional initialiser. Variables default to SQL NULL
1983/// when no init is given (matches PG).
1984#[derive(Debug, Clone, PartialEq)]
1985pub struct PlPgSqlDeclare {
1986    pub name: String,
1987    /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
1988    /// knows it; raw text otherwise).
1989    pub ty: FunctionArgType,
1990    pub default: Option<Expr>,
1991}
1992
1993#[derive(Debug, Clone, PartialEq)]
1994pub enum PlPgSqlStmt {
1995    /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
1996    /// for clarity in error reporting (PG also forbids it) — the
1997    /// executor errors with a clear "OLD is read-only" message.
1998    Assign { target: AssignTarget, value: Expr },
1999    /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
2000    /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
2001    /// the SELECT statement with the INTO clause stripped; the
2002    /// engine runs it via `Engine::execute`, takes the first
2003    /// row's first column, and assigns to the local variable
2004    /// in the DECLARE scope. Single-column / single-row
2005    /// queries only at v7.16.2; multi-target (`INTO a, b`) is
2006    /// a v7.16.x follow-up.
2007    SelectInto {
2008        var: String,
2009        body: Box<SelectStatement>,
2010    },
2011    /// `RETURN <target>;` — trigger functions canonically return
2012    /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
2013    /// expression for forward compatibility with scalar UDFs.
2014    Return(ReturnTarget),
2015    /// v7.39 (read01 round 66) — `RETURN NEXT <expr>;`: append one row to the
2016    /// set a SETOF function is building, and KEEP GOING. Not a return.
2017    ReturnNext(Expr),
2018    /// v7.39 (read01 round 66) — `RETURN QUERY <select>;`: append every row the
2019    /// query yields, and keep going. It used to desugar to a side-effect
2020    /// statement whose result was DISCARDED — in a SETOF function that is the
2021    /// whole answer thrown away.
2022    ReturnQuery(Box<SelectStatement>),
2023    /// v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the dynamic
2024    /// twin. Its rows go to the set too; it used to run and discard them.
2025    ReturnQueryExecute { sql: Expr },
2026    /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
2027    /// [ELSE body] END IF;`. Branches are tried in order; first
2028    /// truthy condition wins; the optional ELSE runs when no
2029    /// condition matched.
2030    If {
2031        branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
2032        else_branch: Vec<PlPgSqlStmt>,
2033    },
2034    /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
2035    /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
2036    /// (logging — observable side effect only) or `EXCEPTION`
2037    /// (aborts the trigger and propagates as an error). v7.12.6
2038    /// supports the basic format-string substitution PG uses
2039    /// (`%` placeholders consumed positionally).
2040    Raise {
2041        level: RaiseLevel,
2042        message: String,
2043        args: Vec<Expr>,
2044    },
2045    /// v7.12.6 — embedded SQL statement inside the trigger body
2046    /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
2047    /// NEW.col / OLD.col references inside the embedded
2048    /// statement's expression tree are substituted with the
2049    /// current trigger context before the engine re-executes the
2050    /// statement. Recursion depth into nested triggers is
2051    /// bounded by the engine's existing trigger-fire guard.
2052    EmbeddedSql(Box<Statement>),
2053    /// v7.37.20 (20.14) — `ASSERT <condition> [, <message>];`. If
2054    /// the condition evaluates falsy the trigger / DO block aborts
2055    /// with the message (defaulting to a generic shape when none
2056    /// is provided). Same propagation shape as `RAISE EXCEPTION`
2057    /// — the error reaches the caller's query path. PG's behaviour
2058    /// is identical except for a `plpgsql.check_asserts` GUC that
2059    /// can disable the check globally; SPG always evaluates.
2060    Assert {
2061        condition: Expr,
2062        message: Option<Expr>,
2063    },
2064    /// v7.37.20 (20.3) — `WHILE <condition> LOOP <body> END LOOP;`.
2065    /// Iterate the body while condition evaluates truthy. Iteration
2066    /// count is bounded by `WHILE_LOOP_BUDGET` to prevent runaway
2067    /// loops; the executor errors out when reached. EXIT / CONTINUE
2068    /// inside the body queue with 20.2.
2069    While {
2070        condition: Expr,
2071        body: Vec<PlPgSqlStmt>,
2072    },
2073    /// v7.37.20 (20.4) — `FOR <var> IN [REVERSE] <start>..<end> LOOP
2074    /// <body> END LOOP;`. Integer iteration; `var` is BigInt-valued;
2075    /// bounds inclusive on both sides. REVERSE walks backward.
2076    /// Iteration budget guards runaway.
2077    ForRange {
2078        var: String,
2079        start: Expr,
2080        end: Expr,
2081        reverse: bool,
2082        body: Vec<PlPgSqlStmt>,
2083    },
2084    /// v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`. Runs the body
2085    /// repeatedly; only `EXIT [WHEN <cond>]` breaks out. Iteration
2086    /// budget guards runaway.
2087    Loop { body: Vec<PlPgSqlStmt> },
2088    /// v7.37.20 (20.2) — `EXIT [WHEN <condition>];` inside a loop.
2089    /// Unconditional (no WHEN) or conditional (only breaks when
2090    /// condition is truthy). Bubbles up as BodyOutcome::Break which
2091    /// the enclosing loop catches. Outside a loop it's a no-op.
2092    Exit { when: Option<Expr> },
2093    /// v7.37.20 (20.2) — `CONTINUE [WHEN <condition>];` inside a
2094    /// loop. Same shape as EXIT but bubbles up as BodyOutcome::Continue
2095    /// which the enclosing loop catches, skipping the remainder of
2096    /// the body and jumping to the next iteration.
2097    Continue { when: Option<Expr> },
2098    /// v7.37.20 (20.13) — `EXECUTE <string_expr>;` runs a runtime-
2099    /// computed SQL statement. The expression is evaluated to a
2100    /// text value, the resulting string is parsed and dispatched
2101    /// through the engine like an EmbeddedSql. USING <param_list>
2102    /// for placeholder binding queues with v7.40 PL/pgSQL epic.
2103    ExecuteDynamic { sql: Expr },
2104    /// v7.37.20 (20.5) — `FOR <var> IN <select_body> LOOP <body>
2105    /// END LOOP;`. Runs the SELECT once, iterates the resulting
2106    /// rows, binds the first column of each row to `var` as a
2107    /// scalar Value, then runs the body per iteration. EXIT /
2108    /// CONTINUE / ASSERT / RAISE etc. propagate through the
2109    /// enclosing loop's BodyOutcome discipline the same way
2110    /// FOR range and WHILE do. Full record-binding (var as
2111    /// composite carrying all columns) queues with v7.40 record
2112    /// type infrastructure.
2113    ForQuery {
2114        var: String,
2115        query: Box<SelectStatement>,
2116        body: Vec<PlPgSqlStmt>,
2117    },
2118    /// v7.37.20 (20.6) — `FOR <var> IN EXECUTE <string_expr> LOOP
2119    /// <body> END LOOP;`. Same shape as ForQuery but the SELECT is
2120    /// computed at runtime from a text expression, parsed on the
2121    /// fly, then iterated. Enables dynamic queries where the
2122    /// projection / FROM / WHERE clauses depend on runtime values.
2123    ForExecute {
2124        var: String,
2125        sql_expr: Expr,
2126        body: Vec<PlPgSqlStmt>,
2127    },
2128}
2129
2130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2131pub enum RaiseLevel {
2132    /// `RAISE NOTICE` — diagnostic message, observable in the
2133    /// server log. Does not affect the trigger's outcome.
2134    Notice,
2135    /// `RAISE WARNING` — like NOTICE, slightly louder severity.
2136    Warning,
2137    /// `RAISE INFO` — like NOTICE, slightly quieter.
2138    Info,
2139    /// `RAISE LOG` — like NOTICE, lower priority.
2140    Log,
2141    /// `RAISE DEBUG` — like NOTICE, lowest priority.
2142    Debug,
2143    /// `RAISE EXCEPTION` — aborts the trigger function with the
2144    /// given message, propagating up to the caller as a query-
2145    /// level error.
2146    Exception,
2147}
2148
2149#[derive(Debug, Clone, PartialEq)]
2150pub enum AssignTarget {
2151    NewColumn(String),
2152    OldColumn(String),
2153    /// Reserved for v7.12.5 DECLARE'd local variables.
2154    Local(String),
2155}
2156
2157#[derive(Debug, Clone, PartialEq)]
2158pub enum ReturnTarget {
2159    /// `RETURN NEW;` — for BEFORE triggers, this is the row that
2160    /// actually gets written (possibly with NEW.col mutations
2161    /// applied). For AFTER triggers, the return value is ignored.
2162    New,
2163    /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
2164    /// the delete proceed; for BEFORE UPDATE / INSERT it's
2165    /// equivalent to dropping the write.
2166    Old,
2167    /// `RETURN NULL;` — for BEFORE triggers, skips the write
2168    /// entirely. For AFTER, the return value is ignored.
2169    Null,
2170    /// `RETURN <expr>;` — non-row return shape; reserved for the
2171    /// scalar UDF surface in v7.12.5+. Executor errors when used
2172    /// inside a trigger function.
2173    Expr(Expr),
2174}
2175
2176/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
2177/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
2178/// but the executor refuses them. `WHEN (cond)` clauses are out
2179/// of scope; the trigger function can short-circuit on a leading
2180/// IF inside its body once v7.12.5 lands IF.
2181#[derive(Debug, Clone, PartialEq)]
2182pub struct CreateTriggerStatement {
2183    pub name: String,
2184    pub or_replace: bool,
2185    pub timing: TriggerTiming,
2186    /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
2187    /// three entries in order.
2188    pub events: Vec<TriggerEvent>,
2189    pub table: String,
2190    /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
2191    /// only `Row`; `Statement` parses but the executor refuses.
2192    pub for_each: TriggerForEach,
2193    /// Name of the function to invoke. The function must exist at
2194    /// CREATE TRIGGER time — PG18-measured (round 753): PG refuses a
2195    /// forward reference (`function no_such_fn() does not exist`), so
2196    /// requiring it IS the PG behaviour (the old note claimed the
2197    /// opposite).
2198    pub function: String,
2199    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
2200    /// (mailrs round-5 G7). Non-empty only when the events list
2201    /// contains UPDATE and the user wrote the column-list filter.
2202    /// PG fires the trigger only when at least one of these
2203    /// columns appears in the SET clause; SPG conservatively
2204    /// fires on any UPDATE matching the listed columns or
2205    /// rewriting them at the row level. Empty vec = no filter
2206    /// (fire on every UPDATE).
2207    pub update_columns: Vec<String>,
2208    /// v7.39 (round 138) — `WHEN ( condition )` row-level filter: the row
2209    /// trigger fires only when the condition (over NEW / OLD) is true. `None`
2210    /// = no WHEN (fire unconditionally). Not allowed on INSTEAD OF triggers.
2211    pub when_condition: Option<Expr>,
2212}
2213
2214/// v7.39 (round 139) — `CREATE RULE` query-rewrite rule AST node.
2215#[derive(Debug, Clone, PartialEq)]
2216pub struct CreateRuleStatement {
2217    pub name: String,
2218    pub or_replace: bool,
2219    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
2220    pub event: String,
2221    pub table: String,
2222    /// `true` = `DO INSTEAD` (replace the operation), `false` = `DO ALSO`
2223    /// (run alongside; PG's default when neither keyword is written).
2224    pub instead: bool,
2225    /// Optional `WHERE ( condition )` — the rule applies only when it holds.
2226    pub when_condition: Option<Expr>,
2227    /// The `DO` commands (over NEW / OLD). Empty = `NOTHING`.
2228    pub commands: Vec<Statement>,
2229}
2230
2231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2232pub enum TriggerTiming {
2233    /// Fires before the row is written; the trigger function's
2234    /// return value (NEW or NULL) decides the row content and
2235    /// whether the write proceeds at all.
2236    Before,
2237    /// Fires after the row is written; the return value is
2238    /// ignored.
2239    After,
2240    /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
2241    /// v7.12.4 (SPG has no updatable-view surface).
2242    InsteadOf,
2243}
2244
2245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2246pub enum TriggerEvent {
2247    Insert,
2248    Update,
2249    Delete,
2250    /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
2251    /// so the trigger never fires.
2252    Truncate,
2253}
2254
2255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2256pub enum TriggerForEach {
2257    Row,
2258    Statement,
2259}
2260
2261/// v7.39 (round 537) — a `CREATE INDEX` key column's ordering clause.
2262///
2263/// SPG's index does not scan in a direction, but `indexdef` reproduces
2264/// the DDL and dropping this made `(a DESC NULLS LAST)` read back as
2265/// `(a)`. `nulls_first` is `None` when the statement did not say, in
2266/// which case PG's default applies — LAST for ascending, FIRST for
2267/// descending, and neither is rendered.
2268#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2269pub struct IndexColumnOrder {
2270    pub descending: bool,
2271    pub nulls_first: Option<bool>,
2272}
2273
2274#[derive(Debug, Clone, PartialEq)]
2275pub struct CreateIndexStatement {
2276    pub name: String,
2277    /// `CREATE INDEX CONCURRENTLY`. SPG builds indexes synchronously
2278    /// either way, so this changes nothing about how the index is made
2279    /// — it is carried because PG refuses the CONCURRENTLY form inside
2280    /// a transaction block and accepts the plain one, and the engine
2281    /// cannot tell them apart without it.
2282    pub concurrently: bool,
2283    /// v7.39 (round 537) — the leading key column's ordering clause,
2284    /// which is the column SPG indexes.
2285    pub key_order: IndexColumnOrder,
2286    /// v7.39 (round 538) — an explicit `COLLATE` on that key, as
2287    /// written. SPG orders text by bytes, so honouring it changes
2288    /// nothing; PG prints it, because an explicitly named collation and
2289    /// the one a column inherits are different objects.
2290    pub key_collation: Option<String>,
2291    pub table: String,
2292    pub column: String,
2293    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2294    /// (PG 15+). Default (`false`) is the SQL-standard NULLS DISTINCT, where
2295    /// any NULL in the key exempts the row from the uniqueness check.
2296    pub nulls_not_distinct: bool,
2297    /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
2298    /// graph for vector kNN); unspecified is the default B-tree index.
2299    pub method: IndexMethod,
2300    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2301    /// index name already exists, instead of raising `DuplicateIndex`.
2302    pub if_not_exists: bool,
2303    /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
2304    /// non-key columns the planner should treat as "covered" by
2305    /// this index when checking whether a query can run as an
2306    /// index-only scan. Empty when no `INCLUDE` clause was given.
2307    pub included_columns: Vec<String>,
2308    /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
2309    /// for which `<expr>` evaluates truthy enter the index;
2310    /// queries whose `WHERE` clause's canonical Display form
2311    /// matches this expression's Display form can be served by the
2312    /// partial index. Stored as a parsed `Expr` so the engine
2313    /// re-uses the existing evaluation path; storage persists the
2314    /// Display form on the catalog snapshot.
2315    pub partial_predicate: Option<Expr>,
2316    /// v6.8.2 — expression-based index. When `Some(expr)`, the
2317    /// index key is the result of `expr` evaluated on each row
2318    /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
2319    /// field still names the *primary* column the expression
2320    /// touches so existing planner shortcuts that resolve a
2321    /// column position stay valid. `None` = plain
2322    /// column-reference index (the legacy shape).
2323    pub expression: Option<Expr>,
2324    /// v7.9.14 — extra column names after the leading column in a
2325    /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
2326    /// planner today still only uses the leading column for index
2327    /// seeks; the extras are tracked verbatim so the same DDL
2328    /// round-trips through WAL replay + catalog snapshot, and so
2329    /// the engine can emit a clear warning at INDEX CREATE time
2330    /// that only the leading column is currently honoured.
2331    /// Composite BTree index keys land in v7.10.
2332    pub extra_columns: Vec<String>,
2333    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2334    /// enforces uniqueness on the indexed key (combined with the
2335    /// `partial_predicate` filter — only rows where the predicate
2336    /// evaluates truthy enter the uniqueness check). Standard SQL
2337    /// and PG's canonical way to express conditional uniqueness.
2338    /// mailrs K1.
2339    pub is_unique: bool,
2340    /// v7.15.0 — operator class on the leading column, when the
2341    /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2342    /// Lower-cased. Most opclasses are still informational; the
2343    /// engine routes on `gin_trgm_ops` specifically to build a
2344    /// trigram-shingle GIN over a TEXT column, and otherwise
2345    /// keeps the current "accepted and discarded" behaviour for
2346    /// pg_dump compatibility.
2347    pub opclass: Option<String>,
2348    /// r1038 — the access method as WRITTEN, lower-cased; `None` when
2349    /// there was no `USING` clause.
2350    ///
2351    /// `method` cannot answer this: `gist` / `spgist` / `hash` all become
2352    /// `IndexMethod::BTree` so PG schemas naming an AM SPG has no
2353    /// implementation for still load. That degradation is deliberate, but
2354    /// it loses the name — and the operator-class check needs it, both to
2355    /// look the class up under the AM the user actually named and to say
2356    /// which AM it was missing from, the way PG's message does.
2357    pub method_name: Option<String>,
2358}
2359
2360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2361pub enum IndexMethod {
2362    /// Default — B-tree over `IndexKey`. Used for equality / range
2363    /// lookups on scalar columns.
2364    BTree,
2365    /// `USING hnsw` — NSW graph for kNN over a vector column.
2366    Hnsw,
2367    /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2368    /// metadata that records (min_key, max_key) for each page in a
2369    /// cold-tier segment, on the indexed column. The optimizer
2370    /// can use these summaries to skip pages whose range does NOT
2371    /// overlap a query's WHERE predicate. BRIN indexes carry no
2372    /// in-memory data — the summaries live in the segment v2
2373    /// envelope's sidecar. Created via the standard
2374    /// `CREATE INDEX … USING brin (col)` syntax.
2375    Brin,
2376    /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2377    /// column. Posting lists map `lexeme word` → row locators; the
2378    /// planner uses them to narrow `WHERE col @@ tsquery` to the
2379    /// candidate rows whose vectors contain a matching term, then
2380    /// re-evaluates the full `@@` semantics on each candidate.
2381    /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2382    /// silently degraded to a full scan at query time.
2383    Gin,
2384}
2385
2386/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2387/// inside a CREATE TABLE column list.
2388///
2389/// The source table's shape can only be read from the catalog, so the
2390/// parser records the clause and the engine expands it. `at` is how many
2391/// explicit columns preceded it: PG keeps the written order, so
2392/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2393#[derive(Debug, Clone, PartialEq)]
2394pub struct LikeSpec {
2395    pub source: String,
2396    pub at: usize,
2397    pub options: LikeOptions,
2398}
2399
2400/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2401/// types and NOT NULL and nothing else — measured on PG18, where a
2402/// copied generated column becomes a plain one and a copied identity
2403/// column loses its identity.
2404#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2405pub struct LikeOptions {
2406    pub defaults: bool,
2407    pub constraints: bool,
2408    pub identity: bool,
2409    pub generated: bool,
2410    pub indexes: bool,
2411    pub comments: bool,
2412}
2413
2414#[derive(Debug, Clone, PartialEq)]
2415pub struct CreateTableStatement {
2416    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2417    /// creating session's own namespace: it shadows a permanent table of the
2418    /// same name, other sessions never see it, and it is dropped when the
2419    /// session ends. A `bool` here lands in the struct's existing padding.
2420    pub temporary: bool,
2421    pub name: String,
2422    /// v7.39 — the `ENGINE=` a MySQL dump names. Consumed and discarded
2423    /// before, so `ENGINE=NONSUCH` built a table where MySQL 9.7.2
2424    /// answers `ERROR 1286`, and `sql_mode` claimed
2425    /// `NO_ENGINE_SUBSTITUTION` while doing it.
2426    pub engine: Option<String>,
2427    pub columns: Vec<ColumnDef>,
2428    /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2429    /// the order written. Empty for a table that has none.
2430    pub like_specs: Vec<LikeSpec>,
2431    /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2432    /// Empty for a table that inherits from nothing. Order matters:
2433    /// the child takes each parent's columns in this order before its
2434    /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2435    pub inherits: Vec<String>,
2436    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2437    /// table name already exists, instead of raising `DuplicateTable`.
2438    pub if_not_exists: bool,
2439    /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2440    /// constraints. Column-level `REFERENCES` (single-column inline
2441    /// form) is normalised into this vec at parse time so the engine
2442    /// sees one uniform list.
2443    pub foreign_keys: Vec<ForeignKeyConstraint>,
2444    /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2445    /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2446    /// Engine resolves each into a BTree index named after the
2447    /// constraint's leading column at CREATE TABLE time; INSERT
2448    /// path enforces composite uniqueness via row scan on the
2449    /// leading column index.
2450    pub table_constraints: Vec<TableConstraint>,
2451    /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2452    /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2453    /// the engine creates a parent table whose own rows stay
2454    /// empty and routes INSERT/SELECT through children. Mutually
2455    /// exclusive with `partition_of` (parser enforces).
2456    pub partition_by: Option<PartitionBySpec>,
2457    /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2458    /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2459    /// the table inherits its column list from `parent` (the
2460    /// parser rejects an explicit column list when this is set);
2461    /// engine routes child rows back to the parent at INSERT.
2462    pub partition_of: Option<PartitionOfSpec>,
2463}
2464
2465/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2466/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2467/// future LIST / HASH without breaking the public AST shape.
2468#[derive(Debug, Clone, PartialEq)]
2469pub struct PartitionBySpec {
2470    pub kind: PartitionKindAst,
2471    /// One or more ident references into the parent's column list.
2472    /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2473    /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2474    /// shape PG-compatible.
2475    pub key_columns: Vec<String>,
2476}
2477
2478#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2479pub enum PartitionKindAst {
2480    Range,
2481    /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2482    /// `FOR VALUES IN (lit, lit, …)`.
2483    List,
2484    /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2485    /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2486    Hash,
2487}
2488
2489/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2490/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2491/// or the catch-all `DEFAULT` partition.
2492#[derive(Debug, Clone, PartialEq)]
2493pub struct PartitionOfSpec {
2494    pub parent_name: String,
2495    pub bounds: PartitionOfBoundsAst,
2496}
2497
2498#[derive(Debug, Clone, PartialEq)]
2499pub enum PartitionOfBoundsAst {
2500    /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2501    /// (lits include vector bodies), so we box both bounds to keep
2502    /// the variant size in line with `Default` for clippy and to
2503    /// minimise per-statement footprint when the partition shape
2504    /// isn't in use.
2505    Range {
2506        lower: Box<Expr>,
2507        upper: Box<Expr>,
2508    },
2509    /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2510    /// expr resolves to a typed literal at child-create time.
2511    List {
2512        values: Vec<Expr>,
2513    },
2514    /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2515    /// PG enforces `0 ≤ r < m`; m must be positive.
2516    Hash {
2517        modulus: u32,
2518        remainder: u32,
2519    },
2520    Default,
2521}
2522
2523/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2524/// column list. Either a composite PRIMARY KEY or a UNIQUE
2525/// (single- or multi-column).
2526#[derive(Debug, Clone, PartialEq)]
2527pub enum TableConstraint {
2528    /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2529    /// referenced column. Engine builds a BTree index named
2530    /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2531    PrimaryKey {
2532        name: Option<String>,
2533        columns: Vec<String>,
2534        /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2535        /// Round 621 consumed the clauses; these carry them.
2536        deferrable: bool,
2537        initially_deferred: bool,
2538    },
2539    /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2540    /// named `<table>_<leading_col>_key` (single-column) or
2541    /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2542    /// uniqueness on INSERT.
2543    Unique {
2544        name: Option<String>,
2545        columns: Vec<String>,
2546        /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2547        /// G10). PG 15+ flips the NULL handling so any number of
2548        /// NULL rows collide on the constraint. Default is
2549        /// `false` (NULLS DISTINCT, standard SQL behaviour).
2550        nulls_not_distinct: bool,
2551        /// v7.39 (round 711) — see PrimaryKey.
2552        deferrable: bool,
2553        initially_deferred: bool,
2554    },
2555    /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2556    /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2557    /// this same variant at parse time. Engine evaluates the
2558    /// predicate against each INSERT/UPDATE candidate row; a
2559    /// false / NULL result rejects the mutation.
2560    /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2561    /// PG adds such a constraint without scanning the existing rows: new
2562    /// rows are checked, the ones already there are grandfathered in, and
2563    /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2564    /// scans and flips it. pg_dump emits the suffix for exactly those, so
2565    /// validating them on restore would refuse a dump PG itself produced.
2566    Check {
2567        name: Option<String>,
2568        expr: Expr,
2569        not_valid: bool,
2570    },
2571    /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2572    /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2573    /// every element (the booking/scheduling non-overlap constraint,
2574    /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2575    /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2576    /// enforcement doesn't build the index yet). Each element pairs a
2577    /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2578    Exclude {
2579        name: Option<String>,
2580        method: Option<String>,
2581        elements: Vec<(String, String)>,
2582    },
2583    /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2584    /// non-unique secondary-index declaration inline in CREATE
2585    /// TABLE. Engine builds a BTree index on the leading column
2586    /// (composite columns parse but only the leading column is
2587    /// honoured at v7.15 — matches the existing
2588    /// `CreateIndexStatement::extra_columns` semantics). Useful
2589    /// for `mysql/blog`-style schemas that lean on routine
2590    /// secondary indexes for ORM lookups.
2591    Index {
2592        name: Option<String>,
2593        columns: Vec<String>,
2594    },
2595    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2596    /// (cols)` inline declaration. Pre-v7.17 the parser
2597    /// silently dropped these so MyISAM-imported FULLTEXT
2598    /// indexes vanished; v7.17 routes them through the
2599    /// existing tsvector-GIN engine path so MATCH AGAINST
2600    /// queries get a real inverted index instead of falling
2601    /// back to a full scan. Multi-column FULLTEXT KEYs build
2602    /// one GIN per column at v7.17 (per-column posting lists);
2603    /// the leading column drives query planning.
2604    FulltextIndex {
2605        name: Option<String>,
2606        columns: Vec<String>,
2607    },
2608}
2609
2610#[derive(Debug, Clone, PartialEq)]
2611#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2612pub struct ColumnDef {
2613    pub name: String,
2614    pub ty: ColumnTypeName,
2615    pub nullable: bool,
2616    /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2617    /// evaluates this once (with an empty row) and caches the resulting
2618    /// `Value` on the column schema.
2619    pub default: Option<Expr>,
2620    /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2621    /// per such column and fills the slot when INSERT leaves it
2622    /// unbound (omitted from a column-list INSERT or explicitly NULL).
2623    pub auto_increment: bool,
2624    /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2625    /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2626    /// an implicit BTree index named `<table>_pkey` over this
2627    /// column at CREATE TABLE time, satisfying the parent-side
2628    /// index requirement for any FOREIGN KEY pointing at it.
2629    pub is_primary_key: bool,
2630    /// v7.13.0 — inline `UNIQUE` column constraint
2631    /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2632    /// into a single-column `TableConstraint::Unique` so the
2633    /// engine path stays uniform with table-level UNIQUE.
2634    pub is_unique: bool,
2635    /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2636    /// inline column constraint: treat NULL keys as equal so only one NULL
2637    /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2638    /// `TableConstraint::Unique { nulls_not_distinct }`.
2639    pub unique_nulls_not_distinct: bool,
2640    /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2641    /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2642    /// since this round so the fold into the table-level constraint keeps it.
2643    pub constraint_deferrable: bool,
2644    pub constraint_initially_deferred: bool,
2645    /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2646    /// (mailrs round-5 G3). Stored alongside the column so the
2647    /// CREATE TABLE handler can fold these into table-level
2648    /// CHECK constraints. Multiple inline CHECKs on the same
2649    /// column are concatenated with AND at the table level.
2650    pub check: Option<Expr>,
2651    /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2652    /// parser sees an unknown column-type ident (anything not in
2653    /// the built-in `parse_column_type_name` table), it sets
2654    /// `ty = ColumnTypeName::Text` and records the original name
2655    /// here. The engine resolves at CREATE TABLE time: if a
2656    /// catalog enum/domain with this name exists, the column is
2657    /// bound to it (label-checked on INSERT for enums; CHECK-
2658    /// constrained for domains); otherwise the CREATE TABLE
2659    /// errors with "unknown type".
2660    pub user_type_ref: Option<String>,
2661    /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2662    /// CURRENT_TIMESTAMP` column attribute. When set, an
2663    /// UPDATE that does NOT explicitly bind this column
2664    /// overrides the new value with `now()` (engine clock).
2665    /// Pre-v7.17 SPG silently accepted the syntax and never
2666    /// fired the override — `updated_at` columns from mysqldump
2667    /// stayed pinned at their initial DEFAULT forever, an
2668    /// audit Tier-S silent-failure. Generalised as a stored
2669    /// expression source so future shapes (`ON UPDATE
2670    /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2671    /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2672    pub on_update_runtime: Option<Expr>,
2673    /// v7.17.0 Phase 2.5 — text collation derived from the
2674    /// post-fix `COLLATE <name>` clause (and / or the table-level
2675    /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2676    /// per column). Pre-2.5 SPG accepted the clause and
2677    /// discarded the name, leaving every column byte-compared
2678    /// — a Tier-S silent failure when the customer expected
2679    /// `_ci` / `case_insensitive` semantics. Parser normalises
2680    /// the raw collation name into the variants in `Collation`.
2681    /// Default `Binary` preserves the legacy compare path.
2682    pub collation: Collation,
2683    /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2684    /// explicit `COLLATE <name>` clause rather than the default. Under the
2685    /// MySQL dialect a text column with NO explicit clause takes the
2686    /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2687    /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2688    /// flag is the only thing that tells them apart.
2689    pub collation_explicit: bool,
2690    /// v7.39 (round 676) — the collation name AS WRITTEN, because
2691    /// `collation` above cannot carry it: `Collation` is a two-variant
2692    /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2693    /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2694    /// tell them apart.
2695    pub collation_name: Option<String>,
2696    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2697    /// 4.4 SPG accepted and discarded the keyword, leaving
2698    /// negative values silently accepted on a column the
2699    /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2700    /// rejects negative INSERT / UPDATE values on UNSIGNED int
2701    /// columns. SPG widening to `u64`-shaped storage is out of
2702    /// v7.17 scope; the upper bound remains the signed-type max
2703    /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2704    /// exceeds what every mailrs / Rails app actually uses.
2705    pub is_unsigned: bool,
2706    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2707    /// value list captured at parse time. When `Some`, the parser
2708    /// recognised `ENUM(...)` in the type slot; the engine
2709    /// validates INSERT cells against this list at
2710    /// column_def_to_schema time and persists the variants on
2711    /// `ColumnSchema.inline_enum_variants`. None for all
2712    /// non-ENUM columns.
2713    pub inline_enum_variants: Option<Vec<String>>,
2714    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2715    /// value list. Distinct from ENUM (subset semantics rather
2716    /// than pick-one). None for all non-SET columns.
2717    pub inline_set_variants: Option<Vec<String>>,
2718    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2719    /// STORED` computed-column source. When `Some`, the engine
2720    /// stores the Display-form of the parsed expression on
2721    /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2722    /// and re-evaluates the expression against every INSERT /
2723    /// UPDATE candidate row, overwriting whatever the caller
2724    /// supplied for this column. Boxed to keep `ColumnDef` from
2725    /// blowing past the `large_enum_variant` clippy ceiling
2726    /// (`Expr` widens with vector literals).
2727    pub generated_stored_expr: Option<Box<Expr>>,
2728    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2729    /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2730    /// `auto_increment`; this additionally marks the ALWAYS one, whose
2731    /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2732    /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2733    /// VALUE`. Only meaningful when the column is also an identity column.
2734    pub identity_always: bool,
2735    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2736    /// integer width (TINYINT / MEDIUMINT), captured before the type
2737    /// collapses to SmallInt / Int. The engine copies it to
2738    /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2739    /// path can enforce the real range. None for every other column and
2740    /// under the PG dialect.
2741    pub mysql_int_width: Option<MysqlIntWidth>,
2742    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2743    /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2744    /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2745    /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2746    /// CREATE TABLE time so the write path can truncate and the render path
2747    /// can pad. None under the PG dialect, where temporal columns keep full
2748    /// microseconds.
2749    pub mysql_fsp: Option<u8>,
2750    /// v7.39.2 — the column was written `TIMESTAMP` rather than
2751    /// `DATETIME` in a MySQL session. The engine copies it to
2752    /// `ColumnSchema.mysql_declared_timestamp` at CREATE TABLE.
2753    pub mysql_declared_timestamp: bool,
2754    /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)` pair, copied to
2755    /// `ColumnSchema.mysql_float_md` at CREATE TABLE.
2756    pub mysql_float_md: Option<(u8, u8)>,
2757}
2758
2759/// v7.17.0 Phase 2.5 — text collation classification surfaced
2760/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2761/// engine bridges between the two at CREATE TABLE time.
2762///
2763/// Recognised collation-name patterns (case-insensitive):
2764///   * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase`         → CaseInsensitive
2765///   * Everything else (`C`, `POSIX`, `default`,
2766///     `pg_catalog.default`, `*_cs`, `*_bin`, unknown names)   → Binary
2767#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2768pub enum Collation {
2769    Binary,
2770    CaseInsensitive,
2771}
2772
2773/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2774/// integer width for a column whose `ColumnTypeName` is too wide to carry
2775/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2776/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2777/// TABLE time. Only recorded under the MySQL dialect.
2778#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2779pub enum MysqlIntWidth {
2780    Tiny,
2781    Small,
2782    Medium,
2783    Int,
2784    /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2785    Big,
2786}
2787
2788#[allow(clippy::derivable_impls)]
2789impl Default for Collation {
2790    fn default() -> Self {
2791        Self::Binary
2792    }
2793}
2794
2795impl Collation {
2796    /// Classify a `COLLATE <name>` ident into one of the supported
2797    /// variants. Empty / unknown names fall back to `Binary` —
2798    /// matches the pre-2.5 silent-accept behaviour for snapshots
2799    /// that load through but don't actually depend on the
2800    /// collation semantics.
2801    #[must_use]
2802    pub fn from_collation_name(name: &str) -> Self {
2803        let lc = name.trim().to_ascii_lowercase();
2804        // Strip any quotes / schema-qualifier the parser left on
2805        // (e.g. `pg_catalog.default`).
2806        let bare = lc
2807            .trim_matches(|c: char| c == '"' || c == '\'')
2808            .rsplit('.')
2809            .next()
2810            .unwrap_or("");
2811        if bare.is_empty() {
2812            return Self::Binary;
2813        }
2814        if bare == "case_insensitive" || bare == "nocase" {
2815            return Self::CaseInsensitive;
2816        }
2817        // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2818        // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2819        if bare.ends_with("_ci") {
2820            return Self::CaseInsensitive;
2821        }
2822        Self::Binary
2823    }
2824}
2825
2826/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2827/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2828/// parse into this shape — the column-level form has a single-entry
2829/// `columns` / `parent_columns`.
2830#[derive(Debug, Clone, PartialEq)]
2831pub struct ForeignKeyConstraint {
2832    /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2833    /// today but parses + stores it so a future ALTER TABLE DROP
2834    /// CONSTRAINT can target by name (v7.6.8).
2835    pub name: Option<String>,
2836    /// Local columns participating in the FK (≥ 1).
2837    pub columns: Vec<String>,
2838    /// Referenced parent table.
2839    pub parent_table: String,
2840    /// Referenced parent columns. Must have the same arity as
2841    /// `columns`; engine validates parent has a PK / UNIQUE index
2842    /// on exactly this column set (v7.6.1).
2843    pub parent_columns: Vec<String>,
2844    /// `ON DELETE` action. Defaults to `Restrict` if absent.
2845    pub on_delete: FkAction,
2846    /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2847    pub on_update: FkAction,
2848    /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2849    pub match_type: MatchType,
2850    /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2851    /// dropped on the floor, so a constraint declared DEFERRABLE was
2852    /// enforced immediately and a circular-FK migration could not load.
2853    pub deferrable: bool,
2854    /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2855    /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2856    pub initially_deferred: bool,
2857}
2858
2859/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2860/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2861/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2862#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2863pub enum MatchType {
2864    #[default]
2865    Simple,
2866    Full,
2867}
2868
2869/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2871pub enum FkAction {
2872    /// Reject the parent mutation if any child row references it.
2873    /// SQL spec default; SPG default when no clause is given.
2874    Restrict,
2875    /// Recursively propagate the parent's delete / update to the
2876    /// child rows. Same TX.
2877    Cascade,
2878    /// Set the child FK column(s) to NULL. Requires the FK columns
2879    /// to be NULL-able.
2880    SetNull,
2881    /// Set the child FK column(s) to their declared DEFAULT.
2882    /// Requires the child column(s) to have DEFAULT.
2883    SetDefault,
2884    /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2885    /// `Restrict` because the single-writer model has no deferred
2886    /// constraint window; the keyword is accepted for compatibility.
2887    NoAction,
2888}
2889
2890/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2891/// optional `USING <encoding>` clause; omitting it keeps the
2892/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2893/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2894/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2895/// binary16 (2× compression, ~3 decimal digits of precision).
2896#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2897pub enum VecEncoding {
2898    /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
2899    /// uncompressed `vector` type wire / storage layout.
2900    #[default]
2901    F32,
2902    /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
2903    /// `spg_storage::quantize::Sq8Vector` for the math + recall
2904    /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
2905    /// dim ≥ 32).
2906    Sq8,
2907    /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
2908    /// per-element. DDL keyword `HALF` (pgvector convention).
2909    /// Bit-exact dequantise to f32 at the storage layer; no
2910    /// rerank pass needed for kNN search.
2911    F16,
2912}
2913
2914impl fmt::Display for VecEncoding {
2915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2916        match self {
2917            Self::F32 => f.write_str("F32"),
2918            Self::Sq8 => f.write_str("SQ8"),
2919            // pgvector convention: DDL keyword is `HALF`, not `F16`.
2920            Self::F16 => f.write_str("HALF"),
2921        }
2922    }
2923}
2924
2925/// SQL-level type names. The mapping to the storage runtime's `DataType`
2926/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
2927#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2928pub enum ColumnTypeName {
2929    /// v7.39 (round 291) — PG's `name`, the identifier type its
2930    /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
2931    /// answered `type "name" does not exist` to.
2932    Name,
2933    /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
2934    /// 32-bit wrapping counter the row header carries; `xid8` is the
2935    /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
2936    /// SPG answered `type "xid" does not exist` to.
2937    Xid,
2938    Xid8,
2939    /// v7.39 (round 667) — `OID`. `XID` was already a column type here
2940    /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
2941    /// `type "oid" does not exist` while `t(x XID)` built fine.
2942    Oid,
2943    SmallInt,
2944    Int,
2945    BigInt,
2946    Float,
2947    /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
2948    /// IEEE. It used to map to [`Self::Float`] on the theory that a
2949    /// wider float is harmless, but the width is observable: a `real`
2950    /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
2951    /// answered false where PG answers true.
2952    Real,
2953    Text,
2954    /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
2955    Varchar(u32),
2956    /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
2957    Char(u32),
2958    Bool,
2959    /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
2960    /// `USING <encoding>` clause; omitting it surfaces as
2961    /// `encoding = VecEncoding::F32` (the pre-v6 default).
2962    Vector {
2963        dim: u32,
2964        encoding: VecEncoding,
2965    },
2966    /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
2967    /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
2968    /// v7.39 (round 271) — scale widened to u16 alongside the value's.
2969    /// v7.39 (round 272) — precision too: PG's runs to 1000.
2970    /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
2971    /// a negative one rounds to tens / hundreds. A VALUE's display scale
2972    /// stays unsigned.
2973    Numeric(u16, i16),
2974    /// `DATE` — calendar day, no time-of-day component.
2975    Date,
2976    /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
2977    /// precision.
2978    Timestamp,
2979    /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
2980    /// stores all timestamps as UTC microseconds-since-epoch and
2981    /// does not carry per-row offset (PG's internal representation
2982    /// is the same — TZ is a display convention). The distinction
2983    /// from `TIMESTAMP` exists for the PG-wire layer to advertise
2984    /// OID 1184 so sqlx-style clients decode into
2985    /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
2986    Timestamptz,
2987    /// v4.9 `JSON` — text-backed JSON document. No parse-time
2988    /// validation; the engine round-trips the literal verbatim.
2989    /// PG OID 114 on the wire.
2990    Json,
2991    /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
2992    /// PG OID 3802 on the wire so sqlx-style binary-typed clients
2993    /// decode without a custom type registration.
2994    Jsonb,
2995    /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
2996    /// Literal forms (decoded by the engine at coercion time):
2997    ///   - PG hex form: `'\xDEADBEEF'`
2998    ///   - Escape form: `'foo\\000bar'` (backslash octal triples)
2999    Bytes,
3000    /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
3001    /// OID 1009. Literal forms accepted by the parser:
3002    ///   - `ARRAY['a', 'b', NULL]`
3003    ///   - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
3004    ///     form at coerce time)
3005    TextArray,
3006    /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
3007    /// 1007. Same literal forms as TEXT[] (substituting integer
3008    /// elements).
3009    IntArray,
3010    /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
3011    /// OID 1016.
3012    BigIntArray,
3013    /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
3014    /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
3015    /// external form). G-CRIT-3.
3016    TsVector,
3017    /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
3018    /// wire OID 3615.
3019    TsQuery,
3020    /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
3021    /// Literal input accepts canonical hyphenated, unhyphenated,
3022    /// uppercase, and `{...}`-braced forms; display normalises to
3023    /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
3024    /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
3025    /// gen_random_uuid()`.
3026    Uuid,
3027    /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
3028    /// microseconds since 00:00:00. PG wire OID 1083. Literal
3029    /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
3030    /// (6-digit microsecond precision). Display normalises to
3031    /// the canonical `HH:MM:SS[.ffffff]`.
3032    Time,
3033    /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
3034    /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
3035    /// PG OID; advertised as INT4 on the wire. Display always
3036    /// 4 digits zero-padded.
3037    Year,
3038    /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
3039    /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
3040    /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
3041    /// Offset range: ±14 hours.
3042    TimeTz,
3043    /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
3044    /// (locale-independent storage). Wire OID 790. Literal input
3045    /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
3046    /// major units), optional leading `-`. Display: en_US locale.
3047    Money,
3048    /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
3049    /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
3050    /// — the engine bridges to `DataType::Range(RangeKind)`.
3051    Range(RangeKindAst),
3052    /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
3053    /// `text => text` map with NULL value support.
3054    Hstore,
3055    /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
3056    IntArray2D,
3057    BigIntArray2D,
3058    TextArray2D,
3059    /// v7.39 (read01 round 75) — `bool[][]`.
3060    BoolArray2D,
3061    /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
3062    /// three-field {months, days, micros} struct (PG-byte-equal),
3063    /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
3064    /// β-P2 `INTERVAL` was runtime-only — literal in expression
3065    /// position but rejected at CREATE TABLE.
3066    Interval,
3067    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
3068    /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
3069    /// PG external form quotes each non-NULL element because
3070    /// interval text contains spaces / colons
3071    /// (`{"1 day","24:00:00",NULL}`).
3072    IntervalArray,
3073    /// v7.37.5 γ — full PG array-of-scalar family. Each variant
3074    /// mirrors a scalar `ColumnTypeName` that already existed.
3075    BoolArray,
3076    SmallIntArray,
3077    FloatArray,
3078    NumericArray,
3079    DateArray,
3080    TimestampArray,
3081    TimestamptzArray,
3082    UuidArray,
3083    JsonArray,
3084    JsonbArray,
3085    BytesArray,
3086    VarcharArray,
3087    CharArray,
3088    /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
3089    /// as `Range(RangeKindAst)` — one column type variant covers
3090    /// all six builtin multiranges, kind pins the element type.
3091    /// Wire OIDs in pgwire.
3092    Multirange(RangeKindAst),
3093    /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3094    /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3095    /// Wire OIDs in pgwire.
3096    Point,
3097    Lseg,
3098    Path,
3099    PgBox,
3100    Polygon,
3101    Line,
3102    Circle,
3103    /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3104    Inet,
3105    Cidr,
3106    Macaddr,
3107    Macaddr8,
3108    /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3109    Bit(u32),
3110    /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3111    BitVarying(u32),
3112    Xml,
3113    Char1,
3114    MoneyArray,
3115}
3116
3117/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3118/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3119/// crate doesn't depend on storage. Bridged at engine boundary.
3120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3121pub enum RangeKindAst {
3122    Int4,
3123    Int8,
3124    Num,
3125    Ts,
3126    TsTz,
3127    Date,
3128}
3129
3130impl fmt::Display for ColumnTypeName {
3131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3132        match self {
3133            Self::SmallInt => f.write_str("SMALLINT"),
3134            Self::Int => f.write_str("INT"),
3135            Self::BigInt => f.write_str("BIGINT"),
3136            Self::Float => f.write_str("FLOAT"),
3137            Self::Real => f.write_str("REAL"),
3138            Self::Text => f.write_str("TEXT"),
3139            Self::Name => f.write_str("name"),
3140            Self::Xid => f.write_str("xid"),
3141            Self::Xid8 => f.write_str("xid8"),
3142            Self::Oid => f.write_str("oid"),
3143            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3144            Self::Char(n) => write!(f, "CHAR({n})"),
3145            Self::Bool => f.write_str("BOOL"),
3146            Self::Vector { dim, encoding } => match encoding {
3147                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3148                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3149                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3150            },
3151            Self::Json => f.write_str("JSON"),
3152            Self::Jsonb => f.write_str("JSONB"),
3153            Self::Bytes => f.write_str("BYTEA"),
3154            Self::TextArray => f.write_str("TEXT[]"),
3155            Self::IntArray => f.write_str("INT[]"),
3156            Self::BigIntArray => f.write_str("BIGINT[]"),
3157            Self::TsVector => f.write_str("TSVECTOR"),
3158            Self::TsQuery => f.write_str("TSQUERY"),
3159            Self::Uuid => f.write_str("UUID"),
3160            Self::Numeric(p, s) => {
3161                if *s == 0 {
3162                    write!(f, "NUMERIC({p})")
3163                } else {
3164                    write!(f, "NUMERIC({p}, {s})")
3165                }
3166            }
3167            Self::Date => f.write_str("DATE"),
3168            Self::Timestamp => f.write_str("TIMESTAMP"),
3169            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3170            Self::Time => f.write_str("TIME"),
3171            Self::Year => f.write_str("YEAR"),
3172            Self::TimeTz => f.write_str("TIMETZ"),
3173            Self::Money => f.write_str("MONEY"),
3174            Self::Range(k) => f.write_str(match k {
3175                RangeKindAst::Int4 => "INT4RANGE",
3176                RangeKindAst::Int8 => "INT8RANGE",
3177                RangeKindAst::Num => "NUMRANGE",
3178                RangeKindAst::Ts => "TSRANGE",
3179                RangeKindAst::TsTz => "TSTZRANGE",
3180                RangeKindAst::Date => "DATERANGE",
3181            }),
3182            Self::Hstore => f.write_str("HSTORE"),
3183            Self::Interval => f.write_str("INTERVAL"),
3184            Self::IntervalArray => f.write_str("INTERVAL[]"),
3185            Self::BoolArray => f.write_str("BOOL[]"),
3186            Self::SmallIntArray => f.write_str("SMALLINT[]"),
3187            Self::FloatArray => f.write_str("FLOAT[]"),
3188            Self::NumericArray => f.write_str("NUMERIC[]"),
3189            Self::DateArray => f.write_str("DATE[]"),
3190            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3191            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3192            Self::UuidArray => f.write_str("UUID[]"),
3193            Self::JsonArray => f.write_str("JSON[]"),
3194            Self::JsonbArray => f.write_str("JSONB[]"),
3195            Self::BytesArray => f.write_str("BYTEA[]"),
3196            Self::VarcharArray => f.write_str("VARCHAR[]"),
3197            Self::CharArray => f.write_str("CHAR[]"),
3198            Self::Multirange(k) => f.write_str(match k {
3199                RangeKindAst::Int4 => "INT4MULTIRANGE",
3200                RangeKindAst::Int8 => "INT8MULTIRANGE",
3201                RangeKindAst::Num => "NUMMULTIRANGE",
3202                RangeKindAst::Ts => "TSMULTIRANGE",
3203                RangeKindAst::TsTz => "TSTZMULTIRANGE",
3204                RangeKindAst::Date => "DATEMULTIRANGE",
3205            }),
3206            Self::Point => f.write_str("POINT"),
3207            Self::Lseg => f.write_str("LSEG"),
3208            Self::Path => f.write_str("PATH"),
3209            Self::PgBox => f.write_str("BOX"),
3210            Self::Polygon => f.write_str("POLYGON"),
3211            Self::Line => f.write_str("LINE"),
3212            Self::Circle => f.write_str("CIRCLE"),
3213            Self::Inet => f.write_str("INET"),
3214            Self::Cidr => f.write_str("CIDR"),
3215            Self::Macaddr => f.write_str("MACADDR"),
3216            Self::Macaddr8 => f.write_str("MACADDR8"),
3217            Self::Bit(0) => f.write_str("BIT"),
3218            Self::Bit(n) => write!(f, "BIT({n})"),
3219            Self::BitVarying(0) => f.write_str("VARBIT"),
3220            Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3221            Self::Xml => f.write_str("XML"),
3222            Self::Char1 => f.write_str("\"char\""),
3223            Self::MoneyArray => f.write_str("MONEY[]"),
3224            Self::IntArray2D => f.write_str("INT[][]"),
3225            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3226            Self::TextArray2D => f.write_str("TEXT[][]"),
3227            Self::BoolArray2D => f.write_str("BOOL[][]"),
3228        }
3229    }
3230}
3231
3232/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3233/// engine evaluates `expr` per matched row in the table's row order
3234/// and rewrites cells in place. Indexed columns are dropped + re-
3235/// inserted into the affected B-tree on each row change.
3236/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3237/// tail on a DML statement. Boxed off the statement struct so the PG-only
3238/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3239/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3240/// the identical meaning, so both share this one payload rather than each
3241/// growing its own.
3242#[derive(Debug, Clone, PartialEq)]
3243pub struct DmlOrderLimit {
3244    pub order_by: Vec<OrderBy>,
3245    pub limit: Option<u32>,
3246}
3247
3248/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3249/// FROM, kept so the engine can finish the job.
3250///
3251/// The parser rewrites the statement onto correlated subqueries, and it
3252/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3253/// name belongs to the target or to a source needs their column lists,
3254/// which parse time does not have. Carrying the clause lets the engine
3255/// — which has the catalog — resolve the rest.
3256#[derive(Debug, Clone, PartialEq)]
3257pub struct UpdateFromSources {
3258    pub from: FromClause,
3259    pub sub_where: Option<Expr>,
3260}
3261
3262#[derive(Debug, Clone, PartialEq)]
3263pub struct UpdateStatement {
3264    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3265    /// level UPDATE. Empty for a plain UPDATE.
3266    pub ctes: Vec<Cte>,
3267    pub table: String,
3268    /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3269    /// to `t`'s own rows and not to anything that descends from it.
3270    ///
3271    /// Round 644 taught the FROM clause the keyword and left DML behind
3272    /// because it needed a field here, and this struct carries a warning
3273    /// that round 413 measured widening it in place overflowing the
3274    /// parser's nesting stack. That warning was about `from_sources`, a
3275    /// struct wide enough to need boxing; a `bool` lands in the padding
3276    /// already present — same as `CreateTableStatement::temporary`.
3277    ///
3278    /// It also earns its keep beyond the spelling: the inheritance
3279    /// fan-out needs a way to say "the parent's own rows" as a
3280    /// statement, or running one on the parent recurses forever.
3281    pub only: bool,
3282    /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3283    /// statement's expressions refer to the target row by. PG allows the
3284    /// bare spelling here (unlike INSERT, which requires AS).
3285    pub alias: Option<String>,
3286    pub assignments: Vec<(String, Expr)>,
3287    /// v7.39 (round 533) — boxed: round 413 measured that widening this
3288    /// struct in place overflows the parser's nesting stack.
3289    pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3290    pub where_: Option<Expr>,
3291    /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3292    /// mutate the first `limit` rows in the given order. PG has no such
3293    /// clause; the parser accepts it only under the MySQL dialect. Boxed
3294    /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3295    /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3296    /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3297    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3298    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3299    /// clause (legacy CommandComplete path). Some = engine
3300    /// evaluates the projection over each mutated row and
3301    /// streams the result as a Rows QueryResult.
3302    pub returning: Option<Vec<SelectItem>>,
3303}
3304
3305/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3306/// from the active catalog and prunes them from every index.
3307#[derive(Debug, Clone, PartialEq)]
3308pub struct DeleteStatement {
3309    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3310    /// level DELETE. Empty for a plain DELETE.
3311    pub ctes: Vec<Cte>,
3312    pub table: String,
3313    /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3314    /// to `t`'s own rows and not to anything that descends from it.
3315    ///
3316    /// Round 644 taught the FROM clause the keyword and left DML behind
3317    /// because it needed a field here, and this struct carries a warning
3318    /// that round 413 measured widening it in place overflowing the
3319    /// parser's nesting stack. That warning was about `from_sources`, a
3320    /// struct wide enough to need boxing; a `bool` lands in the padding
3321    /// already present — same as `CreateTableStatement::temporary`.
3322    ///
3323    /// It also earns its keep beyond the spelling: the inheritance
3324    /// fan-out needs a way to say "the parent's own rows" as a
3325    /// statement, or running one on the parent recurses forever.
3326    pub only: bool,
3327    /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3328    /// the WHERE / RETURNING expressions refer to the target row by.
3329    pub alias: Option<String>,
3330    pub where_: Option<Expr>,
3331    /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3332    /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3333    /// form (round 413), so it shares that payload — and it is boxed for
3334    /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3335    /// statement tipped the parser's 512 KiB nesting stack.
3336    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3337    /// v7.9.4 — `RETURNING <projection>`.
3338    pub returning: Option<Vec<SelectItem>>,
3339}
3340
3341/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3342/// One WHEN clause fires per source row depending on whether the
3343/// `on` condition matched any target row(s); the executor walks
3344/// `clauses` in declaration order and fires the first whose
3345/// `matched` kind and optional `condition` are both satisfied.
3346#[derive(Debug, Clone, PartialEq)]
3347pub struct MergeStatement {
3348    /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3349    /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3350    /// in PG). Each CTE materialises before the merge runs and its alias
3351    /// resolves as a source relation.
3352    pub ctes: Vec<Cte>,
3353    pub target: String,
3354    pub target_alias: Option<String>,
3355    pub source: String,
3356    pub source_alias: Option<String>,
3357    /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3358    /// the engine materialises this SELECT for the source rows and `source`
3359    /// is empty; the alias (required by PG for a subquery source) is in
3360    /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3361    pub source_select: Option<Box<SelectStatement>>,
3362    /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3363    /// positional column-alias list after the source alias. Empty when
3364    /// the statement carries none; the engine renames the materialised
3365    /// source columns positionally (PG's rule).
3366    pub source_column_aliases: Vec<String>,
3367    pub on: Expr,
3368    pub clauses: Vec<MergeWhenClause>,
3369    /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3370    /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3371    /// target/source aliases. `None` = no RETURNING (the common form).
3372    pub returning: Option<Vec<SelectItem>>,
3373}
3374
3375#[derive(Debug, Clone, PartialEq)]
3376pub struct MergeWhenClause {
3377    pub matched: MergeMatched,
3378    /// Optional `AND <expr>` filter — when present, the clause
3379    /// only fires for the source rows whose match-pair satisfies
3380    /// the predicate.
3381    pub condition: Option<Expr>,
3382    pub action: MergeAction,
3383}
3384
3385#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3386pub enum MergeMatched {
3387    Matched,
3388    /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3389    /// target row (the classic insert branch).
3390    NotMatched,
3391    /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3392    /// row no source row matches. Actions are UPDATE / DELETE / DO
3393    /// NOTHING only (INSERT is a syntax error, as in PG).
3394    NotMatchedBySource,
3395}
3396
3397#[derive(Debug, Clone, PartialEq)]
3398pub enum MergeAction {
3399    /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3400    /// explicit column list (the bare `INSERT VALUES (vals)`
3401    /// shape lands later).
3402    Insert {
3403        columns: Vec<String>,
3404        values: Vec<Expr>,
3405    },
3406    /// `UPDATE SET col = expr [, …]` — applied to every matched
3407    /// target row for the firing source row.
3408    Update { assignments: Vec<(String, Expr)> },
3409    /// `DELETE` — drop every matched target row.
3410    Delete,
3411    /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3412    /// the clause and SPG mirrors so a customer-side MERGE that
3413    /// uses it for branch-control doesn't error).
3414    DoNothing,
3415}
3416
3417#[derive(Debug, Clone, PartialEq)]
3418pub struct InsertStatement {
3419    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3420    /// level INSERT (writable CTE outer body). Empty for a plain
3421    /// INSERT. PG semantics: each CTE materialises before the
3422    /// outer INSERT runs, sharing the same transaction.
3423    pub ctes: Vec<Cte>,
3424    pub table: String,
3425    /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3426    /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3427    /// row by. PG requires the AS keyword in this position.
3428    pub alias: Option<String>,
3429    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3430    /// `None`, every tuple is positional and must match the table arity.
3431    /// When `Some`, the engine maps each tuple slot to the named column and
3432    /// fills the rest with NULL (must be nullable).
3433    pub columns: Option<Vec<String>>,
3434    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3435    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3436    /// `select_source` is `Some` (the engine builds rows from the
3437    /// inner SELECT result set instead).
3438    pub rows: Vec<Vec<Expr>>,
3439    /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3440    /// round-5 G4). When present, `rows` is empty and the engine
3441    /// materialises the SELECT result, coerces each output tuple to
3442    /// the target column types, and inserts as a single batch.
3443    pub select_source: Option<Box<SelectStatement>>,
3444    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3445    /// upsert clause. None = legacy INSERT (conflict raises a
3446    /// DuplicateKey error). mailrs migration blocker #2.
3447    pub on_conflict: Option<OnConflictClause>,
3448    /// v7.9.4 — `RETURNING <projection>`.
3449    pub returning: Option<Vec<SelectItem>>,
3450    /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3451    /// between the column list and VALUES. Governs how explicitly-supplied
3452    /// values interact with `GENERATED … AS IDENTITY` columns:
3453    ///   * `None` — default. A `GENERATED ALWAYS` identity column rejects
3454    ///     an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3455    ///   * `System` — override the ALWAYS restriction: the explicit value
3456    ///     is used verbatim, as for a `BY DEFAULT` column.
3457    ///   * `User` — ignore any explicit value on a `BY DEFAULT` identity
3458    ///     column and generate from the sequence instead (no effect on
3459    ///     non-identity columns).
3460    pub overriding: Overriding,
3461    /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3462    /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3463    /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3464    /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3465    /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3466    /// into a NOT NULL column becomes the type's default), and the engine
3467    /// cannot recover that intent from the conflict clause alone. A plain
3468    /// `bool` lands in this struct's existing padding, so the AST does not
3469    /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3470    pub mysql_ignore: bool,
3471}
3472
3473/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3474#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3475pub enum Overriding {
3476    /// No `OVERRIDING` clause.
3477    #[default]
3478    None,
3479    /// `OVERRIDING SYSTEM VALUE`.
3480    System,
3481    /// `OVERRIDING USER VALUE`.
3482    User,
3483}
3484
3485/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3486#[derive(Debug, Clone, PartialEq)]
3487pub struct OnConflictClause {
3488    /// Local columns that identify the conflict (must match a
3489    /// UNIQUE / PRIMARY KEY index on the target table). Empty
3490    /// list means the user wrote `ON CONFLICT DO …` without a
3491    /// target — the engine arbitrates on every unique constraint
3492    /// (round 240).
3493    pub target_columns: Vec<String>,
3494    /// v7.39 (round 240) — the index predicate after the target list
3495    /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3496    /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3497    /// which satisfy any predicate, so it is parsed and carried but not
3498    /// consulted (recorded residual: partial-unique-index arbiters).
3499    pub index_where: Option<Expr>,
3500    /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3501    /// <name>`: the pg_dump conflict-target form. The engine
3502    /// resolves the name to the constraint's columns.
3503    pub constraint_name: Option<String>,
3504    /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3505    /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3506    /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3507    /// `ON CONFLICT DO UPDATE` is refused (42601).
3508    pub mysql_lowered: bool,
3509    /// The action on conflict.
3510    pub action: OnConflictAction,
3511}
3512
3513/// v7.9.7 — action on conflict.
3514#[derive(Debug, Clone, PartialEq)]
3515pub enum OnConflictAction {
3516    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3517    /// silently skips conflicting ones.
3518    Nothing,
3519    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3520    /// may reference `EXCLUDED.col` to read the incoming row's
3521    /// value (engine wires `EXCLUDED` as a virtual table).
3522    Update {
3523        assignments: Vec<(String, Expr)>,
3524        where_: Option<Expr>,
3525    },
3526}
3527
3528/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3529///
3530/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3531/// policies are spelled again here and mapped at the engine boundary.
3532/// v7.39 — the modes `BEGIN` / `START TRANSACTION` / `SET TRANSACTION`
3533/// / `SET SESSION CHARACTERISTICS` accept. `read_only` used to be parsed
3534/// and dropped on the floor, so `BEGIN READ ONLY` opened an ordinary
3535/// read-write transaction and every write in it was accepted.
3536///
3537/// `None` on either field means the statement did not name that mode, so
3538/// the session default applies — which is not the same as naming the
3539/// default explicitly.
3540#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3541pub struct TransactionModes {
3542    pub isolation: Option<IsolationLevel>,
3543    /// `Some(true)` = READ ONLY, `Some(false)` = READ WRITE.
3544    pub read_only: Option<bool>,
3545}
3546
3547/// v7.39 — what a read-only transaction refuses, and what PG calls it.
3548///
3549/// SPG did not enforce read-only transactions at all: `BEGIN READ ONLY;
3550/// INSERT …` answered `INSERT 0 1` and committed, and
3551/// `default_transaction_read_only = on` changed nothing. Both GUCs were
3552/// in the inventory, so a session could set one, read it back, and be
3553/// told it held a guarantee nothing was enforcing. Applications open
3554/// read-only transactions as a SAFETY measure — a reporting connection,
3555/// a read-only leg in a pool, a "this path must not write" discipline —
3556/// so accepting the writes is the worst possible answer.
3557///
3558/// `Some(tag)` means refuse with PG's message, `cannot execute {tag} in
3559/// a read-only transaction` (SQLSTATE 25006). Every tag below was read
3560/// back from PostgreSQL 18.6 by running the statement inside
3561/// `BEGIN READ ONLY`, one statement per transaction so no error could be
3562/// attributed to the wrong line.
3563///
3564/// Several answers were not what one would guess, which is why they were
3565/// measured rather than reasoned:
3566///
3567///   * `CREATE TEMP TABLE` is REFUSED, tagged `CREATE TABLE`.
3568///   * `NOTIFY`, `LISTEN` and `REINDEX` are ALLOWED.
3569///   * `PREPARE` of an INSERT is ALLOWED — only the EXECUTE writes.
3570///   * `UPDATE … WHERE false`, which changes nothing, is still REFUSED:
3571///     the verb decides, not the row count.
3572///   * `GRANT`, `COMMENT ON` and `SELECT … FOR SHARE` are all REFUSED.
3573///
3574/// The match is exhaustive on purpose. A new statement cannot be added
3575/// without deciding here whether it writes, which is the failure this
3576/// repository keeps meeting: one member of a family gets handled and its
3577/// siblings quietly do not.
3578impl Statement {
3579    #[must_use]
3580    pub fn read_only_violation_tag(&self) -> Option<&'static str> {
3581        match self {
3582            // ---- writes rows -------------------------------------------
3583            Self::Insert { .. } => Some("INSERT"),
3584            Self::Update { .. } => Some("UPDATE"),
3585            Self::Delete { .. } => Some("DELETE"),
3586            Self::Merge { .. } => Some("MERGE"),
3587            Self::Truncate { .. } => Some("TRUNCATE TABLE"),
3588            Self::CopyFromFile { .. } => Some("COPY FROM"),
3589
3590            // A SELECT that takes row locks writes lock state, and PG
3591            // names the strength it was asked for.
3592            Self::Select(sel) => sel.locking.as_ref().map(|l| match l.strength {
3593                LockStrength::Update => "SELECT FOR UPDATE",
3594                LockStrength::NoKeyUpdate => "SELECT FOR NO KEY UPDATE",
3595                LockStrength::Share => "SELECT FOR SHARE",
3596                LockStrength::KeyShare => "SELECT FOR KEY SHARE",
3597            }),
3598
3599            // ---- changes the catalog -----------------------------------
3600            Self::CreateTable { .. } => Some("CREATE TABLE"),
3601            Self::DropTable { .. } => Some("DROP TABLE"),
3602            Self::AlterTable { .. } => Some("ALTER TABLE"),
3603            Self::CreateIndex { .. } => Some("CREATE INDEX"),
3604            Self::DropIndex { .. } => Some("DROP INDEX"),
3605            Self::AlterIndex { .. } => Some("ALTER INDEX"),
3606            Self::CreateView { .. } => Some("CREATE VIEW"),
3607            Self::DropView { .. } => Some("DROP VIEW"),
3608            Self::CreateMaterializedView { .. } => Some("CREATE MATERIALIZED VIEW"),
3609            Self::RefreshMaterializedView { .. } => Some("REFRESH MATERIALIZED VIEW"),
3610            Self::DropMaterializedView { .. } => Some("DROP MATERIALIZED VIEW"),
3611            Self::CreateSequence { .. } => Some("CREATE SEQUENCE"),
3612            Self::AlterSequence { .. } => Some("ALTER SEQUENCE"),
3613            Self::DropSequence { .. } => Some("DROP SEQUENCE"),
3614            Self::CreateType { .. } => Some("CREATE TYPE"),
3615            Self::DropType { .. } => Some("DROP TYPE"),
3616            Self::AlterTypeAddValue { .. } | Self::AlterTypeRenameValue { .. } => {
3617                Some("ALTER TYPE")
3618            }
3619            Self::CreateDomain { .. } => Some("CREATE DOMAIN"),
3620            Self::AlterDomain { .. } => Some("ALTER DOMAIN"),
3621            Self::DropDomain { .. } => Some("DROP DOMAIN"),
3622            Self::CreateSchema { .. } => Some("CREATE SCHEMA"),
3623            Self::DropSchema { .. } => Some("DROP SCHEMA"),
3624            Self::CreateFunction { .. } => Some("CREATE FUNCTION"),
3625            Self::DropFunction { .. } => Some("DROP FUNCTION"),
3626            Self::CreateTrigger { .. } => Some("CREATE TRIGGER"),
3627            Self::DropTrigger { .. } => Some("DROP TRIGGER"),
3628            Self::CreateRule { .. } => Some("CREATE RULE"),
3629            Self::DropRule { .. } => Some("DROP RULE"),
3630            Self::CreateExtension { .. } => Some("CREATE EXTENSION"),
3631            Self::CreateStatistics { .. } => Some("CREATE STATISTICS"),
3632            Self::DropStatistics { .. } => Some("DROP STATISTICS"),
3633            Self::DropAggregate { .. } => Some("DROP AGGREGATE"),
3634            Self::CommentOn { .. } => Some("COMMENT"),
3635            Self::DropDatabase { .. } => Some("DROP DATABASE"),
3636            Self::CreatePublication { .. } => Some("CREATE PUBLICATION"),
3637            Self::DropPublication { .. } => Some("DROP PUBLICATION"),
3638            Self::CreateSubscription { .. } => Some("CREATE SUBSCRIPTION"),
3639            Self::DropSubscription { .. } => Some("DROP SUBSCRIPTION"),
3640
3641            // ---- changes roles / permissions ---------------------------
3642            Self::CreateUser { .. } => Some("CREATE ROLE"),
3643            Self::DropUser { .. } => Some("DROP ROLE"),
3644            Self::AlterRolePassword { .. } | Self::SetDbRoleSetting { .. } => Some("ALTER ROLE"),
3645            Self::Grant { .. } => Some("GRANT"),
3646            Self::Revoke { .. } => Some("REVOKE"),
3647            Self::CreatePolicy { .. } => Some("CREATE POLICY"),
3648            Self::AlterPolicy { .. } => Some("ALTER POLICY"),
3649            Self::DropPolicy { .. } => Some("DROP POLICY"),
3650            Self::AlterSystem { .. } => Some("ALTER SYSTEM"),
3651
3652            // ---- SPG's own writers -------------------------------------
3653            // Rewrites cold-tier segments on disk. PG has no equivalent to
3654            // ask, so the test is what it does, not what it is called.
3655            Self::CompactColdSegments => Some("COMPACT COLD SEGMENTS"),
3656
3657            // ---- allowed -----------------------------------------------
3658            // Reads, transaction control, session state, cursors, and the
3659            // maintenance statements PG itself permits. `REINDEX` really is
3660            // allowed in a read-only transaction (measured), which is why
3661            // `Maintain` is here.
3662            //
3663            // `Prepare`, `Execute`, `Call` and `DoBlock` are allowed at
3664            // this level for the reason PG allows them: the write inside
3665            // is refused when it runs, by this same check. Measured:
3666            // `PREPARE p AS INSERT …` succeeds; `DO $$ … INSERT … $$`
3667            // fails with `cannot execute INSERT`.
3668            Self::Explain { .. }
3669            | Self::CopyTo { .. }
3670            | Self::CopyToFile { .. }
3671            | Self::Analyze { .. }
3672            | Self::Maintain { .. }
3673            | Self::Vacuum { .. }
3674            | Self::Begin { .. }
3675            | Self::Commit
3676            | Self::Rollback
3677            | Self::Savepoint { .. }
3678            | Self::RollbackToSavepoint { .. }
3679            | Self::ReleaseSavepoint { .. }
3680            | Self::PrepareTransaction { .. }
3681            | Self::SetTransaction { .. }
3682            | Self::SetConstraints { .. }
3683            | Self::SetParameter { .. }
3684            | Self::SetParameterList { .. }
3685            | Self::SetUserVars { .. }
3686            | Self::SetRole { .. }
3687            | Self::ResetParameter { .. }
3688            | Self::ShowParameter { .. }
3689            | Self::Discard { .. }
3690            | Self::Prepare { .. }
3691            | Self::Execute { .. }
3692            | Self::Deallocate { .. }
3693            | Self::Call { .. }
3694            | Self::DoBlock { .. }
3695            | Self::DeclareCursor { .. }
3696            | Self::FetchCursor { .. }
3697            | Self::MoveCursor { .. }
3698            | Self::CloseCursor { .. }
3699            | Self::Listen { .. }
3700            | Self::Notify { .. }
3701            | Self::Unlisten { .. }
3702            | Self::Kill { .. }
3703            | Self::WaitForWalPosition { .. }
3704            | Self::ValidateOnly { .. }
3705            | Self::NoOpPreventedInTransaction { .. }
3706            | Self::Empty
3707            | Self::ShowTables
3708            | Self::ShowDatabases
3709            | Self::UseDatabase(_)
3710            | Self::ShowCreateTable { .. }
3711            | Self::ShowIndexes { .. }
3712            | Self::ShowStatus
3713            | Self::ShowVariables
3714            | Self::ShowVariablesLike { .. }
3715            | Self::ShowProcesslist
3716            | Self::ShowColumns { .. }
3717            | Self::ShowUsers
3718            | Self::ShowPublications
3719            | Self::ShowSubscriptions => None,
3720        }
3721    }
3722}
3723
3724#[derive(Debug, Clone, PartialEq, Eq)]
3725pub struct LockingClause {
3726    pub strength: LockStrength,
3727    /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3728    pub of_tables: Vec<String>,
3729    pub policy: LockWait,
3730}
3731
3732/// PG's four tuple-lock strengths, weakest first.
3733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3734pub enum LockStrength {
3735    KeyShare,
3736    Share,
3737    NoKeyUpdate,
3738    Update,
3739}
3740
3741/// What to do when the row is already locked.
3742#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3743pub enum LockWait {
3744    /// Block until it is free — PG's default.
3745    #[default]
3746    Wait,
3747    /// `NOWAIT` — fail the statement with 55P03.
3748    NoWait,
3749    /// `SKIP LOCKED` — leave the row out of the result.
3750    SkipLocked,
3751}
3752
3753#[derive(Debug, Clone, PartialEq, Default)]
3754pub struct SelectStatement {
3755    /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3756    /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3757    /// whole syntax and locked nothing: two workers running the classic
3758    /// `SKIP LOCKED` queue take both took the same row.
3759    /// v7.39 (round 305) — boxed. A locking clause appears on a
3760    /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3761    /// cost every `SelectStatement` 32 bytes, and this struct sits in
3762    /// recursive evaluation frames where the engine already runs close to
3763    /// its stack budget (a 512 KB depth guard is the canary).
3764    pub locking: Option<alloc::boxed::Box<LockingClause>>,
3765    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3766    /// expressions, materialised once at query start before the
3767    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3768    /// only — no `WITH RECURSIVE` for v4.x.
3769    pub ctes: Vec<Cte>,
3770    pub distinct: bool,
3771    /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3772    /// keep the first row (per ORDER BY) of each group the
3773    /// expressions define. Empty = no DISTINCT ON.
3774    pub distinct_on: Vec<Expr>,
3775    pub items: Vec<SelectItem>,
3776    pub from: Option<FromClause>,
3777    pub where_: Option<Expr>,
3778    pub group_by: Option<Vec<Expr>>,
3779    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3780    /// expands `group_by` to every non-aggregate SELECT-list item
3781    /// before the executor runs. Mutually exclusive with an
3782    /// explicit `group_by` list (the parser sets exactly one).
3783    pub group_by_all: bool,
3784    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3785    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3786    /// aggregate executor resolves them through the same synthetic
3787    /// schema used for the SELECT items.
3788    pub having: Option<Expr>,
3789    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3790    /// itself a `SelectStatement` with `order_by = None` and `limit =
3791    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3792    /// top of the chain).
3793    pub unions: Vec<(UnionKind, SelectStatement)>,
3794    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3795    /// Keys are matched left-to-right: first key decides, ties break
3796    /// to the second, etc.
3797    pub order_by: Vec<OrderBy>,
3798    /// `LIMIT <n>` — bound on row output. `n` is an integer
3799    /// literal **or** (v7.9.24) a placeholder `$N` resolved
3800    /// against the prepared-statement Bind values. mailrs
3801    /// migration follow-up H2.
3802    pub limit: Option<LimitExpr>,
3803    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3804    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3805    pub offset: Option<LimitExpr>,
3806    /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3807    /// (SQL:2008). When true and an ORDER BY is present, the
3808    /// executor extends past the LIMIT-truncated tail to include
3809    /// every row whose ORDER BY key equals the last-kept row's
3810    /// key. Requires an ORDER BY; the executor errors otherwise
3811    /// (matching PG's `WITH TIES` rule). The parser was already
3812    /// accepting `WITH TIES` since Phase 5.1; this field captures
3813    /// the choice so the executor can act on it.
3814    pub limit_with_ties: bool,
3815    /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3816    /// that NOTHING referenced. PG analyses every definition whether
3817    /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3818    /// and silently succeeded here — the referenced ones get their columns
3819    /// resolved through the WindowFunction nodes they were inlined into,
3820    /// and the unreferenced ones used to be dropped at parse, unexamined.
3821    /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3822    ///
3823    /// Not part of `Display`: an unreferenced definition has no effect on
3824    /// the result, so a deparsed body (a stored view) omits it.
3825    pub window_check_exprs: Vec<Expr>,
3826}
3827
3828impl Expr {
3829    /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3830    /// directly inside this expression to `f`. `f` receives each nested
3831    /// statement once; descending further (into that statement's own
3832    /// clauses) is the caller's job, which keeps this walk finite and
3833    /// lets the caller order the recursion.
3834    ///
3835    /// The match is deliberately **wildcard-free**: a new `Expr` variant
3836    /// does not compile until it says whether it can carry a subquery.
3837    /// The row-count resolution pass is built on this, and a shape it
3838    /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3839    /// which every row-count reader would take as "no limit", i.e. the
3840    /// whole table. Compile-time exhaustiveness is what rules that out.
3841    /// Iterative on purpose. Expression trees here get deep (long
3842    /// boolean chains, big IN lists), and this walk is on the path of
3843    /// every statement; recursing would add a frame per node to a stack
3844    /// budget the engine already runs close to — a depth guard that runs
3845    /// on a deliberately small stack caught exactly that. Depth costs
3846    /// heap here instead.
3847    pub fn for_each_subquery_mut<E>(
3848        &mut self,
3849        f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3850    ) -> Result<(), E> {
3851        let mut stack: Vec<&mut Self> = alloc::vec![self];
3852        while let Some(e) = stack.pop() {
3853            match e {
3854                Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3855                Self::NamedArg { expr, .. }
3856                | Self::Collate { expr, .. }
3857                | Self::Variadic(expr)
3858                | Self::Unary { expr, .. }
3859                | Self::Cast { expr, .. }
3860                | Self::FieldAccess { base: expr, .. }
3861                | Self::IsNull { expr, .. }
3862                | Self::BoolTest { expr, .. }
3863                | Self::Extract { source: expr, .. } => stack.push(expr),
3864                Self::Binary { lhs, rhs, .. } => {
3865                    stack.push(lhs);
3866                    stack.push(rhs);
3867                }
3868                Self::Like { expr, pattern, .. } => {
3869                    stack.push(expr);
3870                    stack.push(pattern);
3871                }
3872                Self::ArraySubscript { target, index } => {
3873                    stack.push(target);
3874                    stack.push(index);
3875                }
3876                Self::ArraySlice { target, lo, hi } => {
3877                    stack.push(target);
3878                    stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
3879                }
3880                Self::AnyAll { expr, array, .. } => {
3881                    stack.push(expr);
3882                    stack.push(array);
3883                }
3884                Self::FunctionCall { args, .. } | Self::Array(args) => {
3885                    stack.extend(args.iter_mut());
3886                }
3887                Self::AggregateOrdered {
3888                    call,
3889                    order_by,
3890                    filter,
3891                    ..
3892                } => {
3893                    stack.push(call);
3894                    stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
3895                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3896                }
3897                Self::WindowFunction {
3898                    args,
3899                    partition_by,
3900                    order_by,
3901                    filter,
3902                    ..
3903                } => {
3904                    // `frame` bounds hold folded numbers / interval
3905                    // parts, never expressions — nothing to visit there.
3906                    stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
3907                    stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
3908                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3909                }
3910                Self::InList { expr, list, .. } => {
3911                    stack.push(expr);
3912                    stack.extend(list.iter_mut());
3913                }
3914                Self::Case {
3915                    operand,
3916                    branches,
3917                    else_branch,
3918                } => {
3919                    stack.extend(
3920                        operand
3921                            .iter_mut()
3922                            .chain(else_branch.iter_mut())
3923                            .map(|b| &mut **b),
3924                    );
3925                    for (when, then) in branches.iter_mut() {
3926                        stack.push(when);
3927                        stack.push(then);
3928                    }
3929                }
3930                Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
3931                Self::InSubquery { expr, subquery, .. } => {
3932                    stack.push(expr);
3933                    f(subquery)?;
3934                }
3935                Self::RowInSubquery { row, subquery, .. }
3936                | Self::RowCmpSubquery { row, subquery, .. } => {
3937                    stack.extend(row.iter_mut());
3938                    f(subquery)?;
3939                }
3940            }
3941        }
3942        Ok(())
3943    }
3944}
3945
3946/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
3947/// time or a placeholder `$N` resolved during extended-query
3948/// Bind. mailrs migration follow-up H2.
3949///
3950/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
3951/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
3952/// made the compiler point at every site that used to duplicate a
3953/// row-count out of the AST, which is exactly the set that must not
3954/// bypass the resolution pre-pass.
3955#[derive(Debug, Clone, PartialEq)]
3956pub enum LimitExpr {
3957    /// `LIMIT 10` — value known at parse time.
3958    Literal(u32),
3959    /// `LIMIT $N` — the 1-based parameter index, resolved against
3960    /// the bind values when the prepared statement executes.
3961    Placeholder(u16),
3962    /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
3963    /// greatest(2,3)`: a row-count expression that isn't constant, so
3964    /// it can't be folded at parse time. Evaluated once, before
3965    /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
3966    /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
3967    /// "no limit"). **No execution path may see this variant** —
3968    /// `as_literal` would report `None`, which every row-count reader
3969    /// takes to mean "unlimited", i.e. the whole table.
3970    Expr(alloc::boxed::Box<Expr>),
3971}
3972
3973impl fmt::Display for LimitExpr {
3974    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3975        match self {
3976            Self::Literal(n) => write!(f, "{n}"),
3977            Self::Placeholder(n) => write!(f, "${n}"),
3978            // Parenthesised so the round-trip text re-parses as one
3979            // row-count expression (`LIMIT (SELECT 4)`), which is also
3980            // the only spelling `FETCH FIRST` accepts.
3981            Self::Expr(e) => write!(f, "({e})"),
3982        }
3983    }
3984}
3985
3986impl LimitExpr {
3987    /// Convenience for the simple-query path where no placeholders
3988    /// can possibly exist. Returns the literal value or `None` if
3989    /// this is a placeholder (caller must surface as Unsupported).
3990    ///
3991    /// v7.39 (round 305) — `None` is read by every row-count consumer as
3992    /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
3993    /// therefore silently return the whole table, so the engine's
3994    /// `resolve_limit_exprs` pre-pass rewrites the variant away before
3995    /// dispatch. The assertion makes a missed nesting site fail loudly
3996    /// in every test build rather than quietly widening a result set.
3997    #[must_use]
3998    pub fn as_literal(&self) -> Option<u32> {
3999        match self {
4000            Self::Literal(n) => Some(*n),
4001            Self::Placeholder(_) => None,
4002            Self::Expr(_) => {
4003                debug_assert!(
4004                    false,
4005                    "LimitExpr::Expr reached execution — resolve_limit_exprs \
4006                     missed a nesting site; treating it as `no limit` would \
4007                     return every row"
4008                );
4009                None
4010            }
4011        }
4012    }
4013}
4014
4015/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
4016/// the engine's `substitute_placeholders` pass these are
4017/// always Literal; in the simple-query path a Placeholder
4018/// shape returns None (executor surfaces as
4019/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
4020impl SelectStatement {
4021    #[must_use]
4022    pub fn limit_literal(&self) -> Option<u32> {
4023        self.limit.as_ref().and_then(LimitExpr::as_literal)
4024    }
4025    #[must_use]
4026    pub fn offset_literal(&self) -> Option<u32> {
4027        self.offset.as_ref().and_then(LimitExpr::as_literal)
4028    }
4029}
4030
4031#[derive(Debug, Clone, PartialEq)]
4032pub struct Cte {
4033    pub name: String,
4034    /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
4035    /// classical case) or a data-modifying statement
4036    /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
4037    /// CTE semantics. The modifying body's RETURNING projection
4038    /// becomes the materialised CTE table the outer query can
4039    /// reference; the modifying statement runs once before the
4040    /// outer query, within the same transaction.
4041    pub body: CteBody,
4042    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
4043    /// RECURSIVE keyword. Applies to every CTE in the clause per
4044    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
4045    /// allowed; the engine just runs it once.
4046    pub recursive: bool,
4047    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
4048    /// non-empty, these override the body's output column names
4049    /// position-by-position; the engine errors out if the count
4050    /// doesn't match the body's projection width.
4051    pub column_overrides: Vec<String>,
4052    /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
4053    /// SET seqcol` on a recursive CTE. Desugared at parse time into an
4054    /// extra ordering column on the body (see `rewrite_search_and_cycle`).
4055    pub search: Option<SearchClause>,
4056    /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
4057    /// USING pathcol` cycle detection, desugared at parse time.
4058    pub cycle: Option<CycleClause>,
4059}
4060
4061/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
4062#[derive(Debug, Clone, PartialEq)]
4063pub struct SearchClause {
4064    /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
4065    pub depth_first: bool,
4066    /// The CTE output columns the search orders by.
4067    pub by_columns: Vec<String>,
4068    /// The new column holding the ordering key (a row-array for depth,
4069    /// a `(depth, keys…)` row for breadth).
4070    pub set_column: String,
4071}
4072
4073/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
4074#[derive(Debug, Clone, PartialEq)]
4075pub struct CycleClause {
4076    /// Columns whose repetition along a path marks a cycle.
4077    pub columns: Vec<String>,
4078    /// The new boolean-ish column set to `mark_value` on a cycle.
4079    pub mark_column: String,
4080    /// Value written to `mark_column` when a cycle is detected (default
4081    /// `true`); `default_value` otherwise. PG allows any type; SPG carries
4082    /// them as literals.
4083    pub mark_value: Option<Literal>,
4084    pub default_value: Option<Literal>,
4085    /// The new column accumulating the visited-row path array.
4086    pub path_column: String,
4087}
4088
4089/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
4090/// (Insert / Update / Delete with optional RETURNING). The
4091/// data-modifying variants must carry a RETURNING projection for the
4092/// outer query to reference the CTE alias by; an empty RETURNING is
4093/// only valid if no outer reference materialises (rare — typically
4094/// caught at planning).
4095#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
4096#[derive(Debug, Clone, PartialEq)]
4097pub enum CteBody {
4098    Select(SelectStatement),
4099    Insert(Box<InsertStatement>),
4100    Update(Box<UpdateStatement>),
4101    Delete(Box<DeleteStatement>),
4102    /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
4103    /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
4104    Merge(Box<MergeStatement>),
4105}
4106
4107impl CteBody {
4108    /// Convenience accessor used by classical (read-only) CTE
4109    /// callsites that still expect a SELECT body. Returns None for
4110    /// data-modifying CTEs; callers must explicitly route those
4111    /// through `exec_with_ctes`'s modifying branch.
4112    #[must_use]
4113    pub fn as_select(&self) -> Option<&SelectStatement> {
4114        match self {
4115            Self::Select(s) => Some(s),
4116            _ => None,
4117        }
4118    }
4119
4120    #[must_use]
4121    pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
4122        match self {
4123            Self::Select(s) => Some(s),
4124            _ => None,
4125        }
4126    }
4127
4128    #[must_use]
4129    pub fn is_modifying(&self) -> bool {
4130        !matches!(self, Self::Select(_))
4131    }
4132}
4133
4134#[derive(Debug, Clone, PartialEq)]
4135pub struct OrderBy {
4136    pub expr: Expr,
4137    /// `false` = ASC (default), `true` = DESC.
4138    pub desc: bool,
4139    /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
4140    /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
4141    /// NULLS FIRST for DESC); the engine resolves the effective
4142    /// value via `nulls_first.unwrap_or(desc)`.
4143    pub nulls_first: Option<bool>,
4144    /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
4145    /// It lives here rather than in the expression for the same reason
4146    /// `desc` does: at an ORDER BY key a collation is ordering
4147    /// information, and nothing downstream of the sort needs it. A new
4148    /// `Expr` variant would instead put a new arm on `eval_expr`, which
4149    /// this repo has measured to overflow the debug stack.
4150    ///
4151    /// `None` means none was written, and the key falls back to whatever
4152    /// its COLUMN declares — which is every key that existed before this.
4153    pub collation: Option<String>,
4154}
4155
4156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4157pub enum UnionKind {
4158    /// `UNION` — dedupes the combined set.
4159    Distinct,
4160    /// `UNION ALL` — concatenates without dedup.
4161    All,
4162    /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
4163    /// present on both sides.
4164    Intersect,
4165    /// `INTERSECT ALL` — multiset intersection (min per-row count).
4166    IntersectAll,
4167    /// `EXCEPT` — distinct left rows absent from the right.
4168    Except,
4169    /// `EXCEPT ALL` — multiset subtraction.
4170    ExceptAll,
4171}
4172
4173#[derive(Debug, Clone, PartialEq)]
4174pub enum SelectItem {
4175    Wildcard,
4176    /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
4177    /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
4178    /// `NEW` pseudo-relation).
4179    QualifiedWildcard(String),
4180    Expr {
4181        expr: Expr,
4182        alias: Option<String>,
4183    },
4184}
4185
4186#[derive(Debug, Clone, PartialEq)]
4187pub struct TableRef {
4188    pub name: String,
4189    pub alias: Option<String>,
4190    /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
4191    /// children.
4192    ///
4193    /// The keyword used to be absorbed at parse time, on the reasoning
4194    /// that SPG's inheritance children are separate relations a plain
4195    /// scan does not descend into — so ONLY already described what the
4196    /// scan did. That stopped being true when a partition parent
4197    /// started unioning its children: measured, `SELECT count(*) FROM
4198    /// ONLY <partitioned parent>` answered 2 where PG answers 0.
4199    pub only: bool,
4200    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
4201    /// When `Some(id)`, the scan restricts to rows that live in
4202    /// segment `<id>` only — useful for forensic inspection of a
4203    /// specific freezer-emitted segment without exposing the hot
4204    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
4205    /// is STABILITY carve-out for v6.10 — needs the freezer to
4206    /// stamp each segment with a wall-clock at creation time.
4207    pub as_of_segment: Option<u32>,
4208    /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
4209    /// source. When `Some`, `name` is the alias (defaulting to
4210    /// `"unnest"` when no `AS` is given) and the engine builds a
4211    /// synthetic single-column table by evaluating the expression
4212    /// once at SELECT entry. Each TEXT[] element becomes one row;
4213    /// NULL elements become NULL cells. v7.11 supported
4214    /// uncorrelated UNNEST only as the FROM primary; v7.13.2
4215    /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
4216    /// position (cross-join with regular tables).
4217    pub unnest_expr: Option<Box<Expr>>,
4218    /// v7.13.2 — mailrs round-6 S5. PG-standard
4219    /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
4220    /// when non-empty, the first entry overrides the projected
4221    /// column name for the unnested column. Empty = fall back to
4222    /// the table alias (pre-v7.13.2 behaviour).
4223    pub unnest_column_aliases: Vec<String>,
4224    /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
4225    /// row-stream gains a trailing BIGINT column counting rows
4226    /// from 1 in element order. PG names it `ordinality`; a second
4227    /// entry in the column-alias list renames it.
4228    pub with_ordinality: bool,
4229    /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
4230    /// [, step])` set-returning source. When `Some`, the engine
4231    /// materialises a single-column virtual table by stepping
4232    /// `start` to `stop` inclusive. Args are the literal arg list
4233    /// (2 for default-step, 3 for explicit-step). Supports:
4234    ///   * SmallInt / Int / BigInt with integer step (default = 1)
4235    ///   * Timestamp with INTERVAL step (PG date-range pattern)
4236    /// Mutually exclusive with `unnest_expr` — both populate the
4237    /// same downstream dispatch slot. `name` defaults to
4238    /// `"generate_series"` when no alias is provided.
4239    pub generate_series_args: Option<Vec<Expr>>,
4240    /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
4241    /// table. When `Some`, the TableRef is a parenthesised SELECT
4242    /// that may reference columns from the preceding FROM items
4243    /// (correlated derived table). The executor materialises the
4244    /// subquery per left-row, substituting outer-column references
4245    /// against the current join row's values before running the
4246    /// inner SELECT, then cross-joins the result back.
4247    /// Mutually exclusive with `name` / `unnest_expr` /
4248    /// `generate_series_args`.
4249    pub lateral_subquery: Option<Box<SelectStatement>>,
4250    /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
4251    /// function as a FROM item. PG semantics: for each key/value
4252    /// pair in the JSONB object argument, emit one (key TEXT,
4253    /// value TEXT) row. When prefixed by `LATERAL` and joined via
4254    /// `CROSS JOIN LATERAL`, the argument may reference columns
4255    /// from a preceding FROM item, in which case the executor
4256    /// evaluates `<expr>` per outer row.
4257    /// Mutually exclusive with `unnest_expr` / `generate_series_args`
4258    /// / `lateral_subquery`. The optional `LATERAL` keyword does not
4259    /// require a separate flag — the executor evaluates per-row
4260    /// whenever the join sits in a JoinKind context.
4261    ///
4262    /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
4263    /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
4264    /// `json_each` / `json_each_text`) so the executor picks the
4265    /// value-column rendering (JSON text vs unwrapped text).
4266    pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
4267    /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
4268    /// function channel: `(lowercase fn name, args)`. Carries
4269    /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
4270    /// dispatches by name.
4271    pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
4272    /// v7.39 (read01 round 78) — this FROM item is a call to a function that
4273    /// returns a BASE type, so the item's row type IS that scalar: a whole-row
4274    /// reference to it yields the value, not a one-field composite
4275    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
4276    /// desugared shape is indistinguishable from a hand-written
4277    /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
4278    /// only the parser knows which one it built, so it says so here.
4279    pub scalar_fn_item: bool,
4280    /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
4281    /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
4282    /// target-list SRFs follow — see round 67). The array-returning family keeps
4283    /// its own lowering; this channel carries the ones that have no array form
4284    /// (`generate_series`, a user `RETURNS SETOF` function).
4285    pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
4286    /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4287    /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4288    /// tables (implicit LATERAL, like every SRF channel). Executed by
4289    /// walking the row path over the parsed doc, then each column's
4290    /// path per row-item; NESTED expands as a per-parent outer join.
4291    pub json_table: Option<Box<JsonTable>>,
4292}
4293
4294/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4295#[derive(Debug, Clone, PartialEq)]
4296pub struct JsonTable {
4297    /// The document expression (jsonb/json/text). May reference outer
4298    /// columns → implicit LATERAL.
4299    pub doc: Box<Expr>,
4300    /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4301    /// match is one row's context item.
4302    pub row_path: String,
4303    /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4304    pub columns: Vec<JsonTableColumn>,
4305    /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4306    pub passing: Vec<(String, Expr)>,
4307}
4308
4309/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4310#[derive(Debug, Clone, PartialEq)]
4311pub enum JsonTableColumn {
4312    /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4313    Ordinality { name: String },
4314    /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4315    /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4316    /// `<name> <type> EXISTS [PATH '<p>']`.
4317    Regular {
4318        name: String,
4319        ty: ColumnTypeName,
4320        /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4321        path: String,
4322        /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4323        exists: bool,
4324        /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4325        format_json: bool,
4326        /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4327        wrapper: bool,
4328        /// Behaviour when the path matches nothing (default NULL).
4329        on_empty: JsonTableOnBehavior,
4330        /// Behaviour when coercion fails (default NULL).
4331        on_error: JsonTableOnBehavior,
4332    },
4333    /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4334    /// row like a LEFT JOIN (a parent with no nested match still emits one
4335    /// row, nested cols NULL).
4336    Nested {
4337        path: String,
4338        columns: Vec<JsonTableColumn>,
4339    },
4340}
4341
4342/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4343#[derive(Debug, Clone, PartialEq)]
4344pub enum JsonTableOnBehavior {
4345    /// Default: the column value is NULL.
4346    Null,
4347    /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4348    Error,
4349    /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4350    Default(Box<Expr>),
4351}
4352
4353/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4354/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4355/// joins evaluate left-associatively in nested-loop order.
4356#[derive(Debug, Clone, PartialEq)]
4357pub struct FromClause {
4358    pub primary: TableRef,
4359    pub joins: Vec<FromJoin>,
4360}
4361
4362#[derive(Debug, Clone, PartialEq)]
4363pub struct FromJoin {
4364    pub kind: JoinKind,
4365    pub table: TableRef,
4366    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4367    pub on: Option<Expr>,
4368    /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4369    /// USING column list so the executor can perform PG's column-merge
4370    /// (the join columns collapse to a single unqualified output column,
4371    /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4372    /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4373    /// USING into an equivalent `on` predicate so the join filter/count
4374    /// path works unchanged; `using_cols` drives only the output-shape
4375    /// rewrite. Empty/`None` for `ON` and CROSS joins.
4376    pub using_cols: Option<Vec<String>>,
4377    /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4378    /// column names are not known until the table schemas are available
4379    /// (parse time is schema-less), so the parser only sets this flag and
4380    /// leaves `on`/`using_cols` empty; the engine resolves the common
4381    /// columns at execution time, synthesises the `on` predicate + the
4382    /// USING column-merge, and clears the flag. If there are no common
4383    /// columns PG treats it as a CROSS join.
4384    pub natural: bool,
4385}
4386
4387#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4388pub enum JoinKind {
4389    Inner,
4390    Left,
4391    Cross,
4392    /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4393    /// NULL-filling the left (drive) columns on unmatched right rows.
4394    /// The executor runs the LEFT algorithm's mirror: it tracks which
4395    /// peer rows matched and emits the unmatched ones with a NULL-left
4396    /// tuple after the probe loop. Output column order is unchanged
4397    /// (left-table cols then right-table cols).
4398    Right,
4399    /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4400    /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4401    FullOuter,
4402    /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4403    /// once, paired with the first peer row that satisfies the ON. Not
4404    /// reachable from SQL — the EXISTS pull-up emits it, which is what
4405    /// frees positive EXISTS from the round-721 uniqueness gate (an
4406    /// INNER join would multiply the outer rows; a semi join cannot).
4407    Semi,
4408}
4409
4410#[derive(Debug, Clone, PartialEq)]
4411pub enum Expr {
4412    Literal(Literal),
4413    /// v7.39.2 — `<expr> COLLATE <name>`: the collation this expression
4414    /// compares under, whatever the column or the database says.
4415    ///
4416    /// The parser used to refuse the locale names in this position and
4417    /// SILENTLY ABSORB the byte-order ones, so `'a' COLLATE "C" < 'B'`
4418    /// answered `t` where PostgreSQL 18.6 answers `f` — the one family
4419    /// it let through is the one where dropping it changes the answer.
4420    ///
4421    /// Whether dropping is safe depends on the DATABASE's own collation,
4422    /// which the parser cannot see: under `SPG_LC_COLLATE=C` absorbing
4423    /// `COLLATE "C"` is exactly right. So the name rides along and the
4424    /// engine, which knows, decides.
4425    Collate {
4426        expr: Box<Expr>,
4427        collation: String,
4428    },
4429    Column(ColumnName),
4430    /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4431    /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4432    /// callee's declared parameter names, and a user function's live in the
4433    /// catalog — which the parser cannot see. So the name rides along in the
4434    /// tree and the evaluator, which has the catalog, does the reordering.
4435    /// Appears only inside a `FunctionCall`'s argument list.
4436    NamedArg {
4437        name: String,
4438        expr: Box<Expr>,
4439    },
4440    /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4441    /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4442    /// expression evaluates to an array whose elements the evaluator splices
4443    /// into the call as individual trailing arguments. Appears only inside a
4444    /// `FunctionCall`'s argument list.
4445    Variadic(Box<Expr>),
4446    /// v6.1.1 — `$N` parameter placeholder for the extended query
4447    /// protocol. The number is 1-based per PostgreSQL convention.
4448    /// Evaluation looks up `params[N-1]` from the prepared-statement
4449    /// bind buffer; out-of-range indices raise a runtime error
4450    /// (same shape as a column-not-found miss).
4451    Placeholder(u16),
4452    Binary {
4453        lhs: Box<Expr>,
4454        op: BinOp,
4455        rhs: Box<Expr>,
4456    },
4457    Unary {
4458        op: UnOp,
4459        expr: Box<Expr>,
4460    },
4461    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4462    /// TEXT, BOOL targets; engine coerces at evaluation time.
4463    Cast {
4464        expr: Box<Expr>,
4465        target: CastTarget,
4466    },
4467    /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4468    /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4469    /// whole-row reference, or a composite-returning function); `field` names
4470    /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4471    /// column names for a whole-row). Only the parenthesised form reaches
4472    /// here — a bare `a.b` is parsed as a qualified column reference.
4473    FieldAccess {
4474        base: Box<Expr>,
4475        field: String,
4476    },
4477    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4478    IsNull {
4479        expr: Box<Expr>,
4480        negated: bool,
4481    },
4482    /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4483    /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4484    /// `Some(false)` for FALSE and `None` for UNKNOWN.
4485    ///
4486    /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4487    /// The semantics were right, but the AST then had no way to say what
4488    /// the user wrote, so every renderer printed the lowering:
4489    /// `CHECK ((a > 1) IS TRUE)` came back as
4490    /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4491    /// dumped view lost the form too.
4492    BoolTest {
4493        expr: Box<Expr>,
4494        value: Option<bool>,
4495        negated: bool,
4496    },
4497    /// Function call `name(args...)`. v1.4 supports a small built-in set
4498    /// (length, upper, lower, abs, coalesce); unknown names error at eval
4499    /// time so the parser stays open for v1.5 aggregates.
4500    FunctionCall {
4501        name: String,
4502        args: Vec<Expr>,
4503    },
4504    /// v7.24 (mailrs round-16 A) — an aggregate call with an
4505    /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4506    /// Wraps the plain [`Expr::FunctionCall`] so every existing
4507    /// FunctionCall consumer stays untouched; only the aggregate
4508    /// executor (and the expression walkers) know the wrapper.
4509    /// Non-aggregate evaluation contexts reject it at eval time.
4510    AggregateOrdered {
4511        call: Box<Expr>,
4512        order_by: Vec<OrderBy>,
4513        /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4514        /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4515        /// aggregate modifier so plain FunctionCall stays untouched.
4516        distinct: bool,
4517        /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4518        /// Only the rows where `cond` is true contribute to this
4519        /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4520        /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4521        /// END)`, which is faithful for NULL-ignoring aggregates but
4522        /// WRONG for `array_agg` (it would collect a NULL per excluded
4523        /// row). The executor instead skips excluded rows before
4524        /// accumulation, which is correct for every aggregate.
4525        filter: Option<Box<Expr>>,
4526    },
4527    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4528    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4529    /// the next char (so `\%` matches a literal `%`).
4530    Like {
4531        expr: Box<Expr>,
4532        pattern: Box<Expr>,
4533        negated: bool,
4534        /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4535        /// match. PG folds both operands.
4536        case_insensitive: bool,
4537    },
4538    /// v4.12 window function call: `name(args) OVER (PARTITION BY
4539    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4540    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4541    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4542    /// unordered windows and "from start of partition through
4543    /// current row" for ordered windows — no explicit ROWS /
4544    /// RANGE clause in v4.12 MVP.
4545    WindowFunction {
4546        name: String,
4547        args: Vec<Expr>,
4548        partition_by: Vec<Expr>,
4549        /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4550        /// (None = PG default, same contract as [`OrderBy`]).
4551        order_by: Vec<(
4552            Expr,
4553            bool,         /* desc */
4554            Option<bool>, /* nulls_first */
4555        )>,
4556        /// v4.20 explicit frame. `None` means "use the default":
4557        /// whole-partition when unordered, running aggregate from
4558        /// partition start through current row when ordered.
4559        frame: Option<WindowFrame>,
4560        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4561        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4562        /// `Respect` (PG / ANSI default — NULLs participate). Other
4563        /// window functions ignore this flag.
4564        null_treatment: NullTreatment,
4565        /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4566        /// = no FILTER. Only aggregate window functions honor it; the
4567        /// predicate restricts which peer rows contribute within the frame.
4568        filter: Option<Box<Expr>>,
4569    },
4570    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4571    /// position. Must return exactly one row × one column at eval
4572    /// time; the engine errors out otherwise. Uncorrelated only —
4573    /// the inner SELECT cannot reference outer columns.
4574    ScalarSubquery(Box<SelectStatement>),
4575    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4576    /// projection is ignored; only row-count matters.
4577    Exists {
4578        subquery: Box<SelectStatement>,
4579        negated: bool,
4580    },
4581    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4582    /// project exactly one column; membership is tested by Eq
4583    /// against each row's value (NULL handling follows ANSI:
4584    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4585    InSubquery {
4586        expr: Box<Expr>,
4587        subquery: Box<SelectStatement>,
4588        negated: bool,
4589    },
4590    /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4591    /// against a multi-column subquery. Row comparisons against a *list*
4592    /// decompose to OR-of-AND at parse time, but the subquery form can't
4593    /// (its rows are only known at runtime), so this survives as its own
4594    /// node evaluated with PG's row-comparison three-valued logic.
4595    RowInSubquery {
4596        row: Vec<Expr>,
4597        subquery: Box<SelectStatement>,
4598        negated: bool,
4599    },
4600    /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4601    /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4602    /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4603    /// subquery form can't, so it survives as its own node. The subquery
4604    /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4605    RowCmpSubquery {
4606        row: Vec<Expr>,
4607        op: BinOp,
4608        subquery: Box<SelectStatement>,
4609    },
4610    /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4611    /// list. Both the parser's literal-list path and the engine's
4612    /// IN-subquery materialisation used to desugar into a left-deep
4613    /// OR-Eq chain, so expression depth scaled with the element count
4614    /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4615    /// (recursive eval AND recursive Box drop) and aborted embedding
4616    /// host processes. The flat node keeps depth constant: eval is an
4617    /// iterative scan with PG three-valued logic, drop is a Vec drop.
4618    InList {
4619        expr: Box<Expr>,
4620        list: Vec<Expr>,
4621        negated: bool,
4622    },
4623    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4624    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4625    /// because the `FROM` keyword is what separates the two halves,
4626    /// not a comma.
4627    Extract {
4628        field: ExtractField,
4629        source: Box<Expr>,
4630    },
4631    /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4632    /// element is evaluated independently; NULLs are allowed.
4633    /// v7.10 supports only single-dimension TEXT[] semantically;
4634    /// non-text elements coerce at engine evaluation time when
4635    /// the surrounding context (column type / cast) makes the
4636    /// target clear.
4637    Array(Vec<Expr>),
4638    /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4639    /// engine returns NULL for out-of-range indices.
4640    ArraySubscript {
4641        target: Box<Expr>,
4642        index: Box<Expr>,
4643    },
4644    /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4645    /// inclusive; a missing bound extends to that end of the
4646    /// array and out-of-range bounds clamp. Returns an array of
4647    /// the same element type.
4648    ArraySlice {
4649        target: Box<Expr>,
4650        lo: Option<Box<Expr>>,
4651        hi: Option<Box<Expr>>,
4652    },
4653    /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4654    /// operator is the comparison binary op (Eq / Ne / Lt / …);
4655    /// the engine desugars: `ANY` returns true if any element
4656    /// satisfies; `ALL` returns true only if every element does.
4657    /// NULL handling follows PG's three-valued logic.
4658    AnyAll {
4659        expr: Box<Expr>,
4660        op: BinOp,
4661        array: Box<Expr>,
4662        /// `true` = ANY, `false` = ALL.
4663        is_any: bool,
4664    },
4665    /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4666    /// (searched form, `operand` is None) and
4667    /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4668    /// `operand` is the lead expression compared against each
4669    /// branch's match). Each `(when_expr, then_expr)` branch
4670    /// stays as written; engine short-circuits on the first match.
4671    /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4672    /// mailrs round-5 G9.
4673    Case {
4674        operand: Option<Box<Expr>>,
4675        branches: Vec<(Expr, Expr)>,
4676        else_branch: Option<Box<Expr>>,
4677    },
4678}
4679
4680/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4681/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4682/// in the offset walk. `Ignore` causes the function to skip NULL
4683/// values in the argument expression, returning the next non-NULL.
4684#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4685pub enum NullTreatment {
4686    #[default]
4687    Respect,
4688    Ignore,
4689}
4690
4691/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4692/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4693/// where end implicitly = CURRENT ROW.
4694#[derive(Debug, Clone, PartialEq, Eq)]
4695pub struct WindowFrame {
4696    pub kind: FrameKind,
4697    pub start: FrameBound,
4698    pub end: Option<FrameBound>,
4699    /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4700    /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4701    /// no-op; CURRENT ROW drops the current row from the frame.
4702    pub exclude: FrameExclusion,
4703}
4704
4705#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4706pub enum FrameExclusion {
4707    /// Default — exclude nothing.
4708    #[default]
4709    NoOthers,
4710    /// Drop the current row from the frame.
4711    CurrentRow,
4712    /// Drop the current row's whole peer group.
4713    Group,
4714    /// Drop the current row's peers but keep the current row.
4715    Ties,
4716}
4717
4718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4719pub enum FrameKind {
4720    Rows,
4721    Range,
4722    /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4723    /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4724    /// bounds (no explicit integer offsets) GROUPS behaves identically
4725    /// to RANGE — both consult the peer-group of the current row.
4726    /// Integer offsets are not yet supported; the executor rejects
4727    /// them at run time.
4728    Groups,
4729}
4730
4731#[derive(Debug, Clone, PartialEq, Eq)]
4732pub enum FrameBound {
4733    UnboundedPreceding,
4734    OffsetPreceding(u64),
4735    CurrentRow,
4736    OffsetFollowing(u64),
4737    UnboundedFollowing,
4738    /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4739    /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4740    /// interval is folded to its (months, days, micros) components at
4741    /// parse time.
4742    IntervalPreceding {
4743        months: i32,
4744        days: i32,
4745        micros: i64,
4746    },
4747    IntervalFollowing {
4748        months: i32,
4749        days: i32,
4750        micros: i64,
4751    },
4752}
4753
4754impl fmt::Display for FrameBound {
4755    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4756        match self {
4757            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4758            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4759            Self::CurrentRow => f.write_str("CURRENT ROW"),
4760            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4761            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4762            Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4763            Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4764        }
4765    }
4766}
4767
4768#[derive(Debug, Clone, PartialEq, Eq)]
4769pub enum ExtractField {
4770    Year,
4771    Month,
4772    Day,
4773    Hour,
4774    Minute,
4775    Second,
4776    Microsecond,
4777    /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4778    /// SPG keeps the integer convention — truncated seconds).
4779    Epoch,
4780    /// Day of week, 0 = Sunday … 6 = Saturday.
4781    Dow,
4782    /// ISO day of week, 1 = Monday … 7 = Sunday.
4783    Isodow,
4784    /// Day of year, 1-366.
4785    Doy,
4786    /// ISO 8601 week number, 1-53.
4787    Week,
4788    /// ISO 8601 week-numbering year (pairs with `Week`).
4789    Isoyear,
4790    /// Quarter, 1-4.
4791    Quarter,
4792    /// Year divided by 10 (floor).
4793    Decade,
4794    /// Century — 2001-2100 is century 21.
4795    Century,
4796    /// Millennium — 2001-3000 is millennium 3.
4797    Millennium,
4798    /// Julian day number (truncated for timestamps).
4799    Julian,
4800    /// Seconds and fraction in milliseconds (ss·1000 + frac).
4801    Millisecond,
4802    /// UTC offset in seconds — SPG sessions run UTC, so 0.
4803    Timezone,
4804    /// Hour component of the UTC offset — 0.
4805    TimezoneHour,
4806    /// Minute component of the UTC offset — 0.
4807    TimezoneMinute,
4808    /// v7.39 (round 253) — a field name the parser does not know. PG
4809    /// resolves EXTRACT fields at RUNTIME and reports them with the
4810    /// source type (`unit "nosuch" not recognized for type timestamp
4811    /// without time zone`, 22023), so the parser carries the raw name
4812    /// instead of rejecting.
4813    Other(String),
4814}
4815
4816impl fmt::Display for ExtractField {
4817    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4818        f.write_str(match self {
4819            Self::Year => "YEAR",
4820            Self::Month => "MONTH",
4821            Self::Day => "DAY",
4822            Self::Hour => "HOUR",
4823            Self::Minute => "MINUTE",
4824            Self::Second => "SECOND",
4825            Self::Microsecond => "MICROSECOND",
4826            Self::Epoch => "EPOCH",
4827            Self::Dow => "DOW",
4828            Self::Isodow => "ISODOW",
4829            Self::Doy => "DOY",
4830            Self::Week => "WEEK",
4831            Self::Isoyear => "ISOYEAR",
4832            Self::Quarter => "QUARTER",
4833            Self::Decade => "DECADE",
4834            Self::Century => "CENTURY",
4835            Self::Millennium => "MILLENNIUM",
4836            Self::Julian => "JULIAN",
4837            Self::Millisecond => "MILLISECOND",
4838            Self::Timezone => "TIMEZONE",
4839            Self::TimezoneHour => "TIMEZONE_HOUR",
4840            Self::TimezoneMinute => "TIMEZONE_MINUTE",
4841            Self::Other(name) => return f.write_str(name),
4842        })
4843    }
4844}
4845
4846#[derive(Debug, Clone, PartialEq, Eq)]
4847pub enum CastTarget {
4848    Int,
4849    BigInt,
4850    Float,
4851    Text,
4852    Bool,
4853    Vector,
4854    Date,
4855    Timestamp,
4856    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4857    /// H3a. Engine reuses the existing runtime-interval / timestamp
4858    /// paths (parse the text input, return the matching Value).
4859    Interval,
4860    Timestamptz,
4861    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4862    /// types (v7.9.0); the cast just routes Text→Json with the
4863    /// requested OID for the wire layer.
4864    Json,
4865    Jsonb,
4866    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4867    /// compatibility; engine surfaces as Unsupported with a
4868    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4869    RegType,
4870    RegClass,
4871    /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
4872    /// the PG external array form `{a,b,NULL}`.
4873    TextArray,
4874    /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
4875    /// `{1,2,3}` or widens a `TextArray` whose elements are
4876    /// integer-shaped.
4877    IntArray,
4878    BigIntArray,
4879    /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
4880    /// external form text representation. Used by pg_dump output
4881    /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
4882    TsVector,
4883    TsQuery,
4884    /// v7.17.0 — `::uuid`. Decodes the LHS Text via
4885    /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
4886    /// unhyphenated, uppercase, and brace-wrapped forms); malformed
4887    /// input is a SQL error.
4888    Uuid,
4889    /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
4890    /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
4891    /// inputs pass through unchanged. Closes the mailrs D-pre #3
4892    /// reverse-acceptance gap — anywhere a PG schema writes
4893    /// `expr::bytea`, SPG now matches.
4894    Bytea,
4895    /// v7.37.5 ship triage — generic cast target for the long tail
4896    /// of PG type names the parser meets in `expr::TYPE` shapes that
4897    /// don't deserve their own enum variant. The engine routes these
4898    /// through `column_type_to_data_type` + the existing typed
4899    /// `coerce_value` dispatch, so adding a new PG type to SPG
4900    /// implicitly adds its cast-target form too — no parser change
4901    /// per type. The string carries the lowercase PG type ident
4902    /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
4903    /// a clear message when the type isn't known.
4904    Named(String),
4905}
4906
4907impl fmt::Display for CastTarget {
4908    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4909        f.write_str(match self {
4910            Self::Int => "int",
4911            Self::BigInt => "bigint",
4912            Self::Float => "float",
4913            Self::Text => "text",
4914            Self::Bool => "bool",
4915            Self::Vector => "vector",
4916            Self::Interval => "interval",
4917            Self::Timestamptz => "timestamptz",
4918            Self::Json => "json",
4919            Self::Jsonb => "jsonb",
4920            Self::RegType => "regtype",
4921            Self::RegClass => "regclass",
4922            Self::Date => "date",
4923            Self::Timestamp => "timestamp",
4924            Self::TextArray => "TEXT[]",
4925            Self::IntArray => "INT[]",
4926            Self::BigIntArray => "BIGINT[]",
4927            Self::TsVector => "tsvector",
4928            Self::TsQuery => "tsquery",
4929            Self::Uuid => "uuid",
4930            Self::Bytea => "bytea",
4931            // v7.37.5 — `Self::Named` carries its own canonical name.
4932            Self::Named(name) => return f.write_str(name),
4933        })
4934    }
4935}
4936
4937#[derive(Debug, Clone, PartialEq)]
4938pub enum Literal {
4939    Integer(i64),
4940    Float(f64),
4941    /// Exact decimal literal — a bare `12.34`-style token, kept as
4942    /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
4943    /// before it becomes a `Value::Numeric`. PG parses such literals as
4944    /// `numeric`, not `double precision`. (Scientific/huge literals stay
4945    /// `Float`.)
4946    Numeric {
4947        unscaled: i128,
4948        /// v7.39 (round 271) — widened to u16. At u8 a literal with more
4949        /// than 255 decimal places could not be represented, and the
4950        /// conversion's `.expect("lexer-validated decimal")` aborted the
4951        /// query with an internal error on SQL PG accepts.
4952        scale: u16,
4953    },
4954    /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
4955    /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
4956    /// `Value::NumericBig` at eval; previously such literals fell back to double.
4957    NumericBig(String),
4958    String(String),
4959    /// v7.38.8 — a temporal constant that has already been decoded.
4960    ///
4961    /// Without these the only way to carry one through the AST was as
4962    /// text, and a predicate comparing a `timestamp` column against a
4963    /// literal then coerced that text back into a timestamp ONCE PER
4964    /// ROW — 32 ns of the 52 a comparison cost, measured on a customer
4965    /// profile. `constfold` produced text for the same reason: its exit
4966    /// had nothing else to hand back.
4967    ///
4968    /// `text` keeps the spelling so `Display` round-trips byte for byte,
4969    /// the way `Interval` already does and for the same reason: this
4970    /// node is printed in EXPLAIN, in dumps and in error messages, and
4971    /// none of those should change because the value stopped being
4972    /// carried as a string. The enum already holds a `String` and an
4973    /// `i128`, so neither variant widens it.
4974    Timestamp {
4975        micros: i64,
4976        text: String,
4977    },
4978    /// Days since the epoch `Value::Date` counts from. See
4979    /// [`Literal::Timestamp`].
4980    Date {
4981        days: i32,
4982        text: String,
4983    },
4984    Bool(bool),
4985    Null,
4986    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
4987    Vector(Vec<f32>),
4988    /// TEXT[] value carried through the prepared-bind path
4989    /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
4990    /// text form, so the array rides the AST natively).
4991    TextArray(Vec<Option<String>>),
4992    /// INT[] value carried through the prepared-bind path.
4993    IntArray(Vec<Option<i32>>),
4994    /// BIGINT[] value carried through the prepared-bind path.
4995    BigIntArray(Vec<Option<i64>>),
4996    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
4997    /// Three independent dimensions: `months` (variable-length;
4998    /// year/month), `days` (fixed 86400 seconds at non-DST, but
4999    /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
5000    /// stays distinguishable), and `micros` (sub-day; can carry).
5001    /// `text` keeps the original spelling so Display round-trips
5002    /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
5003    Interval {
5004        months: i32,
5005        days: i32,
5006        micros: i64,
5007        text: String,
5008    },
5009}
5010
5011#[derive(Debug, Clone, PartialEq, Eq)]
5012pub struct ColumnName {
5013    pub qualifier: Option<String>,
5014    pub name: String,
5015}
5016
5017#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5018pub enum BinOp {
5019    Or,
5020    And,
5021    Eq,
5022    NotEq,
5023    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
5024    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
5025    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
5026    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
5027    /// PG-style JOIN ON predicates and pg_dump output.
5028    IsDistinctFrom,
5029    IsNotDistinctFrom,
5030    /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
5031    /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
5032    /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
5033    /// is a real division (round 351).
5034    IntDiv,
5035    Lt,
5036    LtEq,
5037    Gt,
5038    GtEq,
5039    Add,
5040    Sub,
5041    Mul,
5042    Div,
5043    /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
5044    /// precedence as Mul/Div; result type follows left operand.
5045    Mod,
5046    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
5047    /// operands of equal dimension; engine returns `Value::Float(d)`.
5048    L2Distance,
5049    /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
5050    GeomParallel,
5051    /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
5052    OverLeft,
5053    OverRight,
5054    /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
5055    GeomPerp,
5056    /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
5057    GeomSameAs,
5058    /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
5059    /// object to the left-hand one.
5060    ClosestPoint,
5061    /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
5062    GeomHoriz,
5063    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
5064    /// more similar" remains true (matches pgvector's published convention).
5065    InnerProduct,
5066    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
5067    CosineDistance,
5068    /// SQL string concatenation `||`. NULL propagates.
5069    Concat,
5070    /// Bitwise OR `|` on integers.
5071    BitOr,
5072    /// Bitwise AND `&` on integers.
5073    BitAnd,
5074    /// Bitwise XOR `#` on integers and equal-length bit strings.
5075    BitXor,
5076    /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
5077    /// sides as truth values and returns their exclusive-or (`1 XOR 0`
5078    /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
5079    /// MySQL dialect produces it; PG has no logical XOR. Its precedence
5080    /// sits between OR (loosest) and AND.
5081    LogicalXor,
5082    /// v4.14 `json -> key` — element access by string key (object)
5083    /// or integer index (array). Returns a JSON value.
5084    JsonGet,
5085    /// v4.14 `json ->> key` — same access, returns the result as
5086    /// TEXT (unwraps a top-level JSON string; renders other scalars
5087    /// as their canonical text).
5088    JsonGetText,
5089    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
5090    /// text array literal like `'{a,0,b}'`. Returns JSON.
5091    JsonGetPath,
5092    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
5093    JsonGetPathText,
5094    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
5095    /// when every key/value in `sub_json` is structurally present in
5096    /// the left side. Matches PG semantics (top-level + recursive).
5097    JsonContains,
5098    /// `@?` — jsonb path existence (jsonb_path_exists).
5099    JsonPathExists,
5100    /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
5101    /// `a <@ b` is defined as `b @> a` (same semantics, swapped
5102    /// sides). Eval dispatch reuses `JsonContains` with swapped args.
5103    JsonContainedBy,
5104    /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
5105    /// returns BOOL. For an object, true if `key` is an existing
5106    /// member name; for an array, true if any element is the string
5107    /// `key` (PG semantics).
5108    JsonKeyExists,
5109    /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
5110    /// returns BOOL.
5111    JsonKeysAny,
5112    /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
5113    /// returns BOOL.
5114    JsonKeysAll,
5115    /// `jsonb #- path_text[]` — delete the value at a nested path.
5116    /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
5117    JsonDeletePath,
5118    /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
5119    /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
5120    /// tsvector` and engine eval normalises either ordering.
5121    TsMatch,
5122    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
5123    /// `<<`. LHS network is strictly inside RHS network (no equality).
5124    InetContainedBy,
5125    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
5126    /// `<<=`. LHS network ⊆ RHS network.
5127    InetContainedByEq,
5128    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
5129    /// LHS network strictly contains RHS network.
5130    InetContains,
5131    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
5132    /// LHS network ⊇ RHS network.
5133    InetContainsEq,
5134    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
5135    /// True iff either network contains any address of the other.
5136    InetOverlap,
5137    /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
5138    /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
5139    Intersects,
5140    /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
5141    /// (point, box).
5142    IsBelow,
5143    IsAbove,
5144    /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
5145    /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
5146    /// where `'A' < 'a'` is false under a non-C collation, which is the
5147    /// whole reason the operator family exists — it is what makes a LIKE
5148    /// prefix index-usable. pg_dump writes these into index definitions.
5149    PatternLt,
5150    PatternLtEq,
5151    PatternGt,
5152    PatternGtEq,
5153}
5154
5155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5156pub enum UnOp {
5157    Not,
5158    Neg,
5159    /// Bitwise NOT `~` on integers.
5160    BitNot,
5161    /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
5162    /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
5163    /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
5164    /// while PG18 and MariaDB accept every one of them.
5165    ///
5166    /// It is not a no-op to drop at parse time — PG refuses it on
5167    /// non-numeric operands ("operator does not exist: + boolean"), so the
5168    /// operand's type has to be seen at eval.
5169    Plus,
5170}
5171
5172// --- Display impls (round-trip-safe) --------------------------------------
5173
5174impl Statement {
5175    /// v7.18 — classify whether the statement is read-only at
5176    /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
5177    /// route SELECT-shaped traffic through the fan-out
5178    /// `AsyncReadHandle` (no writer-lock contention) while
5179    /// keeping DML / DDL / TX-control on the single-writer path.
5180    ///
5181    /// The classification matches what
5182    /// `Engine::execute_readonly_with_cancel` accepts: anything
5183    /// that does NOT mutate catalog, statistics, session state,
5184    /// or transaction state. WaitForWalPosition is included
5185    /// (engine returns `Unsupported`, but the classification is
5186    /// semantically read-only — no mutation). Empty is excluded
5187    /// out of an abundance of caution — the no-op routes
5188    /// through the writer so any future side effect lands
5189    /// uniformly.
5190    ///
5191    /// **Not connection-state aware**. `SET LOCAL` / `RESET`
5192    /// affect session parameters and must run on the writer
5193    /// engine that owns the session state; they classify as
5194    /// writer-path here. Same for `BEGIN` / `COMMIT` /
5195    /// `ROLLBACK` / `SAVEPOINT` — transaction control is
5196    /// always writer-path.
5197    /// v7.39 (round 435) — does this statement implicitly COMMIT an open
5198    /// transaction under MySQL?
5199    ///
5200    /// PG runs DDL inside the transaction; MySQL commits before (and after)
5201    /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
5202    /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
5203    /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
5204    /// nested START TRANSACTION; and measured NOT to fire for `CREATE
5205    /// TEMPORARY TABLE`, `SET`, or a SELECT.
5206    ///
5207    /// A positive list, not "everything that is not DML": a statement
5208    /// wrongly listed here commits a client's data early, which is as bad as
5209    /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
5210    /// COMPACT) are left out — a MySQL session never sends them.
5211    #[must_use]
5212    pub fn mysql_implicit_commit(&self) -> bool {
5213        match self {
5214            // MySQL's documented exception, measured on MariaDB 11: a
5215            // TEMPORARY table is not DDL for this purpose and does not
5216            // commit. (Round 435 got this for free because the parser then
5217            // lowered that spelling to `Statement::Empty`; round 436 made it
5218            // a real CREATE TABLE, and the round-435 pin caught it.)
5219            Self::CreateTable(c) => !c.temporary,
5220            // MySQL commits the open transaction and opens a fresh one.
5221            Self::Begin { .. }
5222            | Self::DropTable { .. }
5223            | Self::DropIndex { .. }
5224            | Self::CreateIndex(_)
5225            | Self::AlterIndex { .. }
5226            | Self::AlterTable(_)
5227            | Self::Truncate { .. }
5228            | Self::Analyze { .. }
5229            | Self::CreateStatistics { .. }
5230            | Self::DropStatistics { .. }
5231            | Self::CreateView { .. }
5232            | Self::DropView { .. }
5233            | Self::CreateMaterializedView { .. }
5234            | Self::RefreshMaterializedView { .. }
5235            | Self::DropMaterializedView { .. }
5236            | Self::CreateSequence(_)
5237            | Self::AlterSequence { .. }
5238            | Self::DropSequence { .. }
5239            | Self::CreateFunction(_)
5240            | Self::DropFunction { .. }
5241            | Self::CreateTrigger(_)
5242            | Self::DropTrigger { .. }
5243            | Self::CreateRule(_)
5244            | Self::DropRule { .. }
5245            | Self::CreateType(_)
5246            | Self::DropType { .. }
5247            | Self::AlterTypeAddValue { .. }
5248            | Self::AlterTypeRenameValue { .. }
5249            | Self::CreateDomain(_)
5250            | Self::AlterDomain { .. }
5251            | Self::DropDomain { .. }
5252            | Self::CreateSchema { .. }
5253            | Self::DropSchema { .. }
5254            | Self::CreateUser { .. }
5255            | Self::DropUser { .. }
5256            | Self::Grant { .. }
5257            | Self::Revoke { .. }
5258            | Self::CreatePolicy(_)
5259            | Self::AlterPolicy(_)
5260            | Self::DropPolicy { .. }
5261            | Self::CommentOn { .. }
5262            | Self::CreateExtension { .. } => true,
5263            _ => false,
5264        }
5265    }
5266
5267    #[must_use]
5268    pub fn is_readonly(&self) -> bool {
5269        match self {
5270            // v7.39 (round 288) — SET CONSTRAINTS changes transaction
5271            // state, and IMMEDIATE can run the deferred checks there and
5272            // then; writer-path.
5273            Statement::SetConstraints { .. } => false,
5274            // v7.39 (round 695) — it writes nothing (SPG has no
5275            // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
5276            // writer and a read-only session refuses it there too.
5277            Statement::AlterSystem { .. } => false,
5278            // Same shape: a no-op here, a writer to PG, so a read-only
5279            // session refuses it as PG's would.
5280            Statement::NoOpPreventedInTransaction { .. } => false,
5281            Statement::DropDatabase { .. } => false,
5282            // v7.39 (round 696) — they perform nothing, so nothing is
5283            // written; PG classes LOCK and the OWNED BY pair as writers and
5284            // a read-only session refuses them there.
5285            Statement::ValidateOnly { .. } => false,
5286            // v7.39 (round 750) — a credential rotation persists.
5287            Statement::AlterRolePassword { .. } => true,
5288            Statement::DropAggregate { .. } => false,
5289            // v7.39 (round 547) — records a GUC default in the catalog.
5290            Statement::SetDbRoleSetting(_) => false,
5291            // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
5292            // but they name a relation and PG refuses one that is not
5293            // there, so they are not read-only in the sense this asks.
5294            Statement::Maintain { .. } => false,
5295            // v7.39 (round 277) — the prepared-statement surface is
5296            // session state, like SET; writer-path so it lands on the
5297            // engine that owns the session. EXECUTE may also run a
5298            // write, and its body is only known at execution time.
5299            Statement::Prepare { .. }
5300            | Statement::Execute { .. }
5301            | Statement::Deallocate(_)
5302            | Statement::Call(_)
5303            | Statement::PrepareTransaction(_)
5304            | Statement::CreateStatistics { .. }
5305            | Statement::DropStatistics { .. }
5306            // v7.39 (round 318, V51) — KILL signals another connection;
5307            // it must run on the writer path that owns the registry hook.
5308            | Statement::Kill { .. }
5309            // v7.39 (round 320, V53) — DISCARD throws session state away;
5310            // writer path, like SET / RESET.
5311            | Statement::Discard(_)
5312            // v7.39.2 — `USE <db>` writes session state, the same way
5313            // SET does, and takes the same path.
5314            | Statement::UseDatabase(_) => false,
5315            // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
5316            // locks MUTATES the lock table, so it is not a read. Left as
5317            // a read it went to the read-only executor and the locking
5318            // pre-pass never ran at all — the clause was honoured only
5319            // inside an explicit transaction, and silently ignored in
5320            // autocommit, which is where a queue worker runs it.
5321            Statement::Select(s) if s.locking.is_some() => false,
5322            Statement::Select(_)
5323            | Statement::CopyTo { .. }
5324            | Statement::CopyToFile { .. }
5325            | Statement::Explain(_)
5326            | Statement::ShowTables
5327            | Statement::ShowDatabases
5328            | Statement::ShowCreateTable(_)
5329            | Statement::ShowIndexes(_)
5330            | Statement::ShowStatus
5331            | Statement::ShowVariables
5332            | Statement::ShowVariablesLike(_)
5333            | Statement::ShowProcesslist
5334            | Statement::ShowColumns(_)
5335            | Statement::ShowUsers
5336            | Statement::ShowPublications
5337            | Statement::ShowSubscriptions
5338            | Statement::WaitForWalPosition { .. } => true,
5339            // Everything else mutates catalog, statistics,
5340            // session state, or transaction state — writer path.
5341            // Listed explicitly so a new Statement variant fails
5342            // the match exhaustiveness check and forces a
5343            // classification decision at add-site.
5344            Statement::Empty
5345            // v7.39 (round 169) — VACUUM mutates storage (reclaims
5346            // tombstoned versions): writer path.
5347            | Statement::Vacuum { .. }
5348            | Statement::DropTable { .. }
5349            | Statement::DropIndex { .. }
5350            | Statement::CreateTable(_)
5351            | Statement::CreateExtension(_)
5352            | Statement::DoBlock(_)
5353            | Statement::CreateIndex(_)
5354            | Statement::Insert(_)
5355            | Statement::Update(_)
5356            | Statement::Delete(_)
5357            | Statement::Merge(_)
5358            | Statement::Begin(_)
5359            | Statement::Commit
5360            | Statement::Rollback
5361            | Statement::Savepoint(_)
5362            | Statement::RollbackToSavepoint(_)
5363            | Statement::ReleaseSavepoint(_)
5364            | Statement::CreateUser(_)
5365            | Statement::DropUser { .. }
5366            | Statement::SetRole(_)
5367            | Statement::Grant(_)
5368            | Statement::Revoke(_)
5369            | Statement::CreatePolicy(_)
5370            | Statement::AlterPolicy(_)
5371            | Statement::DropPolicy(_)
5372            | Statement::AlterIndex(_)
5373            | Statement::AlterTable(_)
5374            | Statement::CreatePublication(_)
5375            | Statement::DropPublication { .. }
5376            | Statement::CreateSubscription(_)
5377            | Statement::DropSubscription { .. }
5378            | Statement::Analyze(_)
5379            | Statement::Truncate { .. }
5380            | Statement::CompactColdSegments
5381            | Statement::SetParameter { .. }
5382            | Statement::SetParameterList(_)
5383            | Statement::SetUserVars(..)
5384            | Statement::SetTransaction { .. }
5385            | Statement::ShowParameter(_)
5386            | Statement::ResetParameter(_)
5387            | Statement::CreateFunction(_)
5388            | Statement::CreateTrigger(_)
5389            | Statement::DropTrigger { .. }
5390            | Statement::CreateRule(_)
5391            | Statement::DropRule { .. }
5392            | Statement::DropFunction { .. }
5393            | Statement::CreateSequence(_)
5394            | Statement::AlterSequence(_)
5395            | Statement::DropSequence { .. }
5396            | Statement::CreateView(_)
5397            | Statement::DropView { .. }
5398            | Statement::CreateMaterializedView(_)
5399            | Statement::RefreshMaterializedView { .. }
5400            | Statement::DropMaterializedView { .. }
5401            | Statement::CreateType(_)
5402            | Statement::AlterTypeAddValue { .. }
5403            | Statement::AlterTypeRenameValue { .. }
5404            | Statement::CommentOn { .. }
5405            | Statement::DropType { .. }
5406            | Statement::CreateDomain(_)
5407            | Statement::DropDomain { .. }
5408            | Statement::CreateSchema { .. }
5409            | Statement::DropSchema { .. }
5410            // v7.39 (round 218) — cursors mutate per-session cursor state
5411            // (open/position/close) on the writer engine: writer path.
5412            | Statement::DeclareCursor { .. }
5413            | Statement::FetchCursor { .. }
5414            | Statement::MoveCursor { .. }
5415            | Statement::CloseCursor { .. }
5416            // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5417            // state / the notification queue: writer path.
5418            | Statement::Listen(_)
5419            | Statement::Notify { .. }
5420            | Statement::Unlisten(_)
5421            | Statement::CopyFromFile { .. }
5422            | Statement::AlterDomain { .. } => false,
5423        }
5424    }
5425}
5426
5427/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5428/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5429#[derive(Debug, Clone, PartialEq, Eq)]
5430pub struct GrantStatement {
5431    /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5432    /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5433    /// is why they keep the case the user typed.
5434    pub privileges: Vec<GrantPriv>,
5435    /// What the privileges are on.
5436    pub object: GrantObject,
5437    /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5438    pub grantees: Vec<String>,
5439    /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5440    /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5441    /// privilege itself).
5442    pub grant_option: bool,
5443}
5444
5445/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5446/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5447/// An empty column list means the privilege is table-wide.
5448#[derive(Debug, Clone, PartialEq, Eq)]
5449pub struct GrantPriv {
5450    pub word: String,
5451    pub columns: Vec<String>,
5452}
5453
5454/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5455/// privileges; every other object class parses and is accepted as a no-op, so
5456/// a pg_dump that grants on schemas / sequences / functions still restores.
5457#[derive(Debug, Clone, PartialEq, Eq)]
5458pub enum GrantObject {
5459    /// `ON [TABLE] a, b` — the enforced case.
5460    Tables(Vec<String>),
5461    /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5462    /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5463    /// granted roles; the grantees are the members.
5464    Roles(Vec<String>),
5465    /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5466    /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5467    Sequences(Vec<String>),
5468    /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5469    Schemas(Vec<String>),
5470    /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5471    Databases(Vec<String>),
5472    /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5473    /// (SPG keys functions by name); the argument list parses and is dropped.
5474    Functions(Vec<(String, Option<Vec<String>>)>),
5475    /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5476    /// every table at GRANT time, exactly like PG.
5477    AllTablesInSchema,
5478    /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5479    /// message.
5480    Other(String),
5481}
5482
5483impl GrantStatement {
5484    /// Round-trip text. `grant = false` renders the REVOKE form.
5485    fn render(&self, grant: bool) -> alloc::string::String {
5486        use core::fmt::Write as _;
5487        let mut s = alloc::string::String::new();
5488        let privs = if self.privileges.is_empty() {
5489            alloc::string::String::from("ALL")
5490        } else {
5491            let parts: Vec<_> = self
5492                .privileges
5493                .iter()
5494                .map(|p| {
5495                    if p.columns.is_empty() {
5496                        p.word.clone()
5497                    } else {
5498                        let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5499                        alloc::format!("{} ({})", p.word, cols.join(", "))
5500                    }
5501                })
5502                .collect();
5503            parts.join(", ")
5504        };
5505        let obj = match &self.object {
5506            GrantObject::Tables(t) => {
5507                let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5508                alloc::format!("TABLE {}", names.join(", "))
5509            }
5510            GrantObject::Roles(r) => {
5511                let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5512                names.join(", ")
5513            }
5514            GrantObject::Sequences(n) => {
5515                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5516                alloc::format!("SEQUENCE {}", names.join(", "))
5517            }
5518            GrantObject::Schemas(n) => {
5519                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5520                alloc::format!("SCHEMA {}", names.join(", "))
5521            }
5522            GrantObject::Databases(n) => {
5523                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5524                alloc::format!("DATABASE {}", names.join(", "))
5525            }
5526            GrantObject::Functions(n) => {
5527                let names: Vec<_> = n
5528                    .iter()
5529                    .map(|(name, args)| match args {
5530                        Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5531                        None => quote_ident(name),
5532                    })
5533                    .collect();
5534                alloc::format!("FUNCTION {}", names.join(", "))
5535            }
5536            GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5537            GrantObject::Other(k) => k.clone(),
5538        };
5539        let who: Vec<_> = self
5540            .grantees
5541            .iter()
5542            .map(|g| {
5543                if g.is_empty() {
5544                    "PUBLIC".into()
5545                } else {
5546                    quote_ident(g)
5547                }
5548            })
5549            .collect();
5550        if let GrantObject::Roles(_) = &self.object {
5551            let _ = if grant {
5552                write!(s, "GRANT {obj} TO {}", who.join(", "))
5553            } else {
5554                write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5555            };
5556            return s;
5557        }
5558        if grant {
5559            let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5560            if self.grant_option {
5561                s.push_str(" WITH GRANT OPTION");
5562            }
5563        } else {
5564            s.push_str("REVOKE ");
5565            if self.grant_option {
5566                s.push_str("GRANT OPTION FOR ");
5567            }
5568            let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5569        }
5570        s
5571    }
5572}
5573
5574impl fmt::Display for Statement {
5575    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5576        match self {
5577            Self::Empty => Ok(()),
5578            // v7.39 (round 695) — deparsed the way PG writes it.
5579            // v7.39 (round 696) — never deparsed into a dump (nothing is
5580            // stored), so the shortest faithful spelling of what it was.
5581            Self::DropAggregate { if_exists, items } => {
5582                f.write_str("DROP AGGREGATE ")?;
5583                if *if_exists {
5584                    f.write_str("IF EXISTS ")?;
5585                }
5586                for (i, (name, args)) in items.iter().enumerate() {
5587                    if i > 0 {
5588                        f.write_str(", ")?;
5589                    }
5590                    match args {
5591                        Some(a) => write!(f, "{name}({})", a.join(", "))?,
5592                        None => write!(f, "{name}(*)")?,
5593                    }
5594                }
5595                Ok(())
5596            }
5597            Self::AlterRolePassword { name, password } => {
5598                write!(f, "ALTER ROLE {}", quote_ident(name))?;
5599                match password {
5600                    Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5601                    None => f.write_str(" PASSWORD NULL"),
5602                }
5603            }
5604            Self::ValidateOnly { kind, names } => match kind {
5605                ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5606                ValidateOnlyKind::RoleName => {
5607                    write!(f, "DROP OWNED BY {}", names.join(", "))
5608                }
5609                ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5610                ValidateOnlyKind::ExtensionAvailable => {
5611                    write!(f, "CREATE EXTENSION {}", names.join(", "))
5612                }
5613                ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5614                ValidateOnlyKind::CollationName => {
5615                    write!(f, "DROP COLLATION {}", names.join(", "))
5616                }
5617                ValidateOnlyKind::TsConfigName => {
5618                    write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5619                }
5620                ValidateOnlyKind::EventTriggerName => {
5621                    write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5622                }
5623                ValidateOnlyKind::TablespaceName => {
5624                    write!(f, "DROP TABLESPACE {}", names.join(", "))
5625                }
5626                ValidateOnlyKind::LargeObjectOid => {
5627                    write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5628                }
5629                ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5630                ValidateOnlyKind::AggregateName => {
5631                    write!(f, "ALTER AGGREGATE {}", names.join(", "))
5632                }
5633                ValidateOnlyKind::ConversionName => {
5634                    write!(f, "DROP CONVERSION {}", names.join(", "))
5635                }
5636                ValidateOnlyKind::LanguageName => {
5637                    write!(f, "DROP LANGUAGE {}", names.join(", "))
5638                }
5639                ValidateOnlyKind::ExtensionInstalled => {
5640                    write!(f, "DROP EXTENSION {}", names.join(", "))
5641                }
5642            },
5643            Self::AlterSystem { parameter } => match parameter {
5644                Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5645                None => f.write_str("ALTER SYSTEM RESET ALL"),
5646            },
5647            // v7.39 (round 547) — round-trips as PG writes it.
5648            Self::SetDbRoleSetting(st) => {
5649                match (&st.database, &st.role) {
5650                    (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5651                    (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5652                    (None, None) => f.write_str("ALTER ROLE ALL")?,
5653                }
5654                if let (Some(d), Some(_)) = (&st.database, &st.role) {
5655                    write!(f, " IN DATABASE {d}")?;
5656                }
5657                match (&st.param, &st.value) {
5658                    (None, _) => f.write_str(" RESET ALL"),
5659                    (Some(p), None) => write!(f, " RESET {p}"),
5660                    (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5661                }
5662            }
5663            Self::Maintain {
5664                kind,
5665                concurrently,
5666                target,
5667            } => {
5668                f.write_str(match kind {
5669                    crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5670                    _ => "REINDEX ",
5671                })?;
5672                if *concurrently {
5673                    f.write_str("CONCURRENTLY ")?;
5674                }
5675                if let Some(t) = target {
5676                    f.write_str(t)?;
5677                }
5678                Ok(())
5679            }
5680            Self::DropDatabase { name, if_exists } => {
5681                f.write_str("DROP DATABASE ")?;
5682                if *if_exists {
5683                    f.write_str("IF EXISTS ")?;
5684                }
5685                f.write_str(name)
5686            }
5687            Self::NoOpPreventedInTransaction { what, .. } => f.write_str(what),
5688            Self::SetConstraints { names, deferred } => {
5689                f.write_str("SET CONSTRAINTS ")?;
5690                if names.is_empty() {
5691                    f.write_str("ALL")?;
5692                } else {
5693                    for (i, n) in names.iter().enumerate() {
5694                        if i > 0 {
5695                            f.write_str(", ")?;
5696                        }
5697                        f.write_str(n)?;
5698                    }
5699                }
5700                f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5701            }
5702            // v7.39 (round 277) — the source text is kept verbatim so
5703            // `pg_prepared_statements.statement` can report it the way
5704            // PG does (the whole PREPARE statement, not just the body).
5705            Self::Prepare { source, .. } => f.write_str(source),
5706            Self::Execute { name, args } => {
5707                write!(f, "EXECUTE {}", quote_ident(name))?;
5708                if !args.is_empty() {
5709                    f.write_str("(")?;
5710                    for (i, a) in args.iter().enumerate() {
5711                        if i > 0 {
5712                            f.write_str(", ")?;
5713                        }
5714                        write!(f, "{a}")?;
5715                    }
5716                    f.write_str(")")?;
5717                }
5718                Ok(())
5719            }
5720            Self::CreateStatistics {
5721                name,
5722                if_not_exists,
5723                kinds,
5724                columns,
5725                table,
5726            } => {
5727                f.write_str("CREATE STATISTICS ")?;
5728                if *if_not_exists {
5729                    f.write_str("IF NOT EXISTS ")?;
5730                }
5731                write!(f, "{}", quote_ident(name))?;
5732                if !kinds.is_empty() {
5733                    write!(f, " ({})", kinds.join(", "))?;
5734                }
5735                write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5736            }
5737            Self::DropStatistics { name, if_exists } => {
5738                f.write_str("DROP STATISTICS ")?;
5739                if *if_exists {
5740                    f.write_str("IF EXISTS ")?;
5741                }
5742                write!(f, "{}", quote_ident(name))
5743            }
5744            Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5745            Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5746            Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5747            Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5748            Self::DeclareCursor {
5749                name,
5750                scroll,
5751                hold,
5752                query,
5753            } => {
5754                write!(f, "DECLARE {} ", quote_ident(name))?;
5755                match scroll {
5756                    Some(true) => f.write_str("SCROLL ")?,
5757                    Some(false) => f.write_str("NO SCROLL ")?,
5758                    None => {}
5759                }
5760                f.write_str("CURSOR ")?;
5761                if *hold {
5762                    f.write_str("WITH HOLD ")?;
5763                }
5764                write!(f, "FOR {query}")
5765            }
5766            Self::FetchCursor { name, direction } => {
5767                write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5768            }
5769            Self::MoveCursor { name, direction } => {
5770                write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5771            }
5772            Self::CloseCursor { name } => match name {
5773                Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5774                None => f.write_str("CLOSE ALL"),
5775            },
5776            Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5777            Self::Notify { channel, payload } => {
5778                write!(f, "NOTIFY {}", quote_ident(channel))?;
5779                if let Some(p) = payload {
5780                    write!(f, ", '{}'", p.replace('\'', "''"))?;
5781                }
5782                Ok(())
5783            }
5784            Self::Unlisten(ch) => match ch {
5785                Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5786                None => f.write_str("UNLISTEN *"),
5787            },
5788            Self::CopyTo {
5789                table,
5790                columns,
5791                query,
5792                options,
5793            } => {
5794                if let Some(q) = query {
5795                    write!(f, "COPY ({q})")?;
5796                } else {
5797                    write!(f, "COPY {table}")?;
5798                    if let Some(cols) = columns {
5799                        write!(f, " ({})", cols.join(", "))?;
5800                    }
5801                }
5802                write!(f, " TO STDOUT")?;
5803                let mut parts: Vec<String> = Vec::new();
5804                if options.format == CopyFormat::Csv {
5805                    parts.push("FORMAT csv".to_string());
5806                }
5807                if options.header {
5808                    parts.push("HEADER true".to_string());
5809                }
5810                if let Some(d) = options.delimiter {
5811                    parts.push(alloc::format!("DELIMITER '{d}'"));
5812                }
5813                if let Some(n) = &options.null_str {
5814                    parts.push(alloc::format!("NULL '{n}'"));
5815                }
5816                if let Some(q) = options.quote {
5817                    parts.push(alloc::format!("QUOTE '{q}'"));
5818                }
5819                if !parts.is_empty() {
5820                    write!(f, " WITH ({})", parts.join(", "))?;
5821                }
5822                Ok(())
5823            }
5824            Self::CopyFromFile {
5825                table,
5826                columns,
5827                path,
5828                options,
5829            } => {
5830                write!(f, "COPY {table}")?;
5831                if let Some(cols) = columns {
5832                    write!(f, " ({})", cols.join(", "))?;
5833                }
5834                write!(f, " FROM '{path}'")?;
5835                let mut parts: Vec<String> = Vec::new();
5836                if options.format == CopyFormat::Csv {
5837                    parts.push("FORMAT csv".to_string());
5838                }
5839                if options.header {
5840                    parts.push("HEADER true".to_string());
5841                }
5842                if let Some(d) = options.delimiter {
5843                    parts.push(alloc::format!("DELIMITER '{d}'"));
5844                }
5845                if let Some(n) = &options.null_str {
5846                    parts.push(alloc::format!("NULL '{n}'"));
5847                }
5848                if let Some(q) = options.quote {
5849                    parts.push(alloc::format!("QUOTE '{q}'"));
5850                }
5851                if !parts.is_empty() {
5852                    write!(f, " WITH ({})", parts.join(", "))?;
5853                }
5854                Ok(())
5855            }
5856            Self::CopyToFile {
5857                table,
5858                columns,
5859                query,
5860                path,
5861                options,
5862            } => {
5863                if let Some(q) = query {
5864                    write!(f, "COPY ({q})")?;
5865                } else {
5866                    write!(f, "COPY {table}")?;
5867                    if let Some(cols) = columns {
5868                        write!(f, " ({})", cols.join(", "))?;
5869                    }
5870                }
5871                write!(f, " TO '{path}'")?;
5872                let mut parts: Vec<String> = Vec::new();
5873                if options.format == CopyFormat::Csv {
5874                    parts.push("FORMAT csv".to_string());
5875                }
5876                if options.header {
5877                    parts.push("HEADER true".to_string());
5878                }
5879                if let Some(d) = options.delimiter {
5880                    parts.push(alloc::format!("DELIMITER '{d}'"));
5881                }
5882                if let Some(n) = &options.null_str {
5883                    parts.push(alloc::format!("NULL '{n}'"));
5884                }
5885                if let Some(q) = options.quote {
5886                    parts.push(alloc::format!("QUOTE '{q}'"));
5887                }
5888                if !parts.is_empty() {
5889                    write!(f, " WITH ({})", parts.join(", "))?;
5890                }
5891                Ok(())
5892            }
5893            Self::AlterDomain { name, action } => {
5894                write!(f, "ALTER DOMAIN {name} ")?;
5895                match action {
5896                    AlterDomainAction::AddConstraint { name: cn, check } => match cn {
5897                        Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
5898                        None => write!(f, "ADD CHECK ({check})"),
5899                    },
5900                    AlterDomainAction::DropConstraint {
5901                        name: cn,
5902                        if_exists,
5903                    } => {
5904                        if *if_exists {
5905                            write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
5906                        } else {
5907                            write!(f, "DROP CONSTRAINT {cn}")
5908                        }
5909                    }
5910                    AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
5911                    AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
5912                    AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
5913                    AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
5914                    AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
5915                }
5916            }
5917            Self::Truncate {
5918                tables,
5919                restart_identity,
5920                cascade,
5921                only,
5922            } => {
5923                f.write_str("TRUNCATE TABLE ")?;
5924                if *only {
5925                    f.write_str("ONLY ")?;
5926                }
5927                for (i, t) in tables.iter().enumerate() {
5928                    if i > 0 {
5929                        f.write_str(", ")?;
5930                    }
5931                    f.write_str(t)?;
5932                }
5933                if *restart_identity {
5934                    f.write_str(" RESTART IDENTITY")?;
5935                }
5936                if *cascade {
5937                    f.write_str(" CASCADE")?;
5938                }
5939                Ok(())
5940            }
5941            Self::DropTable { names, if_exists } => {
5942                f.write_str("DROP TABLE ")?;
5943                if *if_exists {
5944                    f.write_str("IF EXISTS ")?;
5945                }
5946                for (i, n) in names.iter().enumerate() {
5947                    if i > 0 {
5948                        f.write_str(", ")?;
5949                    }
5950                    write!(f, "{}", quote_ident(n))?;
5951                }
5952                Ok(())
5953            }
5954            Self::DropIndex {
5955                name,
5956                if_exists,
5957                table,
5958            } => {
5959                f.write_str("DROP INDEX ")?;
5960                if *if_exists {
5961                    f.write_str("IF EXISTS ")?;
5962                }
5963                write!(f, "{}", quote_ident(name))?;
5964                if let Some(t) = table {
5965                    write!(f, " ON {}", quote_ident(t))?;
5966                }
5967                Ok(())
5968            }
5969            Self::Select(s) => s.fmt(f),
5970            Self::CreateTable(s) => s.fmt(f),
5971            Self::CreateIndex(s) => s.fmt(f),
5972            Self::Insert(s) => s.fmt(f),
5973            Self::Update(s) => s.fmt(f),
5974            Self::Delete(s) => s.fmt(f),
5975            Self::Merge(s) => s.fmt(f),
5976            Self::Vacuum { table, analyze } => {
5977                f.write_str("VACUUM")?;
5978                if *analyze {
5979                    f.write_str(" ANALYZE")?;
5980                }
5981                if let Some(t) = table {
5982                    write!(f, " {}", quote_ident(t))?;
5983                }
5984                Ok(())
5985            }
5986            Self::Begin(modes) => {
5987                f.write_str("BEGIN")?;
5988                if let Some(level) = modes.isolation {
5989                    write!(f, " ISOLATION LEVEL {level}")?;
5990                }
5991                match modes.read_only {
5992                    Some(true) => f.write_str(" READ ONLY")?,
5993                    Some(false) => f.write_str(" READ WRITE")?,
5994                    None => {}
5995                }
5996                Ok(())
5997            }
5998            Self::Commit => f.write_str("COMMIT"),
5999            Self::Rollback => f.write_str("ROLLBACK"),
6000            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
6001            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
6002            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
6003            Self::ShowTables => f.write_str("SHOW TABLES"),
6004            Self::ShowDatabases => f.write_str("SHOW DATABASES"),
6005            Self::UseDatabase(n) => write!(f, "USE {}", quote_ident(n)),
6006            Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
6007            Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
6008            Self::ShowStatus => f.write_str("SHOW STATUS"),
6009            Self::ShowVariables => f.write_str("SHOW VARIABLES"),
6010            Self::ShowVariablesLike(p) => {
6011                write!(f, "SHOW VARIABLES LIKE '{}'", p.replace('\'', "''"))
6012            }
6013            Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
6014            Self::Discard(t) => write!(f, "DISCARD {t}"),
6015            Self::Kill { query_only, id } => {
6016                if *query_only {
6017                    write!(f, "KILL QUERY {id}")
6018                } else {
6019                    write!(f, "KILL CONNECTION {id}")
6020                }
6021            }
6022            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
6023            Self::CreateUser(s) => write!(
6024                f,
6025                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
6026                quote_ident(&s.name),
6027                s.role
6028            ),
6029            Self::DropUser { name, if_exists } => {
6030                let ie = if *if_exists { "IF EXISTS " } else { "" };
6031                write!(f, "DROP USER {ie}{}", quote_ident(name))
6032            }
6033            Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
6034            Self::SetRole(None) => f.write_str("RESET ROLE"),
6035            Self::Grant(g) => write!(f, "{}", g.render(true)),
6036            Self::Revoke(g) => write!(f, "{}", g.render(false)),
6037            Self::CreatePolicy(s) => {
6038                write!(
6039                    f,
6040                    "CREATE POLICY {} ON {}",
6041                    quote_ident(&s.name),
6042                    quote_ident(&s.table)
6043                )?;
6044                if !s.permissive {
6045                    f.write_str(" AS RESTRICTIVE")?;
6046                }
6047                if !matches!(s.cmd, PolicyCmd::All) {
6048                    let w = match s.cmd {
6049                        PolicyCmd::Select => "SELECT",
6050                        PolicyCmd::Insert => "INSERT",
6051                        PolicyCmd::Update => "UPDATE",
6052                        PolicyCmd::Delete => "DELETE",
6053                        PolicyCmd::All => unreachable!(),
6054                    };
6055                    write!(f, " FOR {w}")?;
6056                }
6057                if !s.roles.is_empty() {
6058                    write!(f, " TO {}", s.roles.join(", "))?;
6059                }
6060                if let Some(u) = &s.using {
6061                    write!(f, " USING ({u})")?;
6062                }
6063                if let Some(c) = &s.with_check {
6064                    write!(f, " WITH CHECK ({c})")?;
6065                }
6066                Ok(())
6067            }
6068            Self::AlterPolicy(s) => {
6069                write!(
6070                    f,
6071                    "ALTER POLICY {} ON {}",
6072                    quote_ident(&s.name),
6073                    quote_ident(&s.table)
6074                )?;
6075                if let Some(nn) = &s.rename_to {
6076                    return write!(f, " RENAME TO {}", quote_ident(nn));
6077                }
6078                if let Some(roles) = &s.roles {
6079                    write!(f, " TO {}", roles.join(", "))?;
6080                }
6081                if let Some(u) = &s.using {
6082                    write!(f, " USING ({u})")?;
6083                }
6084                if let Some(c) = &s.with_check {
6085                    write!(f, " WITH CHECK ({c})")?;
6086                }
6087                Ok(())
6088            }
6089            Self::DropPolicy(s) => {
6090                f.write_str("DROP POLICY ")?;
6091                if s.if_exists {
6092                    f.write_str("IF EXISTS ")?;
6093                }
6094                write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
6095            }
6096            Self::ShowUsers => f.write_str("SHOW USERS"),
6097            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
6098            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
6099            Self::CreateSubscription(s) => {
6100                write!(
6101                    f,
6102                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
6103                    quote_ident(&s.name),
6104                    s.conn_str.replace('\'', "''")
6105                )?;
6106                for (i, p) in s.publications.iter().enumerate() {
6107                    if i > 0 {
6108                        f.write_str(", ")?;
6109                    }
6110                    write!(f, "{}", quote_ident(p))?;
6111                }
6112                Ok(())
6113            }
6114            Self::DropSubscription { name, if_exists } => {
6115                let opt = if *if_exists { "IF EXISTS " } else { "" };
6116                write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
6117            }
6118            Self::WaitForWalPosition { pos, timeout_ms } => {
6119                write!(f, "WAIT FOR WAL POSITION {pos}")?;
6120                if let Some(ms) = timeout_ms {
6121                    write!(f, " WITH TIMEOUT {ms}")?;
6122                }
6123                Ok(())
6124            }
6125            Self::Analyze(None) => f.write_str("ANALYZE"),
6126            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
6127            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
6128            Self::Explain(e) => {
6129                if e.suggest {
6130                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
6131                } else if e.analyze {
6132                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
6133                } else {
6134                    write!(f, "EXPLAIN {}", e.inner)
6135                }
6136            }
6137            Self::AlterIndex(a) => {
6138                write!(f, "ALTER INDEX ")?;
6139                match &a.target {
6140                    // Parameters are consumed, not stored; the shortest
6141                    // faithful spelling.
6142                    AlterIndexTarget::StorageParams => {
6143                        write!(f, "{} SET ()", quote_ident(&a.name))
6144                    }
6145                    AlterIndexTarget::Rebuild { encoding } => {
6146                        write!(f, "{} REBUILD", quote_ident(&a.name))?;
6147                        if let Some(enc) = encoding {
6148                            write!(f, " WITH (encoding = {enc})")?;
6149                        }
6150                        Ok(())
6151                    }
6152                    AlterIndexTarget::Rename { new, if_exists } => {
6153                        if *if_exists {
6154                            f.write_str("IF EXISTS ")?;
6155                        }
6156                        write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
6157                    }
6158                }
6159            }
6160            Self::AlterTable(a) => {
6161                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
6162                for (i, t) in a.targets.iter().enumerate() {
6163                    if i > 0 {
6164                        f.write_str(", ")?;
6165                    }
6166                    fmt_alter_target(f, t)?;
6167                }
6168                Ok(())
6169            }
6170            Self::CreatePublication(p) => {
6171                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
6172                match &p.scope {
6173                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
6174                    PublicationScope::ForTables(ts) => {
6175                        f.write_str(" FOR TABLE ")?;
6176                        for (i, t) in ts.iter().enumerate() {
6177                            if i > 0 {
6178                                f.write_str(", ")?;
6179                            }
6180                            write!(f, "{}", quote_ident(t))?;
6181                        }
6182                        Ok(())
6183                    }
6184                    PublicationScope::TablesInSchema(schema) => {
6185                        write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
6186                        Ok(())
6187                    }
6188                    PublicationScope::AllTablesExcept(ts) => {
6189                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
6190                        for (i, t) in ts.iter().enumerate() {
6191                            if i > 0 {
6192                                f.write_str(", ")?;
6193                            }
6194                            write!(f, "{}", quote_ident(t))?;
6195                        }
6196                        Ok(())
6197                    }
6198                }
6199            }
6200            Self::CreateExtension(name) => {
6201                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
6202            }
6203            Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
6204            Self::DropPublication { name, if_exists } => {
6205                let opt = if *if_exists { "IF EXISTS " } else { "" };
6206                write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
6207            }
6208            Self::SetParameter { name, value, local } => {
6209                write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
6210                match value {
6211                    SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
6212                    SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
6213                    SetValue::Default => f.write_str("DEFAULT"),
6214                }
6215            }
6216            Self::SetTransaction { modes } => {
6217                f.write_str("SET TRANSACTION")?;
6218                if let Some(isolation) = modes.isolation {
6219                    let name = match isolation {
6220                        IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
6221                        IsolationLevel::ReadCommitted => "READ COMMITTED",
6222                        IsolationLevel::RepeatableRead => "REPEATABLE READ",
6223                        IsolationLevel::Serializable => "SERIALIZABLE",
6224                    };
6225                    write!(f, " ISOLATION LEVEL {name}")?;
6226                }
6227                match modes.read_only {
6228                    Some(true) => f.write_str(" READ ONLY")?,
6229                    Some(false) => f.write_str(" READ WRITE")?,
6230                    None => {}
6231                }
6232                Ok(())
6233            }
6234            Self::ShowParameter(name) => write!(f, "SHOW {name}"),
6235            Self::SetUserVars(assigns, _) => {
6236                f.write_str("SET ")?;
6237                for (i, (name, value)) in assigns.iter().enumerate() {
6238                    if i > 0 {
6239                        f.write_str(", ")?;
6240                    }
6241                    write!(f, "@{name} = {value}")?;
6242                }
6243                Ok(())
6244            }
6245            Self::SetParameterList(pairs) => {
6246                f.write_str("SET ")?;
6247                for (i, (name, value)) in pairs.iter().enumerate() {
6248                    if i > 0 {
6249                        f.write_str(", ")?;
6250                    }
6251                    write!(f, "{name} = ")?;
6252                    match value {
6253                        SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
6254                        SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
6255                        SetValue::Default => f.write_str("DEFAULT")?,
6256                    }
6257                }
6258                Ok(())
6259            }
6260            Self::ResetParameter(None) => f.write_str("RESET ALL"),
6261            Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
6262            Self::CreateFunction(s) => s.fmt(f),
6263            Self::CreateTrigger(s) => s.fmt(f),
6264            Self::DropTrigger {
6265                name,
6266                table,
6267                if_exists,
6268            } => {
6269                f.write_str("DROP TRIGGER ")?;
6270                if *if_exists {
6271                    f.write_str("IF EXISTS ")?;
6272                }
6273                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6274            }
6275            Self::DropFunction {
6276                name,
6277                args,
6278                if_exists,
6279            } => {
6280                f.write_str("DROP FUNCTION ")?;
6281                if *if_exists {
6282                    f.write_str("IF EXISTS ")?;
6283                }
6284                write!(f, "{}", quote_ident(name))?;
6285                if let Some(a) = args {
6286                    write!(f, "({})", a.join(", "))?;
6287                }
6288                Ok(())
6289            }
6290            Self::CreateSequence(s) => s.fmt(f),
6291            Self::AlterSequence(s) => s.fmt(f),
6292            Self::DropSequence { names, if_exists } => {
6293                f.write_str("DROP SEQUENCE ")?;
6294                if *if_exists {
6295                    f.write_str("IF EXISTS ")?;
6296                }
6297                for (i, n) in names.iter().enumerate() {
6298                    if i > 0 {
6299                        f.write_str(", ")?;
6300                    }
6301                    write!(f, "{}", quote_ident(n))?;
6302                }
6303                Ok(())
6304            }
6305            Self::CreateView(v) => v.fmt(f),
6306            Self::DropView { names, if_exists } => {
6307                f.write_str("DROP VIEW ")?;
6308                if *if_exists {
6309                    f.write_str("IF EXISTS ")?;
6310                }
6311                for (i, n) in names.iter().enumerate() {
6312                    if i > 0 {
6313                        f.write_str(", ")?;
6314                    }
6315                    write!(f, "{}", quote_ident(n))?;
6316                }
6317                Ok(())
6318            }
6319            Self::CreateMaterializedView(v) => v.fmt(f),
6320            Self::RefreshMaterializedView { name, with_data } => {
6321                write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
6322                if !*with_data {
6323                    f.write_str(" WITH NO DATA")?;
6324                }
6325                Ok(())
6326            }
6327            Self::DropMaterializedView { names, if_exists } => {
6328                f.write_str("DROP MATERIALIZED VIEW ")?;
6329                if *if_exists {
6330                    f.write_str("IF EXISTS ")?;
6331                }
6332                for (i, n) in names.iter().enumerate() {
6333                    if i > 0 {
6334                        f.write_str(", ")?;
6335                    }
6336                    write!(f, "{}", quote_ident(n))?;
6337                }
6338                Ok(())
6339            }
6340            Self::CreateType(t) => t.fmt(f),
6341            Self::CommentOn {
6342                kind,
6343                name,
6344                comment,
6345            } => {
6346                let body = match comment {
6347                    Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
6348                    None => "NULL".into(),
6349                };
6350                write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
6351            }
6352            Self::AlterTypeRenameValue {
6353                type_name,
6354                old,
6355                new,
6356            } => write!(
6357                f,
6358                "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
6359                quote_ident(type_name),
6360                old.replace('\'', "''"),
6361                new.replace('\'', "''")
6362            ),
6363            Self::AlterTypeAddValue {
6364                type_name,
6365                label,
6366                if_not_exists,
6367                position,
6368            } => {
6369                write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6370                if *if_not_exists {
6371                    write!(f, "IF NOT EXISTS ")?;
6372                }
6373                write!(f, "'{label}'")?;
6374                if let Some((is_before, anchor)) = position {
6375                    write!(
6376                        f,
6377                        " {} '{anchor}'",
6378                        if *is_before { "BEFORE" } else { "AFTER" }
6379                    )?;
6380                }
6381                Ok(())
6382            }
6383            Self::DropType { names, if_exists } => {
6384                f.write_str("DROP TYPE ")?;
6385                if *if_exists {
6386                    f.write_str("IF EXISTS ")?;
6387                }
6388                for (i, n) in names.iter().enumerate() {
6389                    if i > 0 {
6390                        f.write_str(", ")?;
6391                    }
6392                    write!(f, "{}", quote_ident(n))?;
6393                }
6394                Ok(())
6395            }
6396            Self::CreateDomain(d) => d.fmt(f),
6397            Self::DropDomain { names, if_exists } => {
6398                f.write_str("DROP DOMAIN ")?;
6399                if *if_exists {
6400                    f.write_str("IF EXISTS ")?;
6401                }
6402                for (i, n) in names.iter().enumerate() {
6403                    if i > 0 {
6404                        f.write_str(", ")?;
6405                    }
6406                    write!(f, "{}", quote_ident(n))?;
6407                }
6408                Ok(())
6409            }
6410            Self::CreateSchema {
6411                name,
6412                if_not_exists,
6413            } => {
6414                f.write_str("CREATE SCHEMA ")?;
6415                if *if_not_exists {
6416                    f.write_str("IF NOT EXISTS ")?;
6417                }
6418                write!(f, "{}", quote_ident(name))
6419            }
6420            Self::DropSchema { names, if_exists } => {
6421                f.write_str("DROP SCHEMA ")?;
6422                if *if_exists {
6423                    f.write_str("IF EXISTS ")?;
6424                }
6425                for (i, n) in names.iter().enumerate() {
6426                    if i > 0 {
6427                        f.write_str(", ")?;
6428                    }
6429                    write!(f, "{}", quote_ident(n))?;
6430                }
6431                Ok(())
6432            }
6433            Self::CreateRule(r) => {
6434                f.write_str("CREATE ")?;
6435                if r.or_replace {
6436                    f.write_str("OR REPLACE ")?;
6437                }
6438                write!(
6439                    f,
6440                    "RULE {} AS ON {} TO {}",
6441                    quote_ident(&r.name),
6442                    r.event,
6443                    quote_ident(&r.table)
6444                )?;
6445                if let Some(w) = &r.when_condition {
6446                    write!(f, " WHERE {w}")?;
6447                }
6448                f.write_str(if r.instead {
6449                    " DO INSTEAD "
6450                } else {
6451                    " DO ALSO "
6452                })?;
6453                if r.commands.is_empty() {
6454                    f.write_str("NOTHING")?;
6455                } else if r.commands.len() == 1 {
6456                    write!(f, "{}", r.commands[0])?;
6457                } else {
6458                    f.write_str("(")?;
6459                    for (i, c) in r.commands.iter().enumerate() {
6460                        if i > 0 {
6461                            f.write_str("; ")?;
6462                        }
6463                        write!(f, "{c}")?;
6464                    }
6465                    f.write_str(")")?;
6466                }
6467                Ok(())
6468            }
6469            Self::DropRule {
6470                name,
6471                table,
6472                if_exists,
6473            } => {
6474                f.write_str("DROP RULE ")?;
6475                if *if_exists {
6476                    f.write_str("IF EXISTS ")?;
6477                }
6478                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6479            }
6480        }
6481    }
6482}
6483
6484impl fmt::Display for CreateDomainStatement {
6485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6486        write!(
6487            f,
6488            "CREATE DOMAIN {} AS {}",
6489            quote_ident(&self.name),
6490            self.base_type
6491        )?;
6492        if let Some(d) = &self.default {
6493            write!(f, " DEFAULT {d}")?;
6494        }
6495        if self.not_null {
6496            f.write_str(" NOT NULL")?;
6497        }
6498        for c in &self.checks {
6499            write!(f, " CHECK ({c})")?;
6500        }
6501        Ok(())
6502    }
6503}
6504
6505impl fmt::Display for CreateTypeStatement {
6506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6507        write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6508        match &self.kind {
6509            TypeKind::Enum { labels } => {
6510                f.write_str("ENUM (")?;
6511                for (i, l) in labels.iter().enumerate() {
6512                    if i > 0 {
6513                        f.write_str(", ")?;
6514                    }
6515                    write!(f, "'{}'", l.replace('\'', "''"))?;
6516                }
6517                f.write_str(")")
6518            }
6519            TypeKind::Composite { fields, .. } => {
6520                f.write_str("(")?;
6521                for (i, (n, t)) in fields.iter().enumerate() {
6522                    if i > 0 {
6523                        f.write_str(", ")?;
6524                    }
6525                    write!(f, "{} {}", quote_ident(n), t)?;
6526                }
6527                f.write_str(")")
6528            }
6529        }
6530    }
6531}
6532
6533impl fmt::Display for CreateMaterializedViewStatement {
6534    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6535        f.write_str("CREATE MATERIALIZED VIEW ")?;
6536        if self.if_not_exists {
6537            f.write_str("IF NOT EXISTS ")?;
6538        }
6539        write!(f, "{}", quote_ident(&self.name))?;
6540        if !self.columns.is_empty() {
6541            f.write_str(" (")?;
6542            for (i, c) in self.columns.iter().enumerate() {
6543                if i > 0 {
6544                    f.write_str(", ")?;
6545                }
6546                write!(f, "{}", quote_ident(c))?;
6547            }
6548            f.write_str(")")?;
6549        }
6550        write!(f, " AS {}", self.body)?;
6551        if !self.with_data {
6552            f.write_str(" WITH NO DATA")?;
6553        }
6554        Ok(())
6555    }
6556}
6557
6558impl fmt::Display for CreateViewStatement {
6559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6560        f.write_str("CREATE ")?;
6561        if self.or_replace {
6562            f.write_str("OR REPLACE ")?;
6563        }
6564        if self.temporary {
6565            f.write_str("TEMPORARY ")?;
6566        }
6567        f.write_str("VIEW ")?;
6568        if self.if_not_exists {
6569            f.write_str("IF NOT EXISTS ")?;
6570        }
6571        write!(f, "{}", quote_ident(&self.name))?;
6572        if !self.columns.is_empty() {
6573            f.write_str(" (")?;
6574            for (i, c) in self.columns.iter().enumerate() {
6575                if i > 0 {
6576                    f.write_str(", ")?;
6577                }
6578                write!(f, "{}", quote_ident(c))?;
6579            }
6580            f.write_str(")")?;
6581        }
6582        write!(f, " AS {}", self.body)?;
6583        match self.check_option {
6584            Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6585            Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6586            None => Ok(()),
6587        }
6588    }
6589}
6590
6591impl fmt::Display for CreateSequenceStatement {
6592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6593        f.write_str("CREATE ")?;
6594        if self.temporary {
6595            f.write_str("TEMPORARY ")?;
6596        }
6597        f.write_str("SEQUENCE ")?;
6598        if self.if_not_exists {
6599            f.write_str("IF NOT EXISTS ")?;
6600        }
6601        write!(f, "{}", quote_ident(&self.name))?;
6602        if let Some(dt) = self.data_type {
6603            write!(f, " AS {dt}")?;
6604        }
6605        write_sequence_options(f, &self.options)
6606    }
6607}
6608
6609impl fmt::Display for AlterSequenceStatement {
6610    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6611        f.write_str("ALTER SEQUENCE ")?;
6612        if self.if_exists {
6613            f.write_str("IF EXISTS ")?;
6614        }
6615        write!(f, "{}", quote_ident(&self.name))?;
6616        write_sequence_options(f, &self.options)
6617    }
6618}
6619
6620impl fmt::Display for SequenceDataType {
6621    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6622        f.write_str(match self {
6623            Self::SmallInt => "smallint",
6624            Self::Int => "integer",
6625            Self::BigInt => "bigint",
6626        })
6627    }
6628}
6629
6630fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6631    if let Some(n) = o.increment {
6632        write!(f, " INCREMENT BY {n}")?;
6633    }
6634    match o.min_value {
6635        Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6636        Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6637        None => {}
6638    }
6639    match o.max_value {
6640        Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6641        Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6642        None => {}
6643    }
6644    if let Some(n) = o.start {
6645        write!(f, " START WITH {n}")?;
6646    }
6647    match o.restart {
6648        Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6649        Some(None) => f.write_str(" RESTART")?,
6650        None => {}
6651    }
6652    if let Some(n) = o.cache {
6653        write!(f, " CACHE {n}")?;
6654    }
6655    match o.cycle {
6656        Some(true) => f.write_str(" CYCLE")?,
6657        Some(false) => f.write_str(" NO CYCLE")?,
6658        None => {}
6659    }
6660    if let Some(ob) = &o.owned_by {
6661        match ob {
6662            SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6663            SequenceOwnedBy::Column { table, column } => {
6664                write!(
6665                    f,
6666                    " OWNED BY {}.{}",
6667                    quote_ident(table),
6668                    quote_ident(column)
6669                )?;
6670            }
6671        }
6672    }
6673    Ok(())
6674}
6675
6676impl fmt::Display for CreateFunctionStatement {
6677    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6678        f.write_str("CREATE ")?;
6679        if self.or_replace {
6680            f.write_str("OR REPLACE ")?;
6681        }
6682        write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6683        for (i, arg) in self.args.iter().enumerate() {
6684            if i > 0 {
6685                f.write_str(", ")?;
6686            }
6687            match arg.mode {
6688                FunctionArgMode::In => {}
6689                FunctionArgMode::Out => f.write_str("OUT ")?,
6690                FunctionArgMode::InOut => f.write_str("INOUT ")?,
6691            }
6692            if let Some(name) = &arg.name {
6693                write!(f, "{} ", quote_ident(name))?;
6694            }
6695            match &arg.ty {
6696                FunctionArgType::Typed(t) => write!(f, "{t}")?,
6697                FunctionArgType::Raw(s) => f.write_str(s)?,
6698            }
6699        }
6700        f.write_str(") RETURNS ")?;
6701        match &self.returns {
6702            FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6703            FunctionReturn::Void => f.write_str("VOID")?,
6704            FunctionReturn::Type(t) => write!(f, "{t}")?,
6705            FunctionReturn::Other(s) => f.write_str(s)?,
6706        }
6707        write!(f, " LANGUAGE {} AS $$", self.language)?;
6708        match &self.body {
6709            FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6710            FunctionBody::Raw(s) => f.write_str(s)?,
6711        }
6712        f.write_str("$$")
6713    }
6714}
6715
6716impl fmt::Display for PlPgSqlBlock {
6717    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6718        if !self.declarations.is_empty() {
6719            f.write_str("DECLARE\n")?;
6720            for d in &self.declarations {
6721                write!(f, "  {} ", quote_ident(&d.name))?;
6722                match &d.ty {
6723                    FunctionArgType::Typed(t) => write!(f, "{t}")?,
6724                    FunctionArgType::Raw(s) => f.write_str(s)?,
6725                }
6726                if let Some(e) = &d.default {
6727                    write!(f, " := {e}")?;
6728                }
6729                f.write_str(";\n")?;
6730            }
6731        }
6732        f.write_str("BEGIN\n")?;
6733        for stmt in &self.statements {
6734            writeln!(f, "  {stmt};")?;
6735        }
6736        // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6737        // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6738        // parsed block through it — so every exception handler a function
6739        // declared was thrown away AT STORE TIME. The block executed fine while
6740        // it was still an AST (a DO block never round-trips through text), which
6741        // is why only functions and triggers lost theirs.
6742        if !self.exception_handlers.is_empty() {
6743            f.write_str("EXCEPTION\n")?;
6744            for h in &self.exception_handlers {
6745                writeln!(f, "  WHEN {} THEN", h.conditions.join(" OR "))?;
6746                for stmt in &h.body {
6747                    writeln!(f, "    {stmt};")?;
6748                }
6749            }
6750        }
6751        f.write_str("END")
6752    }
6753}
6754
6755impl fmt::Display for PlPgSqlStmt {
6756    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6757        match self {
6758            Self::Assign { target, value } => write!(f, "{target} := {value}"),
6759            Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6760            Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6761            Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6762            Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6763            Self::Return(t) => match t {
6764                ReturnTarget::New => f.write_str("RETURN NEW"),
6765                ReturnTarget::Old => f.write_str("RETURN OLD"),
6766                ReturnTarget::Null => f.write_str("RETURN NULL"),
6767                ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6768            },
6769            Self::If {
6770                branches,
6771                else_branch,
6772            } => {
6773                for (i, (cond, body)) in branches.iter().enumerate() {
6774                    if i == 0 {
6775                        write!(f, "IF {cond} THEN ")?;
6776                    } else {
6777                        write!(f, " ELSIF {cond} THEN ")?;
6778                    }
6779                    for (j, s) in body.iter().enumerate() {
6780                        if j > 0 {
6781                            f.write_str("; ")?;
6782                        }
6783                        write!(f, "{s}")?;
6784                    }
6785                }
6786                if !else_branch.is_empty() {
6787                    f.write_str(" ELSE ")?;
6788                    for (j, s) in else_branch.iter().enumerate() {
6789                        if j > 0 {
6790                            f.write_str("; ")?;
6791                        }
6792                        write!(f, "{s}")?;
6793                    }
6794                }
6795                f.write_str(" END IF")
6796            }
6797            Self::Raise {
6798                level,
6799                message,
6800                args,
6801            } => {
6802                let lvl = match level {
6803                    RaiseLevel::Notice => "NOTICE",
6804                    RaiseLevel::Warning => "WARNING",
6805                    RaiseLevel::Info => "INFO",
6806                    RaiseLevel::Log => "LOG",
6807                    RaiseLevel::Debug => "DEBUG",
6808                    RaiseLevel::Exception => "EXCEPTION",
6809                };
6810                write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6811                for a in args {
6812                    write!(f, ", {a}")?;
6813                }
6814                Ok(())
6815            }
6816            Self::EmbeddedSql(s) => write!(f, "{s}"),
6817            Self::Assert { condition, message } => {
6818                write!(f, "ASSERT {condition}")?;
6819                if let Some(m) = message {
6820                    write!(f, ", {m}")?;
6821                }
6822                Ok(())
6823            }
6824            Self::While { condition, body } => {
6825                writeln!(f, "WHILE {condition} LOOP")?;
6826                for s in body {
6827                    writeln!(f, "  {s};")?;
6828                }
6829                f.write_str("END LOOP")
6830            }
6831            Self::ForRange {
6832                var,
6833                start,
6834                end,
6835                reverse,
6836                body,
6837            } => {
6838                write!(f, "FOR {var} IN ")?;
6839                if *reverse {
6840                    f.write_str("REVERSE ")?;
6841                }
6842                writeln!(f, "{start}..{end} LOOP")?;
6843                for s in body {
6844                    writeln!(f, "  {s};")?;
6845                }
6846                f.write_str("END LOOP")
6847            }
6848            Self::Loop { body } => {
6849                writeln!(f, "LOOP")?;
6850                for s in body {
6851                    writeln!(f, "  {s};")?;
6852                }
6853                f.write_str("END LOOP")
6854            }
6855            Self::Exit { when } => {
6856                f.write_str("EXIT")?;
6857                if let Some(c) = when {
6858                    write!(f, " WHEN {c}")?;
6859                }
6860                Ok(())
6861            }
6862            Self::Continue { when } => {
6863                f.write_str("CONTINUE")?;
6864                if let Some(c) = when {
6865                    write!(f, " WHEN {c}")?;
6866                }
6867                Ok(())
6868            }
6869            Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
6870            Self::ForQuery { var, query, body } => {
6871                writeln!(f, "FOR {var} IN ({query}) LOOP")?;
6872                for s in body {
6873                    writeln!(f, "  {s};")?;
6874                }
6875                f.write_str("END LOOP")
6876            }
6877            Self::ForExecute {
6878                var,
6879                sql_expr,
6880                body,
6881            } => {
6882                writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
6883                for s in body {
6884                    writeln!(f, "  {s};")?;
6885                }
6886                f.write_str("END LOOP")
6887            }
6888        }
6889    }
6890}
6891
6892impl fmt::Display for AssignTarget {
6893    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6894        match self {
6895            Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
6896            Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
6897            Self::Local(n) => f.write_str(n),
6898        }
6899    }
6900}
6901
6902impl fmt::Display for CreateTriggerStatement {
6903    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6904        f.write_str("CREATE ")?;
6905        if self.or_replace {
6906            f.write_str("OR REPLACE ")?;
6907        }
6908        write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
6909        match self.timing {
6910            TriggerTiming::Before => f.write_str("BEFORE")?,
6911            TriggerTiming::After => f.write_str("AFTER")?,
6912            TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
6913        }
6914        for (i, e) in self.events.iter().enumerate() {
6915            if i == 0 {
6916                f.write_str(" ")?;
6917            } else {
6918                f.write_str(" OR ")?;
6919            }
6920            match e {
6921                TriggerEvent::Insert => f.write_str("INSERT")?,
6922                TriggerEvent::Update => {
6923                    f.write_str("UPDATE")?;
6924                    if !self.update_columns.is_empty() {
6925                        f.write_str(" OF ")?;
6926                        for (j, col) in self.update_columns.iter().enumerate() {
6927                            if j > 0 {
6928                                f.write_str(", ")?;
6929                            }
6930                            f.write_str(&quote_ident(col))?;
6931                        }
6932                    }
6933                }
6934                TriggerEvent::Delete => f.write_str("DELETE")?,
6935                TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
6936            }
6937        }
6938        write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
6939        match self.for_each {
6940            TriggerForEach::Row => f.write_str("ROW")?,
6941            TriggerForEach::Statement => f.write_str("STATEMENT")?,
6942        }
6943        write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
6944    }
6945}
6946
6947impl fmt::Display for CreateIndexStatement {
6948    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6949        if self.is_unique {
6950            f.write_str("CREATE UNIQUE INDEX ")?;
6951        } else {
6952            f.write_str("CREATE INDEX ")?;
6953        }
6954        if self.if_not_exists {
6955            f.write_str("IF NOT EXISTS ")?;
6956        }
6957        write!(
6958            f,
6959            "{} ON {} ",
6960            quote_ident(&self.name),
6961            quote_ident(&self.table)
6962        )?;
6963        match self.method {
6964            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
6965            IndexMethod::Brin => f.write_str("USING brin ")?,
6966            IndexMethod::Gin => f.write_str("USING gin ")?,
6967            IndexMethod::BTree => {}
6968        }
6969        if let Some(expr) = &self.expression {
6970            write!(f, "({})", expr)?;
6971        } else if self.extra_columns.is_empty() {
6972            // v7.15.0 — preserve operator class on round-trip
6973            // (`(col opclass)`) so WAL replay reconstructs the
6974            // engine-routing intent (e.g. `gin_trgm_ops` →
6975            // trigram-GIN build path).
6976            if let Some(op) = &self.opclass {
6977                write!(f, "({} {})", quote_ident(&self.column), op)?;
6978            } else {
6979                write!(f, "({})", quote_ident(&self.column))?;
6980            }
6981        } else {
6982            // v7.9.14 — multi-column key. Emit each column quoted
6983            // so the round-tripped form re-parses to identical AST.
6984            f.write_str("(")?;
6985            write!(f, "{}", quote_ident(&self.column))?;
6986            for c in &self.extra_columns {
6987                write!(f, ", {}", quote_ident(c))?;
6988            }
6989            f.write_str(")")?;
6990        }
6991        if !self.included_columns.is_empty() {
6992            f.write_str(" INCLUDE (")?;
6993            for (i, c) in self.included_columns.iter().enumerate() {
6994                if i > 0 {
6995                    f.write_str(", ")?;
6996                }
6997                write!(f, "{}", quote_ident(c))?;
6998            }
6999            f.write_str(")")?;
7000        }
7001        if let Some(pred) = &self.partial_predicate {
7002            write!(f, " WHERE {}", pred)?;
7003        }
7004        Ok(())
7005    }
7006}
7007
7008impl fmt::Display for CreateTableStatement {
7009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7010        f.write_str("CREATE TABLE ")?;
7011        if self.if_not_exists {
7012            f.write_str("IF NOT EXISTS ")?;
7013        }
7014        write!(f, "{}", quote_ident(&self.name))?;
7015        // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
7016        // no column list and no constraints; the table inherits its
7017        // columns from the parent at engine-DDL time.
7018        if let Some(spec) = &self.partition_of {
7019            write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
7020            return match &spec.bounds {
7021                PartitionOfBoundsAst::Range { lower, upper } => {
7022                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7023                }
7024                PartitionOfBoundsAst::List { values } => {
7025                    f.write_str("FOR VALUES IN (")?;
7026                    for (i, v) in values.iter().enumerate() {
7027                        if i > 0 {
7028                            f.write_str(", ")?;
7029                        }
7030                        write!(f, "{}", v)?;
7031                    }
7032                    f.write_str(")")
7033                }
7034                PartitionOfBoundsAst::Hash { modulus, remainder } => {
7035                    write!(
7036                        f,
7037                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7038                        modulus, remainder
7039                    )
7040                }
7041                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7042            };
7043        }
7044        f.write_str(" (")?;
7045        for (i, col) in self.columns.iter().enumerate() {
7046            if i > 0 {
7047                f.write_str(", ")?;
7048            }
7049            write!(f, "{col}")?;
7050        }
7051        // v7.6.0 — render FK constraints in table-level form, after
7052        // the column list. WAL replay round-trips through Display, so
7053        // every FK must serialise here for replay to reconstruct the
7054        // schema bit-for-bit.
7055        for fk in &self.foreign_keys {
7056            f.write_str(", ")?;
7057            write!(f, "{fk}")?;
7058        }
7059        // v7.13.0 — render table-level constraints (PRIMARY KEY /
7060        // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
7061        // column-level UNIQUE / CHECK get lifted to this list at
7062        // parse time, so emitting only here avoids double-counting.
7063        for tc in &self.table_constraints {
7064            f.write_str(", ")?;
7065            write!(f, "{tc}")?;
7066        }
7067        f.write_str(")")?;
7068        // v7.37.6-B — partition-parent suffix renders after the
7069        // closing column-list paren, before the optional MySQL
7070        // table-options tail (which Display doesn't currently emit).
7071        if let Some(spec) = &self.partition_by {
7072            f.write_str(" PARTITION BY ")?;
7073            match spec.kind {
7074                PartitionKindAst::Range => f.write_str("RANGE ")?,
7075                PartitionKindAst::List => f.write_str("LIST ")?,
7076                PartitionKindAst::Hash => f.write_str("HASH ")?,
7077            }
7078            f.write_str("(")?;
7079            for (i, col) in spec.key_columns.iter().enumerate() {
7080                if i > 0 {
7081                    f.write_str(", ")?;
7082                }
7083                f.write_str(&quote_ident(col))?;
7084            }
7085            f.write_str(")")?;
7086        }
7087        Ok(())
7088    }
7089}
7090
7091fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
7092    match t {
7093        AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
7094        AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
7095            write!(f, "REPLICA IDENTITY USING INDEX {index}")
7096        }
7097        AlterTableTarget::Inherit { parent, detach } => {
7098            if *detach {
7099                write!(f, "NO INHERIT {parent}")
7100            } else {
7101                write!(f, "INHERIT {parent}")
7102            }
7103        }
7104        AlterTableTarget::SetHotTierBytes(n) => {
7105            write!(f, "SET hot_tier_bytes = {n}")
7106        }
7107        AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
7108        AlterTableTarget::DropForeignKey { name, if_exists } => {
7109            f.write_str("DROP CONSTRAINT ")?;
7110            if *if_exists {
7111                f.write_str("IF EXISTS ")?;
7112            }
7113            write!(f, "{}", quote_ident(name))
7114        }
7115        AlterTableTarget::DropIndex { name, if_exists } => {
7116            f.write_str("DROP INDEX ")?;
7117            if *if_exists {
7118                f.write_str("IF EXISTS ")?;
7119            }
7120            write!(f, "{}", quote_ident(name))
7121        }
7122        AlterTableTarget::AddColumn {
7123            column,
7124            if_not_exists,
7125        } => {
7126            f.write_str("ADD COLUMN ")?;
7127            if *if_not_exists {
7128                f.write_str("IF NOT EXISTS ")?;
7129            }
7130            write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
7131            if !column.nullable {
7132                f.write_str(" NOT NULL")?;
7133            }
7134            if let Some(d) = &column.default {
7135                write!(f, " DEFAULT {d}")?;
7136            }
7137            if column.auto_increment {
7138                f.write_str(" AUTO_INCREMENT")?;
7139            }
7140            if column.is_primary_key {
7141                f.write_str(" PRIMARY KEY")?;
7142            }
7143            Ok(())
7144        }
7145        AlterTableTarget::AlterColumnType {
7146            column,
7147            new_type,
7148            using,
7149            collation,
7150        } => {
7151            write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
7152            if let Some((_, name)) = collation {
7153                write!(f, " COLLATE {}", quote_ident(name))?;
7154            }
7155            if let Some(u) = using {
7156                write!(f, " USING {u}")?;
7157            }
7158            Ok(())
7159        }
7160        AlterTableTarget::DropColumn {
7161            column,
7162            if_exists,
7163            cascade,
7164        } => {
7165            f.write_str("DROP COLUMN ")?;
7166            if *if_exists {
7167                f.write_str("IF EXISTS ")?;
7168            }
7169            write!(f, "{}", quote_ident(column))?;
7170            if *cascade {
7171                f.write_str(" CASCADE")?;
7172            }
7173            Ok(())
7174        }
7175        AlterTableTarget::AddTableConstraint(tc) => {
7176            write!(f, "ADD {tc}")
7177        }
7178        AlterTableTarget::ValidateConstraint { name } => {
7179            write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
7180        }
7181        AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
7182        AlterTableTarget::ClusterOn { index } => match index {
7183            Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
7184            None => f.write_str("SET WITHOUT CLUSTER"),
7185        },
7186        AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
7187            // Round-trip-safe spelling: re-parsing this form lowers
7188            // back to SetColumnAutoIncrement (the nextval default is
7189            // how pg_dump says "serial").
7190            let seq = seq_name
7191                .clone()
7192                .unwrap_or_else(|| alloc::format!("{column}_seq"));
7193            write!(
7194                f,
7195                "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
7196                quote_ident(column)
7197            )
7198        }
7199        AlterTableTarget::RenameColumn { old, new } => {
7200            write!(
7201                f,
7202                "RENAME COLUMN {} TO {}",
7203                quote_ident(old),
7204                quote_ident(new)
7205            )
7206        }
7207        AlterTableTarget::RenameConstraint { old, new } => {
7208            write!(
7209                f,
7210                "RENAME CONSTRAINT {} TO {}",
7211                quote_ident(old),
7212                quote_ident(new)
7213            )
7214        }
7215        AlterTableTarget::RenameTable { new } => {
7216            write!(f, "RENAME TO {}", quote_ident(new))
7217        }
7218        AlterTableTarget::SetTriggerEnabled { which, enabled } => {
7219            f.write_str(if *enabled {
7220                "ENABLE TRIGGER "
7221            } else {
7222                "DISABLE TRIGGER "
7223            })?;
7224            match which {
7225                TriggerSelector::All => f.write_str("ALL"),
7226                TriggerSelector::Named(n) => f.write_str(&quote_ident(n)),
7227            }
7228        }
7229        AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
7230            (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
7231            (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
7232            (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
7233            (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
7234            (None, None) => Ok(()),
7235        },
7236        AlterTableTarget::AttachPartition { child, bounds } => {
7237            write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
7238            match bounds {
7239                PartitionOfBoundsAst::Range { lower, upper } => {
7240                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7241                }
7242                PartitionOfBoundsAst::List { values } => {
7243                    f.write_str("FOR VALUES IN (")?;
7244                    for (i, v) in values.iter().enumerate() {
7245                        if i > 0 {
7246                            f.write_str(", ")?;
7247                        }
7248                        write!(f, "{}", v)?;
7249                    }
7250                    f.write_str(")")
7251                }
7252                PartitionOfBoundsAst::Hash { modulus, remainder } => {
7253                    write!(
7254                        f,
7255                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7256                        modulus, remainder
7257                    )
7258                }
7259                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7260            }
7261        }
7262        AlterTableTarget::DetachPartition {
7263            child,
7264            concurrently,
7265            finalize,
7266        } => {
7267            write!(f, "DETACH PARTITION {}", quote_ident(child))?;
7268            if *concurrently {
7269                f.write_str(" CONCURRENTLY")?;
7270            }
7271            if *finalize {
7272                f.write_str(" FINALIZE")?;
7273            }
7274            Ok(())
7275        }
7276        AlterTableTarget::AlterColumnSetDefault {
7277            column,
7278            default_expr,
7279        } => write!(
7280            f,
7281            "ALTER COLUMN {} SET DEFAULT {}",
7282            quote_ident(column),
7283            default_expr
7284        ),
7285        AlterTableTarget::AlterColumnDropDefault { column } => {
7286            write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
7287        }
7288        AlterTableTarget::AlterColumnSetNotNull { column } => {
7289            write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
7290        }
7291        AlterTableTarget::AlterColumnDropNotNull { column } => {
7292            write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
7293        }
7294        AlterTableTarget::AlterColumnRestart { column, with } => {
7295            write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
7296            if let Some(n) = with {
7297                write!(f, " WITH {n}")?;
7298            }
7299            Ok(())
7300        }
7301        AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
7302            write!(
7303                f,
7304                "ALTER COLUMN {} DROP EXPRESSION{}",
7305                quote_ident(column),
7306                if *if_exists { " IF EXISTS" } else { "" }
7307            )
7308        }
7309        AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
7310            write!(
7311                f,
7312                "ALTER COLUMN {} DROP IDENTITY{}",
7313                quote_ident(column),
7314                if *if_exists { " IF EXISTS" } else { "" }
7315            )
7316        }
7317        AlterTableTarget::AlterColumnSetExpression { column, expr } => {
7318            write!(
7319                f,
7320                "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
7321                quote_ident(column)
7322            )
7323        }
7324    }
7325}
7326
7327impl fmt::Display for TableConstraint {
7328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7329        match self {
7330            Self::PrimaryKey { name, columns, .. } => {
7331                if let Some(n) = name {
7332                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7333                }
7334                f.write_str("PRIMARY KEY (")?;
7335                for (i, c) in columns.iter().enumerate() {
7336                    if i > 0 {
7337                        f.write_str(", ")?;
7338                    }
7339                    f.write_str(&quote_ident(c))?;
7340                }
7341                f.write_str(")")
7342            }
7343            Self::Unique {
7344                name,
7345                columns,
7346                nulls_not_distinct,
7347                ..
7348            } => {
7349                if let Some(n) = name {
7350                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7351                }
7352                f.write_str("UNIQUE ")?;
7353                if *nulls_not_distinct {
7354                    f.write_str("NULLS NOT DISTINCT ")?;
7355                }
7356                f.write_str("(")?;
7357                for (i, c) in columns.iter().enumerate() {
7358                    if i > 0 {
7359                        f.write_str(", ")?;
7360                    }
7361                    f.write_str(&quote_ident(c))?;
7362                }
7363                f.write_str(")")
7364            }
7365            Self::Check {
7366                name,
7367                expr,
7368                not_valid,
7369            } => {
7370                if let Some(n) = name {
7371                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7372                }
7373                write!(f, "CHECK ({expr})")?;
7374                if *not_valid {
7375                    write!(f, " NOT VALID")?;
7376                }
7377                Ok(())
7378            }
7379            Self::Index { name, columns } => {
7380                f.write_str("KEY ")?;
7381                if let Some(n) = name {
7382                    write!(f, "{} ", quote_ident(n))?;
7383                }
7384                f.write_str("(")?;
7385                for (i, c) in columns.iter().enumerate() {
7386                    if i > 0 {
7387                        f.write_str(", ")?;
7388                    }
7389                    f.write_str(&quote_ident(c))?;
7390                }
7391                f.write_str(")")
7392            }
7393            Self::FulltextIndex { name, columns } => {
7394                // Mysqldump emits `FULLTEXT KEY name (cols)` —
7395                // Display rounds back to that shape so dump
7396                // replay reproduces the input verbatim.
7397                f.write_str("FULLTEXT KEY ")?;
7398                if let Some(n) = name {
7399                    write!(f, "{} ", quote_ident(n))?;
7400                }
7401                f.write_str("(")?;
7402                for (i, c) in columns.iter().enumerate() {
7403                    if i > 0 {
7404                        f.write_str(", ")?;
7405                    }
7406                    f.write_str(&quote_ident(c))?;
7407                }
7408                f.write_str(")")
7409            }
7410            Self::Exclude {
7411                name,
7412                method,
7413                elements,
7414            } => {
7415                if let Some(n) = name {
7416                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7417                }
7418                f.write_str("EXCLUDE ")?;
7419                if let Some(m) = method {
7420                    write!(f, "USING {m} ")?;
7421                }
7422                f.write_str("(")?;
7423                for (i, (col, op)) in elements.iter().enumerate() {
7424                    if i > 0 {
7425                        f.write_str(", ")?;
7426                    }
7427                    write!(f, "{} WITH {op}", quote_ident(col))?;
7428                }
7429                f.write_str(")")
7430            }
7431        }
7432    }
7433}
7434
7435impl fmt::Display for ForeignKeyConstraint {
7436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7437        if let Some(name) = &self.name {
7438            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7439        }
7440        f.write_str("FOREIGN KEY (")?;
7441        for (i, c) in self.columns.iter().enumerate() {
7442            if i > 0 {
7443                f.write_str(", ")?;
7444            }
7445            f.write_str(&quote_ident(c))?;
7446        }
7447        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7448        if !self.parent_columns.is_empty() {
7449            f.write_str(" (")?;
7450            for (i, c) in self.parent_columns.iter().enumerate() {
7451                if i > 0 {
7452                    f.write_str(", ")?;
7453                }
7454                f.write_str(&quote_ident(c))?;
7455            }
7456            f.write_str(")")?;
7457        }
7458        // Only render non-default actions to keep Display output
7459        // close to user input. SPG's default is RESTRICT (matches
7460        // SQL spec).
7461        if self.on_delete != FkAction::Restrict {
7462            write!(f, " ON DELETE {}", self.on_delete)?;
7463        }
7464        if self.on_update != FkAction::Restrict {
7465            write!(f, " ON UPDATE {}", self.on_update)?;
7466        }
7467        Ok(())
7468    }
7469}
7470
7471impl fmt::Display for FkAction {
7472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7473        match self {
7474            Self::Restrict => f.write_str("RESTRICT"),
7475            Self::Cascade => f.write_str("CASCADE"),
7476            Self::SetNull => f.write_str("SET NULL"),
7477            Self::SetDefault => f.write_str("SET DEFAULT"),
7478            Self::NoAction => f.write_str("NO ACTION"),
7479        }
7480    }
7481}
7482
7483impl fmt::Display for ColumnDef {
7484    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7485        // v7.30.1 (mailrs round-24 class audit) — the type position
7486        // must re-parse to the same ColumnDef: a user-defined type
7487        // reference and the MySQL inline ENUM / SET value lists all
7488        // lower `ty` to Text, so rendering `ty` lost them.
7489        write!(f, "{}", quote_ident(&self.name))?;
7490        if let Some(ut) = &self.user_type_ref {
7491            write!(f, " {}", quote_ident(ut))?;
7492        } else if let Some(variants) = &self.inline_enum_variants {
7493            write_variant_list(f, "ENUM", variants)?;
7494        } else if let Some(variants) = &self.inline_set_variants {
7495            write_variant_list(f, "SET", variants)?;
7496        } else {
7497            write!(f, " {}", self.ty)?;
7498        }
7499        if self.is_unsigned {
7500            f.write_str(" UNSIGNED")?;
7501        }
7502        // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7503        // DDL. Only emits when non-default so the typical output
7504        // stays unchanged.
7505        match self.collation {
7506            Collation::Binary => {}
7507            Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7508        }
7509        if let Some(d) = &self.default {
7510            write!(f, " DEFAULT {d}")?;
7511        }
7512        if self.auto_increment {
7513            f.write_str(" AUTO_INCREMENT")?;
7514        }
7515        if !self.nullable {
7516            f.write_str(" NOT NULL")?;
7517        }
7518        // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7519        // is NOT lifted to a table-level constraint at parse time
7520        // (unlike UNIQUE / CHECK), so the WAL round trip of a
7521        // prepared CREATE TABLE silently dropped the primary key.
7522        if self.is_primary_key {
7523            f.write_str(" PRIMARY KEY")?;
7524        }
7525        // The parser accepts only CURRENT_TIMESTAMP here (stored as
7526        // now()), so that spelling is the lossless round trip.
7527        if self.on_update_runtime.is_some() {
7528            f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7529        }
7530        // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7531        // replay reconstructs the computed-column declaration. The
7532        // expression sits inside a single set of parens; STORED is
7533        // the only variant the parser accepts.
7534        if let Some(gen_expr) = &self.generated_stored_expr {
7535            write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7536        }
7537        Ok(())
7538    }
7539}
7540
7541/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7542/// types (MySQL flavour; `ty` is Text underneath).
7543fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7544    write!(f, " {kw}(")?;
7545    for (i, v) in variants.iter().enumerate() {
7546        if i > 0 {
7547            f.write_str(", ")?;
7548        }
7549        write!(f, "'{}'", v.replace('\'', "''"))?;
7550    }
7551    f.write_str(")")
7552}
7553
7554impl fmt::Display for InsertStatement {
7555    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7556        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7557        if let Some(cols) = &self.columns {
7558            f.write_str(" (")?;
7559            for (i, c) in cols.iter().enumerate() {
7560                if i > 0 {
7561                    f.write_str(", ")?;
7562                }
7563                f.write_str(&quote_ident(c))?;
7564            }
7565            f.write_str(")")?;
7566        }
7567        // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7568        // skipping the VALUES list (mailrs round-5 G4).
7569        if let Some(sel) = &self.select_source {
7570            write!(f, " {sel}")?;
7571        } else {
7572            f.write_str(" VALUES ")?;
7573            for (ri, row) in self.rows.iter().enumerate() {
7574                if ri > 0 {
7575                    f.write_str(", ")?;
7576                }
7577                f.write_str("(")?;
7578                for (i, v) in row.iter().enumerate() {
7579                    if i > 0 {
7580                        f.write_str(", ")?;
7581                    }
7582                    write!(f, "{v}")?;
7583                }
7584                f.write_str(")")?;
7585            }
7586        }
7587        // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7588        // Display round trip: WAL persistence renders the bind-final
7589        // AST through this impl, and a replayed bare INSERT turns a
7590        // legal upsert no-op into a UNIQUE violation that refuses to
7591        // open the catalog.
7592        if let Some(oc) = &self.on_conflict {
7593            write!(f, " {oc}")?;
7594        }
7595        write_returning(self.returning.as_deref(), f)?;
7596        Ok(())
7597    }
7598}
7599
7600/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7601/// parser produced, so the AST→SQL round trip preserves upsert
7602/// semantics (WAL replay depends on it).
7603impl fmt::Display for OnConflictClause {
7604    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7605        f.write_str("ON CONFLICT")?;
7606        if let Some(name) = &self.constraint_name {
7607            write!(f, " ON CONSTRAINT {name}")?;
7608        }
7609        if !self.target_columns.is_empty() {
7610            f.write_str(" (")?;
7611            for (i, c) in self.target_columns.iter().enumerate() {
7612                if i > 0 {
7613                    f.write_str(", ")?;
7614                }
7615                f.write_str(&quote_ident(c))?;
7616            }
7617            f.write_str(")")?;
7618        }
7619        if let Some(w) = &self.index_where {
7620            write!(f, " WHERE {w}")?;
7621        }
7622        match &self.action {
7623            OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7624            OnConflictAction::Update {
7625                assignments,
7626                where_,
7627            } => {
7628                f.write_str(" DO UPDATE SET ")?;
7629                for (i, (col, expr)) in assignments.iter().enumerate() {
7630                    if i > 0 {
7631                        f.write_str(", ")?;
7632                    }
7633                    write!(f, "{} = {expr}", quote_ident(col))?;
7634                }
7635                if let Some(w) = where_ {
7636                    write!(f, " WHERE {w}")?;
7637                }
7638                Ok(())
7639            }
7640        }
7641    }
7642}
7643
7644/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7645/// tail for the three DML Display impls.
7646fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7647    let Some(items) = ret else {
7648        return Ok(());
7649    };
7650    f.write_str(" RETURNING ")?;
7651    for (i, item) in items.iter().enumerate() {
7652        if i > 0 {
7653            f.write_str(", ")?;
7654        }
7655        write!(f, "{item}")?;
7656    }
7657    Ok(())
7658}
7659
7660impl fmt::Display for UpdateStatement {
7661    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7662        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7663        for (i, (col, expr)) in self.assignments.iter().enumerate() {
7664            if i > 0 {
7665                f.write_str(", ")?;
7666            }
7667            write!(f, "{} = {expr}", quote_ident(col))?;
7668        }
7669        if let Some(w) = &self.where_ {
7670            write!(f, " WHERE {w}")?;
7671        }
7672        // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7673        if let Some(ol) = self.order_limit.as_deref() {
7674            if !ol.order_by.is_empty() {
7675                f.write_str(" ORDER BY ")?;
7676                for (i, o) in ol.order_by.iter().enumerate() {
7677                    if i > 0 {
7678                        f.write_str(", ")?;
7679                    }
7680                    write!(f, "{}", o.expr)?;
7681                    if o.desc {
7682                        f.write_str(" DESC")?;
7683                    }
7684                    match o.nulls_first {
7685                        Some(true) => f.write_str(" NULLS FIRST")?,
7686                        Some(false) => f.write_str(" NULLS LAST")?,
7687                        None => {}
7688                    }
7689                }
7690            }
7691            if let Some(n) = ol.limit {
7692                write!(f, " LIMIT {n}")?;
7693            }
7694        }
7695        write_returning(self.returning.as_deref(), f)?;
7696        Ok(())
7697    }
7698}
7699
7700impl fmt::Display for DeleteStatement {
7701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7702        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7703        if let Some(w) = &self.where_ {
7704            write!(f, " WHERE {w}")?;
7705        }
7706        write_returning(self.returning.as_deref(), f)?;
7707        Ok(())
7708    }
7709}
7710
7711impl fmt::Display for CteBody {
7712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7713        match self {
7714            Self::Select(s) => write!(f, "{s}"),
7715            Self::Insert(s) => write!(f, "{s}"),
7716            Self::Update(s) => write!(f, "{s}"),
7717            Self::Delete(s) => write!(f, "{s}"),
7718            Self::Merge(s) => write!(f, "{s}"),
7719        }
7720    }
7721}
7722
7723impl fmt::Display for MergeStatement {
7724    // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7725    // (it round-trips for the cases tests cover, not for
7726    // round-tripping every edge of the surface).
7727    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7728        fmt_with_clause(&self.ctes, f)?;
7729        f.write_str("MERGE INTO ")?;
7730        write!(f, "{}", quote_ident(&self.target))?;
7731        if let Some(a) = &self.target_alias {
7732            write!(f, " {}", quote_ident(a))?;
7733        }
7734        f.write_str(" USING ")?;
7735        if let Some(sub) = &self.source_select {
7736            write!(f, "({sub})")?;
7737        } else {
7738            write!(f, "{}", quote_ident(&self.source))?;
7739        }
7740        if let Some(a) = &self.source_alias {
7741            write!(f, " {}", quote_ident(a))?;
7742        }
7743        if !self.source_column_aliases.is_empty() {
7744            f.write_str("(")?;
7745            for (i, c) in self.source_column_aliases.iter().enumerate() {
7746                if i > 0 {
7747                    f.write_str(", ")?;
7748                }
7749                write!(f, "{}", quote_ident(c))?;
7750            }
7751            f.write_str(")")?;
7752        }
7753        write!(f, " ON {}", self.on)?;
7754        for clause in &self.clauses {
7755            f.write_str(" WHEN ")?;
7756            f.write_str(match clause.matched {
7757                MergeMatched::Matched => "MATCHED",
7758                MergeMatched::NotMatched => "NOT MATCHED",
7759                MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7760            })?;
7761            if let Some(c) = &clause.condition {
7762                write!(f, " AND {c}")?;
7763            }
7764            f.write_str(" THEN ")?;
7765            match &clause.action {
7766                MergeAction::Insert { columns, values } => {
7767                    f.write_str("INSERT ")?;
7768                    // A column list is optional (round 146): the bare
7769                    // `INSERT VALUES (…)` form maps positionally.
7770                    if !columns.is_empty() {
7771                        f.write_str("(")?;
7772                        for (i, c) in columns.iter().enumerate() {
7773                            if i > 0 {
7774                                f.write_str(", ")?;
7775                            }
7776                            write!(f, "{}", quote_ident(c))?;
7777                        }
7778                        f.write_str(") ")?;
7779                    }
7780                    f.write_str("VALUES (")?;
7781                    for (i, v) in values.iter().enumerate() {
7782                        if i > 0 {
7783                            f.write_str(", ")?;
7784                        }
7785                        write!(f, "{v}")?;
7786                    }
7787                    f.write_str(")")?;
7788                }
7789                MergeAction::Update { assignments } => {
7790                    f.write_str("UPDATE SET ")?;
7791                    for (i, (c, e)) in assignments.iter().enumerate() {
7792                        if i > 0 {
7793                            f.write_str(", ")?;
7794                        }
7795                        write!(f, "{} = {e}", quote_ident(c))?;
7796                    }
7797                }
7798                MergeAction::Delete => f.write_str("DELETE")?,
7799                MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7800            }
7801        }
7802        if let Some(items) = &self.returning {
7803            f.write_str(" RETURNING ")?;
7804            for (i, it) in items.iter().enumerate() {
7805                if i > 0 {
7806                    f.write_str(", ")?;
7807                }
7808                write!(f, "{it}")?;
7809            }
7810        }
7811        Ok(())
7812    }
7813}
7814
7815/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
7816/// carry a CTE list and must round-trip it identically.
7817fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
7818    if ctes.is_empty() {
7819        return Ok(());
7820    }
7821    f.write_str("WITH ")?;
7822    if ctes.iter().any(|c| c.recursive) {
7823        f.write_str("RECURSIVE ")?;
7824    }
7825    for (i, cte) in ctes.iter().enumerate() {
7826        if i > 0 {
7827            f.write_str(", ")?;
7828        }
7829        f.write_str(&quote_ident(&cte.name))?;
7830        if !cte.column_overrides.is_empty() {
7831            f.write_str(" (")?;
7832            for (ci, c) in cte.column_overrides.iter().enumerate() {
7833                if ci > 0 {
7834                    f.write_str(", ")?;
7835                }
7836                f.write_str(&quote_ident(c))?;
7837            }
7838            f.write_str(")")?;
7839        }
7840        write!(f, " AS ({})", cte.body)?;
7841    }
7842    f.write_str(" ")
7843}
7844
7845impl fmt::Display for SelectStatement {
7846    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7847        // v7.30.1 (mailrs round-24 class audit) — the WITH clause
7848        // must survive the round trip; a CTE-using statement
7849        // re-parsed without it references undefined tables.
7850        fmt_with_clause(&self.ctes, f)?;
7851        write_bare_select(self, f)?;
7852        for (kind, peer) in &self.unions {
7853            f.write_str(match kind {
7854                UnionKind::Distinct => " UNION ",
7855                UnionKind::All => " UNION ALL ",
7856                UnionKind::Intersect => " INTERSECT ",
7857                UnionKind::IntersectAll => " INTERSECT ALL ",
7858                UnionKind::Except => " EXCEPT ",
7859                UnionKind::ExceptAll => " EXCEPT ALL ",
7860            })?;
7861            write_bare_select(peer, f)?;
7862        }
7863        if !self.order_by.is_empty() {
7864            f.write_str(" ORDER BY ")?;
7865            for (i, o) in self.order_by.iter().enumerate() {
7866                if i > 0 {
7867                    f.write_str(", ")?;
7868                }
7869                write!(f, "{}", o.expr)?;
7870                if o.desc {
7871                    f.write_str(" DESC")?;
7872                }
7873                match o.nulls_first {
7874                    Some(true) => f.write_str(" NULLS FIRST")?,
7875                    Some(false) => f.write_str(" NULLS LAST")?,
7876                    None => {}
7877                }
7878            }
7879        }
7880        // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
7881        // exists in the FETCH FIRST spelling; rendering it as LIMIT
7882        // dropped the tie-extension semantics on replay. The parser
7883        // accepts OFFSET before FETCH, so keep that order here.
7884        if self.limit_with_ties {
7885            if let Some(o) = &self.offset {
7886                write!(f, " OFFSET {o}")?;
7887            }
7888            if let Some(n) = &self.limit {
7889                write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
7890            }
7891        } else {
7892            if let Some(n) = &self.limit {
7893                write!(f, " LIMIT {n}")?;
7894            }
7895            if let Some(o) = &self.offset {
7896                write!(f, " OFFSET {o}")?;
7897            }
7898        }
7899        Ok(())
7900    }
7901}
7902
7903fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7904    f.write_str("SELECT ")?;
7905    if s.distinct {
7906        f.write_str("DISTINCT ")?;
7907    }
7908    write_bare_select_body(s, f)
7909}
7910
7911fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7912    for (i, item) in s.items.iter().enumerate() {
7913        if i > 0 {
7914            f.write_str(", ")?;
7915        }
7916        write!(f, "{item}")?;
7917    }
7918    if let Some(t) = &s.from {
7919        write!(f, " FROM {t}")?;
7920    }
7921    if let Some(e) = &s.where_ {
7922        write!(f, " WHERE {e}")?;
7923    }
7924    if let Some(gs) = &s.group_by {
7925        f.write_str(" GROUP BY ")?;
7926        for (i, g) in gs.iter().enumerate() {
7927            if i > 0 {
7928                f.write_str(", ")?;
7929            }
7930            write!(f, "{g}")?;
7931        }
7932    } else if s.group_by_all {
7933        // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
7934        // shortcut parses to group_by: None + this flag; dropping
7935        // it turned an aggregate query into a bare projection on
7936        // re-parse.
7937        f.write_str(" GROUP BY ALL")?;
7938    }
7939    if let Some(h) = &s.having {
7940        write!(f, " HAVING {h}")?;
7941    }
7942    Ok(())
7943}
7944
7945impl fmt::Display for SelectItem {
7946    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7947        match self {
7948            Self::Wildcard => f.write_str("*"),
7949            Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
7950            Self::Expr { expr, alias } => {
7951                write!(f, "{expr}")?;
7952                if let Some(a) = alias {
7953                    write!(f, " AS {}", quote_ident(a))?;
7954                }
7955                Ok(())
7956            }
7957        }
7958    }
7959}
7960
7961impl fmt::Display for FromClause {
7962    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7963        write!(f, "{}", self.primary)?;
7964        for j in &self.joins {
7965            match j.kind {
7966                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
7967                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
7968                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
7969                JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
7970                JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
7971                JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
7972            }
7973            if let Some(on) = &j.on {
7974                write!(f, " ON {on}")?;
7975            }
7976        }
7977        Ok(())
7978    }
7979}
7980
7981/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
7982/// for NESTED). Kept close to the parser's grammar so it re-parses.
7983fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
7984    for (i, c) in cols.iter().enumerate() {
7985        if i > 0 {
7986            f.write_str(", ")?;
7987        }
7988        match c {
7989            JsonTableColumn::Ordinality { name } => {
7990                write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
7991            }
7992            JsonTableColumn::Nested { path, columns } => {
7993                write!(f, "NESTED PATH '{path}' COLUMNS (")?;
7994                fmt_json_table_columns(f, columns)?;
7995                f.write_str(")")?;
7996            }
7997            JsonTableColumn::Regular {
7998                name,
7999                ty,
8000                path,
8001                exists,
8002                format_json,
8003                wrapper,
8004                on_empty,
8005                on_error,
8006            } => {
8007                write!(f, "{} {ty}", quote_ident(name))?;
8008                if *format_json {
8009                    f.write_str(" FORMAT JSON")?;
8010                }
8011                if *exists {
8012                    write!(f, " EXISTS PATH '{path}'")?;
8013                } else {
8014                    write!(f, " PATH '{path}'")?;
8015                }
8016                if *wrapper {
8017                    f.write_str(" WITH WRAPPER")?;
8018                }
8019                if let JsonTableOnBehavior::Error = on_empty {
8020                    f.write_str(" ERROR ON EMPTY")?;
8021                } else if let JsonTableOnBehavior::Default(e) = on_empty {
8022                    write!(f, " DEFAULT {e} ON EMPTY")?;
8023                }
8024                if let JsonTableOnBehavior::Error = on_error {
8025                    f.write_str(" ERROR ON ERROR")?;
8026                } else if let JsonTableOnBehavior::Default(e) = on_error {
8027                    write!(f, " DEFAULT {e} ON ERROR")?;
8028                }
8029            }
8030        }
8031    }
8032    Ok(())
8033}
8034
8035impl fmt::Display for TableRef {
8036    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8037        // v7.30.1 (mailrs round-24 class audit) — the dynamic
8038        // table-ref shapes must round-trip: rendering only the
8039        // (synthetic) name turned LATERAL / unnest() /
8040        // generate_series() into references to nonexistent tables
8041        // on re-parse.
8042        // v7.39 (round 205) — JSON_TABLE round-trips through Display
8043        // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
8044        if let Some(jt) = &self.json_table {
8045            write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
8046            if !jt.passing.is_empty() {
8047                f.write_str(" PASSING ")?;
8048                for (i, (n, e)) in jt.passing.iter().enumerate() {
8049                    if i > 0 {
8050                        f.write_str(", ")?;
8051                    }
8052                    write!(f, "{e} AS {}", quote_ident(n))?;
8053                }
8054            }
8055            f.write_str(" COLUMNS (")?;
8056            fmt_json_table_columns(f, &jt.columns)?;
8057            f.write_str(")")?;
8058            if let Some(a) = &self.alias {
8059                write!(f, " AS {}", quote_ident(a))?;
8060            }
8061            return Ok(());
8062        }
8063        if let Some(inner) = &self.lateral_subquery {
8064            write!(f, "LATERAL ({inner})")?;
8065            if let Some(a) = &self.alias {
8066                write!(f, " AS {}", quote_ident(a))?;
8067                // v7.37 D.28 — a derived table on the lateral_subquery channel
8068                // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
8069                // lowers here). Rendering the alias without the column list lost
8070                // the column names on re-parse (a view body round-trips through
8071                // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
8072                if !self.unnest_column_aliases.is_empty() {
8073                    f.write_str(" (")?;
8074                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8075                        if i > 0 {
8076                            f.write_str(", ")?;
8077                        }
8078                        f.write_str(&quote_ident(c))?;
8079                    }
8080                    f.write_str(")")?;
8081                }
8082            }
8083            return Ok(());
8084        }
8085        if let Some(expr) = &self.unnest_expr {
8086            write!(f, "UNNEST({expr})")?;
8087            if let Some(a) = &self.alias {
8088                write!(f, " AS {}", quote_ident(a))?;
8089                if !self.unnest_column_aliases.is_empty() {
8090                    f.write_str(" (")?;
8091                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8092                        if i > 0 {
8093                            f.write_str(", ")?;
8094                        }
8095                        f.write_str(&quote_ident(c))?;
8096                    }
8097                    f.write_str(")")?;
8098                }
8099            }
8100            return Ok(());
8101        }
8102        // 7.38.1 S5.1 — a FROM-position table function must re-render
8103        // as the CALL, not its bare name: ARRAY(subquery) desugars by
8104        // re-parsing the subquery's canonical text, and a dropped
8105        // argument list turned `pg_options_to_table(x)` into a
8106        // relation lookup that does not exist.
8107        if let Some(call) = &self.table_fn_call {
8108            let (fn_name, args) = call.as_ref();
8109            write!(f, "{fn_name}(")?;
8110            for (i, a) in args.iter().enumerate() {
8111                if i > 0 {
8112                    f.write_str(", ")?;
8113                }
8114                write!(f, "{a}")?;
8115            }
8116            f.write_str(")")?;
8117            if let Some(a) = &self.alias {
8118                write!(f, " AS {}", quote_ident(a))?;
8119                if !self.unnest_column_aliases.is_empty() {
8120                    f.write_str("(")?;
8121                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8122                        if i > 0 {
8123                            f.write_str(", ")?;
8124                        }
8125                        write!(f, "{}", quote_ident(c))?;
8126                    }
8127                    f.write_str(")")?;
8128                }
8129            }
8130            return Ok(());
8131        }
8132        if let Some(args) = &self.generate_series_args {
8133            f.write_str("generate_series(")?;
8134            for (i, a) in args.iter().enumerate() {
8135                if i > 0 {
8136                    f.write_str(", ")?;
8137                }
8138                write!(f, "{a}")?;
8139            }
8140            f.write_str(")")?;
8141            if let Some(a) = &self.alias {
8142                write!(f, " AS {}", quote_ident(a))?;
8143            }
8144            return Ok(());
8145        }
8146        write!(f, "{}", quote_ident(&self.name))?;
8147        if let Some(seg) = self.as_of_segment {
8148            write!(f, " AS OF SEGMENT {seg}")?;
8149        }
8150        if let Some(a) = &self.alias {
8151            write!(f, " AS {}", quote_ident(a))?;
8152        }
8153        Ok(())
8154    }
8155}
8156
8157impl fmt::Display for ColumnName {
8158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8159        if let Some(q) = &self.qualifier {
8160            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
8161        } else {
8162            write!(f, "{}", quote_ident(&self.name))
8163        }
8164    }
8165}
8166
8167/// v7.39 (round 311) — render the left spine of an AND / OR chain
8168/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
8169/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
8170/// SAME operator flattens; anything else is an ordinary operand.
8171fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
8172    if let Expr::Binary {
8173        lhs,
8174        op: inner,
8175        rhs,
8176    } = e
8177        && *inner == op
8178    {
8179        write_bool_chain(f, lhs, op)?;
8180        return write!(f, " {op} {rhs}");
8181    }
8182    write!(f, "{e}")
8183}
8184
8185/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
8186/// form `pg_get_constraintdef(oid, true)` and friends return.
8187///
8188/// The default [`fmt::Display`] parenthesises every operator node, which
8189/// is what PG's non-pretty deparse does and what makes the text
8190/// round-trip. Pretty drops the pairs the grammar can put back, and the
8191/// rule is NOT plain precedence minimisation — measured against PG 18.4
8192/// across 37 shapes:
8193///
8194///   * the boolean layer follows precedence (NOT > AND > OR): an OR
8195///     under an AND keeps its parens, an AND under an OR does not, and a
8196///     comparison under any of them does not (`NOT a > 1`);
8197///   * an associative chain flattens completely, even where the source
8198///     nested it to the right (`a AND (b AND c)` prints as one chain);
8199///   * but an operand of a comparison or arithmetic operator keeps its
8200///     parens whenever it is itself an operator expression — so
8201///     `(a + b) > 10` and `(- a) + b`, even though precedence alone
8202///     would not require either. A cast, function call, column or
8203///     literal in that position does not (`a::text = t`,
8204///     `length(code) > 2`); a cast counts as compound exactly when the
8205///     thing it casts is (`((a + b)::text) = t`).
8206///
8207/// Anything outside that layer defers to `Display`, which is never
8208/// wrong — only more parenthesised than PG would print.
8209#[must_use]
8210pub fn pretty_expr(e: &Expr) -> String {
8211    let mut out = String::new();
8212    write_pretty(&mut out, e, PrettyParent::None, false, false);
8213    out
8214}
8215
8216/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
8217/// writes it.
8218///
8219/// MariaDB names the offending expression in its out-of-range message
8220/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
8221/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
8222/// MySQL client, for a cast the client had just written the other way.
8223#[must_use]
8224pub fn pretty_expr_mysql(e: &Expr) -> String {
8225    let mut out = String::new();
8226    write_pretty(&mut out, e, PrettyParent::None, false, true);
8227    out
8228}
8229
8230/// v7.39 (round 505) — how strongly an expression suggests its own column
8231/// name. A cast keeps its argument's name only when that name is STRONG;
8232/// otherwise the cast reports the type it casts to.
8233///
8234/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
8235/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
8236/// itself `text` — so `case` and a function name cannot be the same kind of
8237/// answer, even though a bare `CASE …` does report `case`.
8238#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8239enum NameStrength {
8240    /// Nothing to go on — PG reports `?column?`.
8241    None,
8242    /// A name, but one a cast overrides: `case`, or a type name.
8243    Weak,
8244    /// A name a cast keeps: a column, or the function that produced it.
8245    Strong,
8246}
8247
8248/// v7.39 (round 505) — the column name PG18 gives a projected expression
8249/// that carries no `AS` alias. `None` means `?column?`.
8250///
8251/// SPG used to print the parsed expression back out, which matched neither
8252/// oracle and made name-keyed row access miss on both wires:
8253///
8254/// | query        | PG18       | SPG (before) |
8255/// |--------------|------------|--------------|
8256/// | `upper(s)`   | `upper`    | `upper(s)`   |
8257/// | `a+b`        | `?column?` | `(a + b)`    |
8258/// | `'lit'`      | `?column?` | `'lit'`      |
8259/// | `CASE …`     | `case`     | `CASE WHEN (a = 1) THEN …` |
8260///
8261/// Every rule below is one of those measurements, taken with `\gdesc`
8262/// against PG18: a call is named for its function, a cast recurses into its
8263/// argument and falls back to the type, a scalar subquery takes the name of
8264/// the column it selects, and operators have no name at all.
8265#[must_use]
8266pub fn figure_column_name(expr: &Expr) -> Option<String> {
8267    let (name, _) = figure_name_inner(expr);
8268    name
8269}
8270
8271/// The name a function reports, which is not always the name SPG parsed it
8272/// under: `count(*)` is held as `count_star` so the star arity survives the
8273/// AST, and that internal spelling must not reach a client. PG18 reports
8274/// `count`.
8275fn canonical_function_name(name: &str) -> String {
8276    match name {
8277        "count_star" => "count".to_string(),
8278        other => other.to_ascii_lowercase(),
8279    }
8280}
8281
8282/// v7.38.7 — a cast target's `pg_type.typname`, for the name a cast
8283/// reports when its operand has none of its own. Only the spellings that
8284/// differ from what the user writes need an entry; everything else is
8285/// already its own typname.
8286fn cast_target_typname(target: &CastTarget) -> String {
8287    let written = target.to_string().to_ascii_lowercase();
8288    let base = written.strip_suffix("[]").unwrap_or(&written);
8289    let mapped = match base {
8290        "bigint" => "int8",
8291        "integer" | "int" => "int4",
8292        "smallint" => "int2",
8293        "boolean" => "bool",
8294        "double precision" => "float8",
8295        "real" => "float4",
8296        "character varying" => "varchar",
8297        "character" => "bpchar",
8298        "timestamp with time zone" => "timestamptz",
8299        "timestamp without time zone" => "timestamp",
8300        "time without time zone" => "time",
8301        "decimal" => "numeric",
8302        other => other,
8303    };
8304    if written.ends_with("[]") {
8305        alloc::format!("_{mapped}")
8306    } else {
8307        String::from(mapped)
8308    }
8309}
8310
8311fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
8312    let strong = |n: String| (Some(n), NameStrength::Strong);
8313    match expr {
8314        // A column keeps its own name, qualifier and all discarded:
8315        // `lbl.a` reports `a`.
8316        Expr::Column(c) => strong(c.name.clone()),
8317        // Calls are named for the function. This covers the shapes that
8318        // only LOOK like syntax — `EXTRACT(year FROM …)` reports
8319        // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
8320        // because PG resolves them to functions before naming them.
8321        Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
8322            strong(canonical_function_name(name))
8323        }
8324        Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
8325        Expr::Extract { .. } => strong("extract".to_string()),
8326        Expr::Exists { .. } => strong("exists".to_string()),
8327        Expr::Array(_) => strong("array".to_string()),
8328        // `(expr).field` is named for the field, as a column would be.
8329        Expr::FieldAccess { field, .. } => strong(field.clone()),
8330        // A cast prefers its argument's name and settles for the type:
8331        // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
8332        Expr::Cast {
8333            expr: inner,
8334            target,
8335        } => match figure_name_inner(inner) {
8336            (Some(n), NameStrength::Strong) => strong(n),
8337            // v7.38.7 — the fallback is the target type's INTERNAL name,
8338            // which is what PG reports: `SELECT 7::bigint` is `int8`, not
8339            // the `bigint` the user typed. Measured on PG18 alongside
8340            // `CAST(7 AS bigint)`, which answers `int8` too.
8341            _ => (Some(cast_target_typname(target)), NameStrength::Weak),
8342        },
8343        // A scalar subquery reports whatever its single output column
8344        // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
8345        Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
8346        // `CASE …` names itself, but weakly — a cast around it wins.
8347        Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
8348        // A literal that carries its own type names itself for that type:
8349        // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
8350        // reports nothing. Weak, like any other type name.
8351        Expr::Literal(Literal::Interval { .. }) => {
8352            (Some("interval".to_string()), NameStrength::Weak)
8353        }
8354        // A wrapper that adds no name of its own.
8355        Expr::Variadic(inner) => figure_name_inner(inner),
8356        Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
8357        // Everything else — operators, comparisons, IS NULL, LIKE, IN,
8358        // literals, placeholders — reports `?column?`.
8359        _ => (None, NameStrength::None),
8360    }
8361}
8362
8363/// The name a scalar subquery's single projected column reports.
8364fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
8365    match sel.items.as_slice() {
8366        [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
8367        [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
8368        _ => (None, NameStrength::None),
8369    }
8370}
8371
8372/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
8373fn pretty_prec(e: &Expr) -> u8 {
8374    match e {
8375        Expr::Binary { op, .. } => match op {
8376            // v7.39 (round 407) — this deparse ladder mirrors the parser's:
8377            // OR < XOR < AND < NOT < comparison < additive < multiplicative.
8378            // XOR (MySQL-only) sits between OR and AND, so AND and everything
8379            // above shifted +1 to open rung 2 for it.
8380            BinOp::Or => 1,
8381            BinOp::LogicalXor => 2,
8382            BinOp::And => 3,
8383            BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
8384            BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
8385            // Everything else in this enum is a comparison-shaped
8386            // operator; they share one level, as in the grammar.
8387            _ => 5,
8388        },
8389        Expr::Unary { op, .. } => match op {
8390            UnOp::Not => 4,
8391            UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
8392        },
8393        _ => u8::MAX,
8394    }
8395}
8396
8397/// Is this node an operator expression — the thing an arithmetic or
8398/// comparison parent keeps parentheses around? A cast inherits the
8399/// answer from what it casts.
8400fn pretty_is_compound(e: &Expr) -> bool {
8401    match e {
8402        Expr::Binary { .. } | Expr::Unary { .. } => true,
8403        Expr::Cast { expr, .. } => pretty_is_compound(expr),
8404        _ => false,
8405    }
8406}
8407
8408/// `parent` describes the enclosing operator: its binding power, and
8409/// whether it is a comparison (which keeps parens around any operator
8410/// operand) or a NOT (which keeps them at equal power too).
8411#[derive(Clone, Copy, PartialEq)]
8412enum PrettyParent {
8413    /// Nothing encloses this node.
8414    None,
8415    /// A comparison-shaped operator: an operator operand always keeps
8416    /// its parens, whatever precedence would allow.
8417    Comparison,
8418    /// Arithmetic / concatenation: precedence decides.
8419    Arith(u8),
8420    /// A boolean connective: precedence decides.
8421    Bool(u8),
8422    /// `NOT`: precedence decides, but equal power still needs parens so
8423    /// `NOT (NOT a > 1)` does not collapse.
8424    Not,
8425}
8426
8427fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8428    let prec = pretty_prec(e);
8429    let is_unary_sign = matches!(
8430        e,
8431        Expr::Unary {
8432            op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8433            ..
8434        }
8435    );
8436    let needs = match parent {
8437        PrettyParent::None => false,
8438        PrettyParent::Comparison => pretty_is_compound(e),
8439        // A sign always keeps its parens under an operator — PG writes
8440        // `(- a) + b` even though precedence would not require it.
8441        PrettyParent::Arith(p) => {
8442            is_unary_sign
8443                || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8444                    && (prec < p || (prec == p && is_rhs)))
8445        }
8446        PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8447        PrettyParent::Not => {
8448            matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8449        }
8450    };
8451    if needs {
8452        out.push('(');
8453    }
8454    match e {
8455        Expr::Binary { lhs, op, rhs } => {
8456            let child = match op {
8457                BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8458                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8459                    PrettyParent::Arith(prec)
8460                }
8461                _ => PrettyParent::Comparison,
8462            };
8463            write_pretty(out, lhs, child, false, mysql);
8464            out.push(' ');
8465            out.push_str(&alloc::format!("{op}"));
8466            out.push(' ');
8467            // AND / OR are associative, so an explicitly right-nested
8468            // chain still prints as one chain.
8469            let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8470            write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8471        }
8472        Expr::Unary { op, expr } => match op {
8473            UnOp::Not => {
8474                out.push_str("NOT ");
8475                write_pretty(out, expr, PrettyParent::Not, false, mysql);
8476            }
8477            UnOp::Neg => {
8478                out.push_str("- ");
8479                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8480            }
8481            UnOp::Plus => {
8482                out.push_str("+ ");
8483                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8484            }
8485            UnOp::BitNot => {
8486                out.push('~');
8487                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8488            }
8489        },
8490        Expr::Cast { expr, target } => {
8491            if mysql {
8492                // MySQL's own spelling, which is what its error messages
8493                // quote back.
8494                out.push_str("cast(");
8495                write_pretty(out, expr, PrettyParent::None, false, mysql);
8496                out.push_str(&alloc::format!(
8497                    " as {})",
8498                    target.to_string().to_lowercase()
8499                ));
8500            } else {
8501                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8502                out.push_str(&alloc::format!("::{target}"));
8503            }
8504        }
8505        Expr::IsNull { expr, negated } => {
8506            write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8507            out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8508        }
8509        other => out.push_str(&alloc::format!("{other}")),
8510    }
8511    if needs {
8512        out.push(')');
8513    }
8514}
8515
8516const fn pretty_prec_not() -> u8 {
8517    // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8518    // when the XOR insertion shifted the deparse ladder up by one).
8519    4
8520}
8521
8522impl fmt::Display for Expr {
8523    #[allow(clippy::too_many_lines)]
8524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8525        match self {
8526            Self::Literal(l) => write!(f, "{l}"),
8527            Self::Column(c) => write!(f, "{c}"),
8528            Self::Placeholder(n) => write!(f, "${n}"),
8529            // Round-trips as the spelling PG's docs lead with.
8530            Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8531            Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8532            // Round-trips with the name quoted, which is how PG spells a
8533            // collation everywhere: `"en_US.utf8"`, `"C"`.
8534            Self::Collate { expr, collation } => {
8535                write!(f, "{expr} COLLATE {}", quote_ident(collation))
8536            }
8537            // v7.39 (round 311) — an AND / OR chain that nests to the
8538            // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8539            // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8540            // its parentheses, because that is a different grouping as
8541            // written. Both halves measured against PG 18.4's deparse,
8542            // which flattens a same-operator left chain at parse time and
8543            // leaves `a AND (b AND c)` alone.
8544            Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8545                f.write_str("(")?;
8546                write_bool_chain(f, lhs, *op)?;
8547                write!(f, " {op} {rhs}")?;
8548                f.write_str(")")
8549            }
8550            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8551            Self::Unary { op, expr } => match op {
8552                UnOp::Not => write!(f, "(NOT {expr})"),
8553                // A space after the sign, as PG's deparse writes it.
8554                UnOp::Neg => write!(f, "(- {expr})"),
8555                UnOp::Plus => write!(f, "(+ {expr})"),
8556                UnOp::BitNot => write!(f, "(~{expr})"),
8557            },
8558            // The OPERAND carries the parentheses, not the cast:
8559            // `(a)::text`, `((a + b))::text`. PG words it this way, and
8560            // it is what keeps `a::text = t` from reading as a cast of
8561            // the comparison.
8562            Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8563            Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8564            Self::AggregateOrdered {
8565                call,
8566                order_by,
8567                distinct,
8568                filter,
8569            } => {
8570                let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8571                    for (i, o) in order_by.iter().enumerate() {
8572                        if i > 0 {
8573                            f.write_str(", ")?;
8574                        }
8575                        write!(f, "{}", o.expr)?;
8576                        if o.desc {
8577                            f.write_str(" DESC")?;
8578                        }
8579                        match o.nulls_first {
8580                            Some(true) => f.write_str(" NULLS FIRST")?,
8581                            Some(false) => f.write_str(" NULLS LAST")?,
8582                            None => {}
8583                        }
8584                    }
8585                    Ok(())
8586                };
8587                // Ordered-set aggregates (`percentile_cont(f) WITHIN
8588                // GROUP (ORDER BY x)`) render the in-parens args as the
8589                // direct argument and the sort spec under WITHIN GROUP —
8590                // not as an in-argument ORDER BY.
8591                let ordered_set = matches!(
8592                    call.as_ref(),
8593                    Expr::FunctionCall { name, .. }
8594                        if matches!(
8595                            name.to_ascii_lowercase().as_str(),
8596                            "percentile_cont" | "percentile_disc" | "mode"
8597                        )
8598                );
8599                if ordered_set {
8600                    write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8601                    fmt_order_by(f)?;
8602                    f.write_str(")")?;
8603                } else {
8604                    // `name([DISTINCT ]args [ORDER BY …])` — peel the
8605                    // inner call's parens to splice modifiers.
8606                    let inner = alloc::format!("{call}");
8607                    let body = inner.strip_suffix(')').unwrap_or(&inner);
8608                    let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8609                    write!(f, "{head}(")?;
8610                    if *distinct {
8611                        f.write_str("DISTINCT ")?;
8612                    }
8613                    write!(f, "{args_part}")?;
8614                    if !order_by.is_empty() {
8615                        f.write_str(" ORDER BY ")?;
8616                        fmt_order_by(f)?;
8617                    }
8618                    f.write_str(")")?;
8619                }
8620                if let Some(cond) = filter {
8621                    write!(f, " FILTER (WHERE {cond})")?;
8622                }
8623                Ok(())
8624            }
8625            Self::IsNull { expr, negated } => {
8626                if *negated {
8627                    write!(f, "({expr} IS NOT NULL)")
8628                } else {
8629                    write!(f, "({expr} IS NULL)")
8630                }
8631            }
8632            Self::BoolTest {
8633                expr,
8634                value,
8635                negated,
8636            } => {
8637                let word = match value {
8638                    Some(true) => "TRUE",
8639                    Some(false) => "FALSE",
8640                    None => "UNKNOWN",
8641                };
8642                if *negated {
8643                    write!(f, "({expr} IS NOT {word})")
8644                } else {
8645                    write!(f, "({expr} IS {word})")
8646                }
8647            }
8648            Self::FunctionCall { name, args } => {
8649                write!(f, "{name}(")?;
8650                for (i, a) in args.iter().enumerate() {
8651                    if i > 0 {
8652                        f.write_str(", ")?;
8653                    }
8654                    write!(f, "{a}")?;
8655                }
8656                f.write_str(")")
8657            }
8658            Self::Like {
8659                expr,
8660                pattern,
8661                negated,
8662                case_insensitive,
8663            } => {
8664                let op = match (negated, case_insensitive) {
8665                    (false, false) => "LIKE",
8666                    (true, false) => "NOT LIKE",
8667                    (false, true) => "ILIKE",
8668                    (true, true) => "NOT ILIKE",
8669                };
8670                write!(f, "({expr} {op} {pattern})")
8671            }
8672            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8673            Self::WindowFunction {
8674                name,
8675                args,
8676                partition_by,
8677                order_by,
8678                frame,
8679                null_treatment,
8680                filter,
8681            } => {
8682                write!(f, "{name}(")?;
8683                for (i, a) in args.iter().enumerate() {
8684                    if i > 0 {
8685                        f.write_str(", ")?;
8686                    }
8687                    write!(f, "{a}")?;
8688                }
8689                f.write_str(")")?;
8690                // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8691                // OVER; it round-trips so a window body's Display re-parses.
8692                if let Some(cond) = filter {
8693                    write!(f, " FILTER (WHERE {cond})")?;
8694                }
8695                // v7.30.1 (mailrs round-24 class audit) — IGNORE
8696                // NULLS sits between the arg list and OVER; dropping
8697                // it reverted replayed queries to RESPECT NULLS.
8698                if matches!(null_treatment, NullTreatment::Ignore) {
8699                    f.write_str(" IGNORE NULLS")?;
8700                }
8701                f.write_str(" OVER (")?;
8702                if !partition_by.is_empty() {
8703                    f.write_str("PARTITION BY ")?;
8704                    for (i, p) in partition_by.iter().enumerate() {
8705                        if i > 0 {
8706                            f.write_str(", ")?;
8707                        }
8708                        write!(f, "{p}")?;
8709                    }
8710                }
8711                if !order_by.is_empty() {
8712                    if !partition_by.is_empty() {
8713                        f.write_str(" ")?;
8714                    }
8715                    f.write_str("ORDER BY ")?;
8716                    for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8717                        if i > 0 {
8718                            f.write_str(", ")?;
8719                        }
8720                        write!(f, "{e}")?;
8721                        if *desc {
8722                            f.write_str(" DESC")?;
8723                        }
8724                        match nulls_first {
8725                            Some(true) => f.write_str(" NULLS FIRST")?,
8726                            Some(false) => f.write_str(" NULLS LAST")?,
8727                            None => {}
8728                        }
8729                    }
8730                }
8731                if let Some(fr) = frame {
8732                    if !partition_by.is_empty() || !order_by.is_empty() {
8733                        f.write_str(" ")?;
8734                    }
8735                    let k = match fr.kind {
8736                        FrameKind::Rows => "ROWS",
8737                        FrameKind::Range => "RANGE",
8738                        FrameKind::Groups => "GROUPS",
8739                    };
8740                    if let Some(end) = &fr.end {
8741                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8742                    } else {
8743                        write!(f, "{k} {}", fr.start)?;
8744                    }
8745                }
8746                f.write_str(")")
8747            }
8748            Self::ScalarSubquery(s) => write!(f, "({s})"),
8749            Self::Exists { subquery, negated } => {
8750                if *negated {
8751                    write!(f, "NOT EXISTS ({subquery})")
8752                } else {
8753                    write!(f, "EXISTS ({subquery})")
8754                }
8755            }
8756            Self::InSubquery {
8757                expr,
8758                subquery,
8759                negated,
8760            } => {
8761                if *negated {
8762                    write!(f, "({expr} NOT IN ({subquery}))")
8763                } else {
8764                    write!(f, "({expr} IN ({subquery}))")
8765                }
8766            }
8767            Self::RowInSubquery {
8768                row,
8769                subquery,
8770                negated,
8771            } => {
8772                write!(f, "(")?;
8773                for (i, e) in row.iter().enumerate() {
8774                    if i > 0 {
8775                        write!(f, ", ")?;
8776                    }
8777                    write!(f, "{e}")?;
8778                }
8779                let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8780                write!(f, "{kw}{subquery})")
8781            }
8782            Self::RowCmpSubquery { row, op, subquery } => {
8783                write!(f, "(")?;
8784                for (i, e) in row.iter().enumerate() {
8785                    if i > 0 {
8786                        write!(f, ", ")?;
8787                    }
8788                    write!(f, "{e}")?;
8789                }
8790                write!(f, ") {op} ({subquery})")
8791            }
8792            Self::InList {
8793                expr,
8794                list,
8795                negated,
8796            } => {
8797                let kw = if *negated { " NOT IN (" } else { " IN (" };
8798                write!(f, "({expr}{kw}")?;
8799                for (i, e) in list.iter().enumerate() {
8800                    if i > 0 {
8801                        f.write_str(", ")?;
8802                    }
8803                    write!(f, "{e}")?;
8804                }
8805                f.write_str("))")
8806            }
8807            Self::Array(items) => {
8808                f.write_str("ARRAY[")?;
8809                for (i, e) in items.iter().enumerate() {
8810                    if i > 0 {
8811                        f.write_str(", ")?;
8812                    }
8813                    write!(f, "{e}")?;
8814                }
8815                f.write_str("]")
8816            }
8817            Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
8818            Self::ArraySlice { target, lo, hi } => {
8819                write!(f, "({target}[")?;
8820                if let Some(l) = lo {
8821                    write!(f, "{l}")?;
8822                }
8823                write!(f, ":")?;
8824                if let Some(h) = hi {
8825                    write!(f, "{h}")?;
8826                }
8827                write!(f, "])")
8828            }
8829            Self::AnyAll {
8830                expr,
8831                op,
8832                array,
8833                is_any,
8834            } => {
8835                let kw = if *is_any { "ANY" } else { "ALL" };
8836                write!(f, "({expr} {op} {kw}({array}))")
8837            }
8838            Self::Case {
8839                operand,
8840                branches,
8841                else_branch,
8842            } => {
8843                f.write_str("CASE")?;
8844                if let Some(op) = operand {
8845                    write!(f, " {op}")?;
8846                }
8847                for (w, t) in branches {
8848                    write!(f, " WHEN {w} THEN {t}")?;
8849                }
8850                if let Some(e) = else_branch {
8851                    write!(f, " ELSE {e}")?;
8852                }
8853                f.write_str(" END")
8854            }
8855        }
8856    }
8857}
8858
8859/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
8860/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
8861pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
8862    use alloc::string::ToString;
8863    if scale == 0 {
8864        return alloc::format!("{unscaled}");
8865    }
8866    let neg = unscaled < 0;
8867    let digits = alloc::format!("{}", unscaled.unsigned_abs());
8868    let scale = scale as usize;
8869    let (int_part, frac_part) = if digits.len() > scale {
8870        (
8871            digits[..digits.len() - scale].to_string(),
8872            digits[digits.len() - scale..].to_string(),
8873        )
8874    } else {
8875        ("0".to_string(), alloc::format!("{digits:0>scale$}"))
8876    };
8877    alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
8878}
8879
8880/// A single-quoted SQL string, with an embedded quote doubled.
8881fn write_quoted(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
8882    f.write_str("'")?;
8883    for c in s.chars() {
8884        if c == '\'' {
8885            f.write_str("''")?;
8886        } else {
8887            write!(f, "{c}")?;
8888        }
8889    }
8890    f.write_str("'")
8891}
8892
8893impl fmt::Display for Literal {
8894    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8895        match self {
8896            Self::Integer(n) => write!(f, "{n}"),
8897            Self::Float(x) => {
8898                let s = format!("{x}");
8899                // Default Display for an integral f64 (e.g. 1.0) emits "1",
8900                // which would round-trip back to Integer. Force a dot.
8901                if s.contains('.') || s.contains('e') || s.contains('E') {
8902                    f.write_str(&s)
8903                } else {
8904                    write!(f, "{s}.0")
8905                }
8906            }
8907            Self::Numeric { unscaled, scale } => {
8908                // Render the exact decimal `unscaled / 10^scale`, preserving
8909                // scale (trailing zeros) — round-trips to the same literal.
8910                f.write_str(&render_exact_decimal(*unscaled, *scale))
8911            }
8912            Self::NumericBig(s) => f.write_str(s),
8913            // Printed exactly as the text form was, so a reader cannot
8914            // tell whether the constant was decoded or not.
8915            Self::Timestamp { text, .. } | Self::Date { text, .. } => write_quoted(f, text),
8916            Self::String(s) => write_quoted(f, s),
8917            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
8918            Self::Null => f.write_str("NULL"),
8919            // PG external array form. Display round-trip re-enters
8920            // through the column-typed text coerce, same as pgwire.
8921            Self::TextArray(items) => {
8922                f.write_str("'{")?;
8923                for (i, it) in items.iter().enumerate() {
8924                    if i > 0 {
8925                        f.write_str(",")?;
8926                    }
8927                    match it {
8928                        None => f.write_str("NULL")?,
8929                        Some(s) => {
8930                            f.write_str("\"")?;
8931                            for c in s.chars() {
8932                                match c {
8933                                    // array-element escapes
8934                                    '"' | '\\' => write!(f, "\\{c}")?,
8935                                    // the OUTER wrapper is a SQL string
8936                                    // literal — embedded quotes must
8937                                    // double, or the rendered form
8938                                    // (WAL replay parses it back) is
8939                                    // invalid SQL
8940                                    '\'' => f.write_str("''")?,
8941                                    _ => write!(f, "{c}")?,
8942                                }
8943                            }
8944                            f.write_str("\"")?;
8945                        }
8946                    }
8947                }
8948                f.write_str("}'")
8949            }
8950            Self::IntArray(items) => {
8951                f.write_str("'{")?;
8952                for (i, it) in items.iter().enumerate() {
8953                    if i > 0 {
8954                        f.write_str(",")?;
8955                    }
8956                    match it {
8957                        None => f.write_str("NULL")?,
8958                        Some(n) => write!(f, "{n}")?,
8959                    }
8960                }
8961                f.write_str("}'")
8962            }
8963            Self::BigIntArray(items) => {
8964                f.write_str("'{")?;
8965                for (i, it) in items.iter().enumerate() {
8966                    if i > 0 {
8967                        f.write_str(",")?;
8968                    }
8969                    match it {
8970                        None => f.write_str("NULL")?,
8971                        Some(n) => write!(f, "{n}")?,
8972                    }
8973                }
8974                f.write_str("}'")
8975            }
8976            Self::Vector(v) => {
8977                f.write_str("[")?;
8978                for (i, x) in v.iter().enumerate() {
8979                    if i > 0 {
8980                        f.write_str(", ")?;
8981                    }
8982                    let s = format!("{x}");
8983                    // Mirror Float Display: force a dot so re-parse stays
8984                    // numerically literal.
8985                    if s.contains('.') || s.contains('e') || s.contains('E') {
8986                        f.write_str(&s)?;
8987                    } else {
8988                        write!(f, "{s}.0")?;
8989                    }
8990                }
8991                f.write_str("]")
8992            }
8993            Self::Interval { text, .. } => {
8994                f.write_str("INTERVAL '")?;
8995                for c in text.chars() {
8996                    if c == '\'' {
8997                        f.write_str("''")?;
8998                    } else {
8999                        write!(f, "{c}")?;
9000                    }
9001                }
9002                f.write_str("'")
9003            }
9004        }
9005    }
9006}
9007
9008impl fmt::Display for BinOp {
9009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9010        f.write_str(match self {
9011            Self::Or => "OR",
9012            Self::And => "AND",
9013            Self::Eq => "=",
9014            Self::NotEq => "<>",
9015            Self::IsDistinctFrom => "IS DISTINCT FROM",
9016            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
9017            Self::IntDiv => "DIV",
9018            Self::Lt => "<",
9019            Self::LtEq => "<=",
9020            Self::Gt => ">",
9021            Self::GtEq => ">=",
9022            Self::Add => "+",
9023            Self::Sub => "-",
9024            Self::Mul => "*",
9025            Self::Div => "/",
9026            Self::Mod => "%",
9027            Self::L2Distance => "<->",
9028            Self::GeomParallel => "?||",
9029            Self::OverLeft => "&<",
9030            Self::OverRight => "&>",
9031            Self::GeomPerp => "?-|",
9032            Self::GeomSameAs => "~=",
9033            Self::ClosestPoint => "##",
9034            Self::GeomHoriz => "?-",
9035            Self::InnerProduct => "<#>",
9036            Self::CosineDistance => "<=>",
9037            Self::Concat => "||",
9038            Self::BitOr => "|",
9039            Self::BitAnd => "&",
9040            Self::BitXor => "#",
9041            Self::LogicalXor => "xor",
9042            Self::JsonGet => "->",
9043            Self::JsonGetText => "->>",
9044            Self::JsonGetPath => "#>",
9045            Self::JsonGetPathText => "#>>",
9046            Self::JsonContains => "@>",
9047            Self::JsonPathExists => "@?",
9048            Self::JsonContainedBy => "<@",
9049            Self::JsonKeyExists => "?",
9050            Self::JsonKeysAny => "?|",
9051            Self::JsonKeysAll => "?&",
9052            Self::JsonDeletePath => "#-",
9053            Self::TsMatch => "@@",
9054            Self::InetContainedBy => "<<",
9055            Self::InetContainedByEq => "<<=",
9056            Self::InetContains => ">>",
9057            Self::InetContainsEq => ">>=",
9058            Self::InetOverlap => "&&",
9059            Self::Intersects => "?#",
9060            Self::IsBelow => "<^",
9061            Self::IsAbove => ">^",
9062            Self::PatternLt => "~<~",
9063            Self::PatternLtEq => "~<=~",
9064            Self::PatternGt => "~>~",
9065            Self::PatternGtEq => "~>=~",
9066        })
9067    }
9068}
9069
9070/// Quote `s` as a PG double-quoted identifier when required (keyword,
9071/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
9072/// Otherwise return it as-is. Returns an owned `String` to keep the call site
9073/// uniform.
9074pub(crate) fn quote_ident(s: &str) -> String {
9075    let needs_quote = match s.chars().next() {
9076        None => true,
9077        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
9078        _ => {
9079            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
9080                || s.chars().any(|c| c.is_ascii_uppercase())
9081                || is_keyword(s)
9082        }
9083    };
9084    if !needs_quote {
9085        return s.to_string();
9086    }
9087    let mut out = String::with_capacity(s.len() + 2);
9088    out.push('"');
9089    for c in s.chars() {
9090        if c == '"' {
9091            out.push_str("\"\"");
9092        } else {
9093            out.push(c);
9094        }
9095    }
9096    out.push('"');
9097    out
9098}
9099
9100fn is_keyword(s: &str) -> bool {
9101    matches!(
9102        &*s.to_ascii_lowercase(),
9103        "select"
9104            | "from"
9105            | "where"
9106            | "as"
9107            | "null"
9108            | "true"
9109            | "false"
9110            | "and"
9111            | "or"
9112            | "not"
9113            | "create"
9114            | "table"
9115            | "insert"
9116            | "into"
9117            | "values"
9118            | "index"
9119            | "on"
9120            | "begin"
9121            | "commit"
9122            | "rollback"
9123            | "is"
9124            | "between"
9125            | "in"
9126            | "like"
9127            | "group"
9128            | "distinct"
9129            | "union"
9130            | "all"
9131            | "join"
9132            | "inner"
9133            | "left"
9134            | "cross"
9135            | "outer"
9136            | "default"
9137            | "savepoint"
9138            | "release"
9139            | "to"
9140            | "having"
9141            | "show"
9142            | "extract"
9143            | "offset"
9144            | "asc"
9145            | "desc"
9146            | "interval"
9147    )
9148}
9149
9150#[cfg(test)]
9151mod tests {
9152    use super::*;
9153    use alloc::vec;
9154
9155    #[test]
9156    fn integer_literal_renders_without_dot() {
9157        assert_eq!(Literal::Integer(42).to_string(), "42");
9158    }
9159
9160    #[test]
9161    fn integral_float_keeps_dot() {
9162        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
9163        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
9164        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
9165    }
9166
9167    #[test]
9168    fn string_literal_doubles_quote() {
9169        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
9170    }
9171
9172    #[test]
9173    fn bool_and_null_render_uppercase() {
9174        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
9175        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
9176        assert_eq!(Literal::Null.to_string(), "NULL");
9177    }
9178
9179    #[test]
9180    fn binary_op_always_parenthesised() {
9181        let e = Expr::Binary {
9182            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
9183            op: BinOp::Add,
9184            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
9185        };
9186        assert_eq!(e.to_string(), "(1 + 2)");
9187    }
9188
9189    #[test]
9190    fn select_star_from_table() {
9191        let s = SelectStatement {
9192            locking: None,
9193            items: vec![SelectItem::Wildcard],
9194            from: Some(FromClause {
9195                primary: TableRef {
9196                    name: "users".into(),
9197                    alias: None,
9198                    only: false,
9199                    as_of_segment: None,
9200                    unnest_expr: None,
9201                    unnest_column_aliases: Vec::new(),
9202                    with_ordinality: false,
9203                    generate_series_args: None,
9204                    lateral_subquery: None,
9205                    jsonb_each_text_arg: None,
9206                    table_fn_call: None,
9207                    rows_from: None,
9208                    json_table: None,
9209                    scalar_fn_item: false,
9210                },
9211                joins: vec![],
9212            }),
9213            where_: None,
9214            group_by: None,
9215            group_by_all: false,
9216            having: None,
9217            unions: vec![],
9218            order_by: Vec::new(),
9219            limit: None,
9220            offset: None,
9221            limit_with_ties: false,
9222            window_check_exprs: Vec::new(),
9223            distinct: false,
9224            distinct_on: Vec::new(),
9225            ctes: vec![],
9226        };
9227        assert_eq!(s.to_string(), "SELECT * FROM users");
9228    }
9229
9230    #[test]
9231    fn quote_ident_for_uppercase_and_keyword() {
9232        assert_eq!(quote_ident("foo"), "foo");
9233        assert_eq!(quote_ident("Foo"), "\"Foo\"");
9234        assert_eq!(quote_ident("select"), "\"select\"");
9235        assert_eq!(quote_ident(""), "\"\"");
9236        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
9237    }
9238}