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.9 — MySQL's top-level `RENAME TABLE a TO b [, c TO d]`.
681    /// PostgreSQL has only `ALTER TABLE … RENAME TO`, so this spelling
682    /// had nowhere to go; it is what a MySQL migration writes.
683    RenameTables(Vec<(String, String)>),
684    /// v7.39 (round 535) — `REINDEX { INDEX | TABLE | SCHEMA | DATABASE
685    /// | SYSTEM } [CONCURRENTLY] <name>` and `CLUSTER [VERBOSE]
686    /// [<table> [USING <index>]]`.
687    ///
688    /// SPG has neither index bloat nor a clustering order to rebuild, so
689    /// the work is a no-op — but PG VALIDATES the target, and both were
690    /// swallowed at parse time, so `REINDEX TABLE typo` reported success.
691    /// The name is carried now so the engine can say what PG says.
692    Maintain {
693        kind: MaintainKind,
694        /// `REINDEX … CONCURRENTLY`. Carried for the same reason as
695        /// [`CreateIndexStatement::concurrently`]: PG bars the
696        /// CONCURRENTLY form inside a transaction block and allows the
697        /// plain one.
698        concurrently: bool,
699        /// `None` for the whole-database forms, which name nothing.
700        target: Option<String>,
701    },
702    /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] [ONLY] <name>
703    /// [, ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE |
704    /// RESTRICT]`. Clears every row from each named table. SPG's
705    /// SEQUENCE identity is per-table; RESTART IDENTITY reinitializes
706    /// the associated sequence to its starting value. CASCADE
707    /// currently walks direct FK-referring tables and truncates
708    /// them too (PG's semantics). The ONLY modifier (skip partitions)
709    /// and RESTRICT (default) are accepted with no effect since
710    /// SPG's declarative partitions are always truncated together.
711    Truncate {
712        tables: Vec<String>,
713        restart_identity: bool,
714        cascade: bool,
715        /// v7.39 (round 647) — `TRUNCATE ONLY t`. Absorbed as a no-op
716        /// since v7.14 on the reasoning that SPG's children are separate
717        /// relations a truncate does not descend into. Same reasoning
718        /// round 621 applied to `FROM ONLY`, and it stopped being true
719        /// for the same reason: measured, `TRUNCATE <inheritance parent>`
720        /// leaves the children's rows where PG empties them, and
721        /// `TRUNCATE ONLY <partitioned parent>` is silently accepted
722        /// where PG refuses it outright.
723        only: bool,
724    },
725    /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
726    /// BTree-cold indices and merges small cold-tier segments
727    /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
728    /// 4 MiB) into a single larger segment per (table, index).
729    /// `WHERE` predicate filtering on which tables to compact is
730    /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
731    /// v6.7.3 only supports the bare form.
732    CompactColdSegments,
733    /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
734    /// parameter on the engine; v7.12.1 honours
735    /// `default_text_search_config` (consumed by `to_tsvector` /
736    /// `plainto_tsquery` family when called without an explicit
737    /// config arg). All other names are accepted as a no-op so PG
738    /// dumps with `SET client_encoding`, `SET search_path` etc.
739    /// load cleanly.
740    SetParameter {
741        name: String,
742        value: SetValue,
743        /// v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to the
744        /// current transaction; the engine saves the prior value and
745        /// restores it at COMMIT / ROLLBACK. Plain `SET` (and `SET
746        /// SESSION`) leave this false and persist for the session.
747        local: bool,
748    },
749    /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
750    /// multi-assignment (mysqldump preamble uses
751    /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
752    /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
753    /// source order. Pairs whose LHS is a MySQL session/user
754    /// variable (`@VAR` / `@@VAR`) are recorded with the raw
755    /// name so the engine can ignore them; pairs whose LHS is
756    /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
757    /// go through the regular `set_session_param` path.
758    SetParameterList(Vec<(String, SetValue)>),
759    /// v7.39 (round 430) — MySQL's USER-defined variables:
760    /// `SET @x = 5, @s := CONCAT('a','b')`. Distinct from
761    /// [`Self::SetParameter`] (a `@@`-style engine/session setting) in
762    /// every way that matters: the value is an arbitrary EXPRESSION, the
763    /// name lives in its own per-session namespace, and reading an unset
764    /// one answers NULL rather than raising. `:=` and `=` are the same
765    /// assignment here.
766    ///
767    /// Before this the parser stripped every `@`, so `@x` and `@@x` were
768    /// the same node: `SET @x = 5` silently landed in the session-parameter
769    /// store where nothing could read it back, and `SELECT @x` failed with
770    /// "Unknown system variable".
771    /// v7.39 (round 554) — `SET @a = …, SETTING = …`.
772    ///
773    /// `settings` is the trailing half a mysqldump preamble writes:
774    /// `SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'`
775    /// saves a value and changes it in one statement. The parser used
776    /// to refuse the mixture outright, so no mysqldump could be
777    /// restored past its preamble.
778    SetUserVars(Vec<(String, Expr)>, Vec<(String, Expr)>),
779    /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
780    /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
781    /// silently accepted). PG-standard surface for picking an
782    /// isolation level. Engine tracks the value on
783    /// `Engine::current_isolation_level()`; actual MVCC / SSI
784    /// semantics implementation lands separately. PG itself maps
785    /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
786    /// effectively every level reads as READ COMMITTED in v7.37.8.
787    SetTransaction {
788        modes: TransactionModes,
789    },
790    /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
791    /// with the parameter's current value as TEXT. Today the only
792    /// recognised param is `transaction_isolation`; further
793    /// surfaces (`search_path`, `application_name`, …) land as the
794    /// session-parameter inventory grows.
795    ShowParameter(String),
796    /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
797    /// to its default. No-op for parameters SPG does not track.
798    ResetParameter(Option<String>),
799    /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
800    /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
801    /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
802    /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
803    /// languages parse but error at exec time with a clear
804    /// unsupported message.
805    CreateFunction(CreateFunctionStatement),
806    /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
807    /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
808    /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
809    /// triggers and column-list / WHEN clauses are out of scope
810    /// for v7.12.4.
811    CreateTrigger(CreateTriggerStatement),
812    /// v7.39 (round 139) — `CREATE RULE name AS ON event TO table [WHERE cond]
813    /// DO [ALSO|INSTEAD] { NOTHING | command }` query-rewrite rule.
814    CreateRule(CreateRuleStatement),
815    /// v7.39 (round 139) — `DROP RULE [IF EXISTS] name ON table`.
816    DropRule {
817        name: String,
818        table: String,
819        if_exists: bool,
820    },
821    /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
822    /// no-op when missing if `IF EXISTS` is set.
823    DropTrigger {
824        name: String,
825        table: String,
826        if_exists: bool,
827    },
828    /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
829    /// DROP TRIGGER but global (no table scope).
830    DropFunction {
831        name: String,
832        /// v7.39 (read01 round 62) — the argument TYPES, when the statement gave
833        /// them: `DROP FUNCTION f(int)` drops that overload only. `None` = no
834        /// argument list, which PG accepts only when the name is unambiguous.
835        args: Option<Vec<String>>,
836        if_exists: bool,
837    },
838    /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
839    /// [AS data_type]
840    /// [INCREMENT [BY] n]
841    /// [MINVALUE n | NO MINVALUE]
842    /// [MAXVALUE n | NO MAXVALUE]
843    /// [START [WITH] n]
844    /// [CACHE n]
845    /// [[NO] CYCLE]
846    /// [OWNED BY {table.col | NONE}]`.
847    /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
848    /// emits + nextval/currval/setval downstream all work.
849    CreateSequence(CreateSequenceStatement),
850    /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
851    /// the same option grammar as CREATE SEQUENCE, plus
852    /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
853    AlterSequence(AlterSequenceStatement),
854    /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
855    /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
856    /// silently (no FK on sequences).
857    DropSequence {
858        names: Vec<String>,
859        if_exists: bool,
860    },
861    /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
862    /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
863    /// silent-no-op VIEW story from the v7.17 customer-readiness
864    /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
865    /// so any downstream `SELECT FROM v` errored with table-not-
866    /// found. The view body is stored verbatim; SELECT FROM <v>
867    /// rewrites at exec-time by prepending the view body as a
868    /// synthetic CTE.
869    CreateView(CreateViewStatement),
870    /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
871    /// [CASCADE | RESTRICT]`. Removes the matching view from the
872    /// catalog; CASCADE/RESTRICT parsed silently.
873    DropView {
874        names: Vec<String>,
875        if_exists: bool,
876    },
877    /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
878    /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
879    /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
880    /// model: the materialised result lives as a regular table
881    /// with the matching name + a parallel
882    /// `materialized_views` registry mapping name → body source
883    /// (used by REFRESH).
884    CreateMaterializedView(CreateMaterializedViewStatement),
885    /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
886    /// [NO] DATA]`. Re-runs the stored body and replaces the
887    /// cached rows. `WITH NO DATA` truncates without re-running.
888    RefreshMaterializedView {
889        name: String,
890        with_data: bool,
891    },
892    /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
893    /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
894    /// backing table and the source registry entry.
895    DropMaterializedView {
896        names: Vec<String>,
897        if_exists: bool,
898    },
899    /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
900    /// …)`. Closes the silent-no-op CREATE TYPE story so PG
901    /// dumps that declare enum types load with real constraints
902    /// instead of becoming free-form TEXT. Future kinds
903    /// (composite / range / domain) extend the inner `kind`
904    /// enum.
905    CreateType(CreateTypeStatement),
906    /// v7.37 D.55 — `ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
907    /// [{BEFORE | AFTER} 'existing']`. Extends an enum's label list so
908    /// enum evolution stops being a silent no-op. `position` is
909    /// `Some((is_before, anchor))`.
910    /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
911    /// Used to be swallowed by the ALTER TYPE no-op tail, so the rename was
912    /// accepted and silently ignored.
913    /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
914    /// Used to be swallowed as dump noise, so a comment was accepted and lost
915    /// (and obj_description / col_description always returned NULL).
916    /// `kind` is lowercase ("table" / "column" / "index" / …); for a column
917    /// `name` is the dotted `table.column`. `comment: None` = `IS NULL` = remove.
918    CommentOn {
919        kind: String,
920        name: String,
921        comment: Option<String>,
922    },
923    AlterTypeRenameValue {
924        type_name: String,
925        old: String,
926        new: String,
927    },
928    AlterTypeAddValue {
929        type_name: String,
930        label: String,
931        if_not_exists: bool,
932        position: Option<(bool, String)>,
933    },
934    /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
935    /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
936    /// from the catalog.
937    DropType {
938        names: Vec<String>,
939        if_exists: bool,
940    },
941    /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
942    /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
943    /// A DOMAIN is a named CHECK-constrained alias over a built-
944    /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
945    /// every column declared with the domain. Closes the
946    /// silent-no-op CREATE DOMAIN story so PG dumps that ship
947    /// validated identifier types (email, positive_int, …) keep
948    /// their guarantees.
949    CreateDomain(CreateDomainStatement),
950    /// v7.39 (round 260) — `ALTER DOMAIN name <action>`. Every form was
951    /// previously swallowed by the catch-all DDL arm: the statement
952    /// reported success and did nothing, so a migration that dropped a
953    /// constraint kept rejecting the data it had just been told to
954    /// accept.
955    AlterDomain {
956        name: String,
957        action: AlterDomainAction,
958    },
959    /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
960    /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
961    /// domain from the catalog.
962    DropDomain {
963        names: Vec<String>,
964        if_exists: bool,
965    },
966    /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
967    /// name [AUTHORIZATION user]`. SPG is single-database;
968    /// schemas are tracked as a namespace registry so pg_dump
969    /// multi-schema declarations land cleanly and `SELECT *
970    /// FROM information_schema.schemata` returns real entries.
971    /// Schema-qualified `schema.table` references still strip
972    /// the prefix at lookup time per PG (schemas are not
973    /// isolation boundaries in v7.17 — see project-next-docket
974    /// for the v7.18+ isolation tracking).
975    CreateSchema {
976        name: String,
977        if_not_exists: bool,
978    },
979    /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
980    /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
981    /// from the registry; built-in `public` / `pg_catalog` /
982    /// `information_schema` cannot be dropped.
983    DropSchema {
984        names: Vec<String>,
985        if_exists: bool,
986    },
987}
988
989/// v7.39 (round 260) — the `ALTER DOMAIN` actions SPG implements.
990#[derive(Debug, Clone, PartialEq)]
991pub enum AlterDomainAction {
992    AddConstraint { name: Option<String>, check: Expr },
993    DropConstraint { name: String, if_exists: bool },
994    SetDefault(Expr),
995    DropDefault,
996    SetNotNull,
997    DropNotNull,
998    RenameTo(String),
999}
1000
1001/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
1002#[derive(Debug, Clone, PartialEq)]
1003pub struct CreateDomainStatement {
1004    pub name: String,
1005    /// Base type for the domain (one of the built-in
1006    /// `ColumnTypeName` variants).
1007    pub base_type: ColumnTypeName,
1008    /// v7.39 (round 259) — `CREATE DOMAIN child AS parent …` where
1009    /// `parent` is itself a DOMAIN. The parser already captured the
1010    /// unknown type name; it just was not carried here, so the parent's
1011    /// CHECK constraints were invisible and a value violating them was
1012    /// silently accepted. `base_type` still holds the ultimate scalar
1013    /// type, which is what the storage tier stores.
1014    pub base_domain: Option<String>,
1015    /// Optional `DEFAULT <expr>`. Resolved at engine-side
1016    /// CREATE TABLE time when a column is bound to this domain.
1017    pub default: Option<Expr>,
1018    /// `NOT NULL` from the domain definition. Engine ORs this
1019    /// with the column-level nullability so the strictest of the
1020    /// two wins (i.e. the column is non-nullable if either side
1021    /// says so).
1022    pub not_null: bool,
1023    /// Zero-or-more `CHECK (expr)` predicates. Each one is
1024    /// enforced as part of the column's CHECK list at INSERT /
1025    /// UPDATE time, with `VALUE` substituted for the column's
1026    /// current cell value.
1027    pub checks: Vec<Expr>,
1028}
1029
1030/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
1031#[derive(Debug, Clone, PartialEq, Eq)]
1032pub struct CreateTypeStatement {
1033    pub name: String,
1034    pub kind: TypeKind,
1035}
1036
1037/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
1038/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
1039/// and later (COMPOSITE, RANGE) can land without an AST shape
1040/// migration.
1041///
1042/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
1043/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
1044/// stores the field list in the catalog so PG dumps that emit
1045/// `CREATE TYPE … AS (…)` don't error out; using a composite type
1046/// as a column type lands in Phase 2 (Value::Composite encoding +
1047/// ROW() literal + field-access syntax).
1048#[derive(Debug, Clone, PartialEq, Eq)]
1049pub enum TypeKind {
1050    /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
1051    /// labels are ordered).
1052    Enum { labels: Vec<String> },
1053    /// `AS (field_name field_type, …)`. Order matters; PG
1054    /// composite literals are positional.
1055    Composite {
1056        fields: Vec<(String, ColumnTypeName)>,
1057        /// v7.39 (round 264) — parallel to `fields`: the raw type NAME
1058        /// when a field's type is not a builtin (i.e. another composite).
1059        /// The parser already captures it; without carrying it here a
1060        /// nested composite field resolved to the Text placeholder and
1061        /// the inner record never became a record.
1062        field_user_types: Vec<Option<String>>,
1063    },
1064}
1065
1066/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
1067/// a string literal, an identifier (often a config name), an
1068/// integer/float, or the bare `DEFAULT` keyword.
1069#[derive(Debug, Clone, PartialEq)]
1070pub enum SetValue {
1071    String(String),
1072    Ident(String),
1073    Number(String),
1074    Default,
1075}
1076
1077/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
1078/// at parse time and tracks the selected value on the engine. The
1079/// actual semantic differentiation (REPEATABLE READ snapshot,
1080/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
1081/// today every level reads as effective READ COMMITTED (which is
1082/// also how PG treats READ UNCOMMITTED — it silently upgrades to
1083/// READ COMMITTED). Default = `ReadCommitted`.
1084#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1085pub enum IsolationLevel {
1086    ReadUncommitted,
1087    #[default]
1088    ReadCommitted,
1089    RepeatableRead,
1090    Serializable,
1091}
1092
1093impl IsolationLevel {
1094    /// Canonical PG-style display name, as `SHOW transaction_isolation`
1095    /// would return it. v7.39 (round 770, F31 tranche 6 #154) — PG
1096    /// KEEPS the "read uncommitted" label (measured: `BEGIN ISOLATION
1097    /// LEVEL READ UNCOMMITTED; SHOW transaction_isolation` answers
1098    /// `read uncommitted`) and only BEHAVES as read committed; the old
1099    /// fold renamed the label too.
1100    /// v7.39 — the MySQL display name, which is NOT the PG one: MySQL
1101    /// hyphenates and upper-cases. Measured on MySQL 9.7.2 by setting
1102    /// each level and reading `@@transaction_isolation` back:
1103    /// `READ-UNCOMMITTED` / `READ-COMMITTED` / `REPEATABLE-READ` /
1104    /// `SERIALIZABLE` (the last has no hyphen because it is one word).
1105    ///
1106    /// This exists so the two MySQL surfaces cannot drift: both
1107    /// `SHOW VARIABLES` and `@@transaction_isolation` used to carry
1108    /// their own hard-coded literal, and the literals disagreed —
1109    /// one said `REPEATABLE-READ` while the engine ran read committed.
1110    /// v7.39 — parse what `default_transaction_isolation` holds. PG
1111    /// accepts the SQL spellings and stores them lower-cased with a
1112    /// space; anything else is not a level this understands and the
1113    /// caller keeps its own default rather than guessing.
1114    #[must_use]
1115    pub fn from_pg_name(name: &str) -> Option<Self> {
1116        match name.trim().to_ascii_lowercase().as_str() {
1117            "read uncommitted" => Some(Self::ReadUncommitted),
1118            "read committed" => Some(Self::ReadCommitted),
1119            "repeatable read" => Some(Self::RepeatableRead),
1120            "serializable" => Some(Self::Serializable),
1121            _ => None,
1122        }
1123    }
1124
1125    #[must_use]
1126    pub fn as_mysql_str(self) -> &'static str {
1127        match self {
1128            Self::ReadUncommitted => "READ-UNCOMMITTED",
1129            Self::ReadCommitted => "READ-COMMITTED",
1130            Self::RepeatableRead => "REPEATABLE-READ",
1131            Self::Serializable => "SERIALIZABLE",
1132        }
1133    }
1134
1135    pub fn as_pg_str(self) -> &'static str {
1136        match self {
1137            Self::ReadUncommitted => "read uncommitted",
1138            Self::ReadCommitted => "read committed",
1139            Self::RepeatableRead => "repeatable read",
1140            Self::Serializable => "serializable",
1141        }
1142    }
1143}
1144
1145impl core::fmt::Display for IsolationLevel {
1146    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1147        f.write_str(self.as_pg_str())
1148    }
1149}
1150
1151/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
1152/// single fixed-shape DDL; the WITH-clause options PG supports
1153/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
1154/// scope for v6.1.4 — `enabled` defaults to true and there are
1155/// no other knobs to set in v6.1.x.
1156#[derive(Debug, Clone, PartialEq, Eq)]
1157pub struct CreateSubscriptionStatement {
1158    pub name: String,
1159    /// Connection string in PG keyword=value form (e.g.
1160    /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
1161    /// `host` and `port` fields; the rest is reserved for
1162    /// future v6.1.x options.
1163    pub conn_str: String,
1164    /// One or more publications on the remote side. Order is
1165    /// preserved verbatim from the DDL; the worker requests them
1166    /// in this order. v6.1.4 records the list; v6.1.5
1167    /// publisher-side filtering enforces it.
1168    pub publications: Vec<String>,
1169}
1170
1171/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
1172#[derive(Debug, Clone, PartialEq, Eq)]
1173pub struct CreateSequenceStatement {
1174    pub name: String,
1175    pub if_not_exists: bool,
1176    pub temporary: bool,
1177    /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
1178    pub data_type: Option<SequenceDataType>,
1179    pub options: SequenceOptions,
1180}
1181
1182/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
1183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1184pub enum SequenceDataType {
1185    SmallInt,
1186    Int,
1187    BigInt,
1188}
1189
1190/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
1191/// All fields are optional. `min_value`/`max_value` carry
1192/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
1193#[derive(Debug, Clone, Default, PartialEq, Eq)]
1194pub struct SequenceOptions {
1195    pub increment: Option<i64>,
1196    pub min_value: Option<SeqBound>,
1197    pub max_value: Option<SeqBound>,
1198    pub start: Option<i64>,
1199    /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
1200    /// RESTART, `Some(Some(n))` = RESTART WITH n.
1201    pub restart: Option<Option<i64>>,
1202    pub cache: Option<i64>,
1203    pub cycle: Option<bool>,
1204    pub owned_by: Option<SequenceOwnedBy>,
1205}
1206
1207/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
1208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1209pub enum SeqBound {
1210    Value(i64),
1211    NoBound,
1212}
1213
1214/// v7.17.0 — `OWNED BY {table.col | NONE}`.
1215#[derive(Debug, Clone, PartialEq, Eq)]
1216pub enum SequenceOwnedBy {
1217    None,
1218    Column { table: String, column: String },
1219}
1220
1221/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
1222#[derive(Debug, Clone, PartialEq)]
1223pub struct CreateMaterializedViewStatement {
1224    pub name: String,
1225    pub if_not_exists: bool,
1226    /// Optional `(col, col, …)` rename list. Applies to the
1227    /// backing table at CREATE / REFRESH time.
1228    pub columns: Vec<String>,
1229    /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
1230    /// the cached rows.
1231    pub body: SelectStatement,
1232    /// `WITH DATA` (default) = materialise the rows at CREATE
1233    /// time. `WITH NO DATA` = create an empty backing table;
1234    /// callers must REFRESH before SELECT returns rows.
1235    pub with_data: bool,
1236    /// v7.38 (read01 P6.49) — when true this node came from
1237    /// `CREATE TABLE … AS <select>` (CTAS) / `SELECT … INTO`, so the
1238    /// executor creates a plain table and does NOT register it in the
1239    /// materialized-view registry (no REFRESH semantics).
1240    pub as_plain_table: bool,
1241    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE … AS <select>`. Only
1242    /// meaningful together with `as_plain_table`; the executor puts the
1243    /// resulting table in the creating session's namespace.
1244    pub temporary: bool,
1245}
1246
1247/// v7.39 (read01 round 132) — `WITH [LOCAL | CASCADED] CHECK OPTION` on an
1248/// auto-updatable view. `Cascaded` is PG's default when the bare
1249/// `WITH CHECK OPTION` is written.
1250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1251pub enum ViewCheckOption {
1252    Local,
1253    Cascaded,
1254}
1255
1256/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
1257#[derive(Debug, Clone, PartialEq)]
1258pub struct CreateViewStatement {
1259    pub name: String,
1260    pub or_replace: bool,
1261    pub if_not_exists: bool,
1262    pub temporary: bool,
1263    /// Optional `(col, col, …)` rename list. When non-empty,
1264    /// these override the body's projected column names per-
1265    /// position at SELECT-from-view time.
1266    pub columns: Vec<String>,
1267    /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
1268    /// time to materialise the view as a synthetic CTE.
1269    pub body: SelectStatement,
1270    /// v7.39 (round 132) — `WITH CHECK OPTION`. When set, a write through this
1271    /// view whose resulting row fails the view's WHERE is rejected (SQLSTATE
1272    /// 44000). `None` = no check option.
1273    pub check_option: Option<ViewCheckOption>,
1274}
1275
1276/// v7.17.0 — `ALTER SEQUENCE` AST node.
1277#[derive(Debug, Clone, PartialEq, Eq)]
1278pub struct AlterSequenceStatement {
1279    pub name: String,
1280    pub if_exists: bool,
1281    pub options: SequenceOptions,
1282    /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`. Set
1283    /// instead of `options`; the two forms are mutually exclusive in PG.
1284    pub rename_to: Option<String>,
1285}
1286
1287/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
1288/// the [`PublicationScope`] shape. v6.1.2 only accepted
1289/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
1290/// variants by flipping the parser gate (no AST migration).
1291#[derive(Debug, Clone, PartialEq, Eq)]
1292pub struct CreatePublicationStatement {
1293    pub name: String,
1294    pub scope: PublicationScope,
1295}
1296
1297/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
1298/// flips the parser gate for the `ForTables` / `AllTablesExcept`
1299/// variants — the on-disk shape, snapshot serialisation, and the
1300/// AST round-trip Display path were already in place in v6.1.2
1301/// so this is a parser-only widening.
1302#[derive(Debug, Clone, PartialEq, Eq)]
1303pub enum PublicationScope {
1304    AllTables,
1305    ForTables(Vec<String>),
1306    AllTablesExcept(Vec<String>),
1307    /// v7.39 (round 754, F31-B5) — `FOR TABLES IN SCHEMA <name>`
1308    /// (PG 15+). AST-only: the executor folds `public` to
1309    /// [`PublicationScope::AllTables`] (SPG's single-schema world)
1310    /// and refuses any other schema with PG's sentence, so the
1311    /// catalog / serializer / replication filter never see it.
1312    TablesInSchema(String),
1313}
1314
1315#[derive(Debug, Clone, PartialEq, Eq)]
1316pub struct AlterIndexStatement {
1317    pub name: String,
1318    pub target: AlterIndexTarget,
1319}
1320
1321#[derive(Debug, Clone, PartialEq, Eq)]
1322pub enum AlterIndexTarget {
1323    /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
1324    /// rebuilds the existing graph in place without touching the
1325    /// column encoding; `Some(enc)` re-encodes every cell first.
1326    Rebuild { encoding: Option<VecEncoding> },
1327    /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
1328    /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
1329    /// uses it to make the migration idempotent (re-running on a
1330    /// DB where the rename already happened is a no-op rather
1331    /// than an error).
1332    Rename { new: String, if_exists: bool },
1333    /// v7.39 (round 710) — `SET ( option = value, … )` / `RESET ( … )`.
1334    /// Was a SYNTAX ERROR; PG resolves the INDEX first (`relation "x"
1335    /// does not exist`), so the index is validated and the storage
1336    /// parameters no-op (SPG engine-manages them, as ALTER TABLE's
1337    /// SET/RESET arms already record).
1338    StorageParams,
1339}
1340
1341/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
1342/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
1343/// can add more SET subjects without changing the dispatch shape.
1344#[derive(Debug, Clone, PartialEq)]
1345pub struct AlterTableStatement {
1346    pub name: String,
1347    /// v7.13.2 — mailrs round-6 S1. One or more subactions
1348    /// separated by commas in the source SQL. PG-semantic apply
1349    /// is sequential; engine bails on first error (no
1350    /// transactional rollback of completed subactions in v7.13).
1351    /// Single-subaction shape stays a 1-element vec.
1352    pub targets: Vec<AlterTableTarget>,
1353}
1354/// v7.39.9 — the `FIRST` / `AFTER c` trailer, written back the way it
1355/// was read.
1356fn write_column_position(
1357    f: &mut core::fmt::Formatter<'_>,
1358    pos: Option<&ColumnPosition>,
1359) -> core::fmt::Result {
1360    match pos {
1361        Some(ColumnPosition::First) => f.write_str(" FIRST"),
1362        Some(ColumnPosition::After(c)) => write!(f, " AFTER {}", quote_ident(c)),
1363        None => Ok(()),
1364    }
1365}
1366
1367/// v7.39.9 — where MySQL's `ADD` / `MODIFY` / `CHANGE` puts a column.
1368///
1369/// The row encoding is positional and `SELECT *` reads it in order, so
1370/// this is an answer, not a formatting preference.
1371#[derive(Debug, Clone, PartialEq, Eq)]
1372pub enum ColumnPosition {
1373    First,
1374    After(String),
1375}
1376
1377#[derive(Debug, Clone, PartialEq)]
1378#[allow(clippy::large_enum_variant)]
1379pub enum AlterTableTarget {
1380    /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
1381    ///
1382    /// Both were accepted-and-ignored since v7.37.18, on the reasoning
1383    /// that SPG has no PG-style inheritance. Round 645 gave it one, and
1384    /// the reasoning went stale: `NO INHERIT` reported success while the
1385    /// child stayed attached, which is the worst kind of answer — the
1386    /// statement says it worked and the catalog disagrees.
1387    Inherit { parent: String, detach: bool },
1388    /// Per-table hot-tier byte budget override. The freezer
1389    /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
1390    SetHotTierBytes(u64),
1391    /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
1392    /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
1393    /// Engine validates existing rows against the new constraint
1394    /// before installing it.
1395    AddForeignKey(ForeignKeyConstraint),
1396    /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
1397    /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
1398    /// no-op when no FK with that name exists; otherwise raises.
1399    DropForeignKey { name: String, if_exists: bool },
1400    /// v7.39 (round 431) — MySQL's `ALTER TABLE t DROP {INDEX|KEY} name`,
1401    /// the counterpart of `ADD INDEX`. Lowers to the same catalog action
1402    /// as the standalone `DROP INDEX` statement.
1403    DropIndex { name: String, if_exists: bool },
1404    /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
1405    /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
1406    /// (20 migrate-*.sql hits). Engine appends the column to the
1407    /// schema and back-fills every existing row with the DEFAULT
1408    /// (or NULL when no DEFAULT and the column is nullable).
1409    AddColumn {
1410        column: ColumnDef,
1411        if_not_exists: bool,
1412        /// v7.39.9 — MySQL's `FIRST` / `AFTER <col>`, which say where
1413        /// the column goes. `None` is the PostgreSQL form and appends.
1414        position: Option<ColumnPosition>,
1415    },
1416    /// v7.39.9 — MySQL's `MODIFY COLUMN c <definition>` and
1417    /// `CHANGE COLUMN old new <definition>`.
1418    ///
1419    /// Both REPLACE the column's definition rather than amending it,
1420    /// which is the part that cannot be expressed by the PostgreSQL
1421    /// spellings SPG already had. Measured on MySQL 9.7.2: a column
1422    /// declared `INT NOT NULL DEFAULT 5`, after `MODIFY COLUMN b
1423    /// BIGINT`, is `bigint` NULLABLE with NO default — restating them
1424    /// keeps them, omitting them drops them. `CHANGE` is the same and
1425    /// also renames.
1426    ModifyColumn {
1427        /// The column as it is named now.
1428        column: String,
1429        /// `CHANGE`'s new name; `None` for `MODIFY`, which keeps it.
1430        rename_to: Option<String>,
1431        /// The whole new definition, exactly as written.
1432        definition: ColumnDef,
1433        position: Option<ColumnPosition>,
1434    },
1435    /// v7.39.9 — MySQL's `RENAME {INDEX|KEY} old TO new`.
1436    RenameIndex { old: String, new: String },
1437    /// v7.39.9 — MySQL's `ALTER TABLE t AUTO_INCREMENT = n`, which sets
1438    /// the value the NEXT insert takes. Measured on 9.7.2: after
1439    /// `= 100`, the next row's id is 100.
1440    SetTableAutoIncrement(i64),
1441    /// v7.39.9 — MySQL's `ENGINE = <name>`. SPG has one storage engine
1442    /// and substitutes for every name MySQL knows, exactly as
1443    /// `CREATE TABLE` already does; a name MySQL does not know is
1444    /// refused with its 1286, because a typo in a migration must not
1445    /// quietly become SPG's storage.
1446    SetEngine(String),
1447    /// v7.39.9 — MySQL's `CONVERT TO CHARACTER SET <cs> [COLLATE <c>]`.
1448    /// SPG stores UTF-8 throughout, so a charset it can represent is
1449    /// accepted and one it cannot is refused with MySQL's 1115.
1450    ConvertToCharacterSet {
1451        charset: String,
1452        collate: Option<String>,
1453    },
1454    /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
1455    /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
1456    /// existing row's column value by evaluating the optional
1457    /// USING expression (default `col::<ty>`) and re-coercing
1458    /// against the new column type.
1459    AlterColumnType {
1460        column: String,
1461        new_type: ColumnTypeName,
1462        using: Option<Expr>,
1463        /// v7.39 (round 713) — `COLLATE <name>` between the type and
1464        /// USING. PG re-collates the column, and an ABSENT clause RESETS
1465        /// the collation to the type default (measured round 713) — so
1466        /// `None` is not "leave it alone". The type parser consumed the
1467        /// clause all along and this surface dropped it on the floor:
1468        /// the statement succeeded and the ordering did not change, the
1469        /// silent-divergence shape. Folded variant + the name as written.
1470        collation: Option<(Collation, String)>,
1471    },
1472    /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
1473    /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
1474    /// every row's value at that position is removed; any index
1475    /// on the column is dropped. `if_exists` makes the drop a
1476    /// no-op when the column is missing. `cascade` removes
1477    /// dependents (FKs referencing the column, partial indexes
1478    /// whose predicate names the column); without it, the engine
1479    /// rejects when dependents exist.
1480    DropColumn {
1481        column: String,
1482        if_exists: bool,
1483        cascade: bool,
1484    },
1485    /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
1486    /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
1487    /// CONSTRAINT name CHECK (expr)` — table-level constraints
1488    /// installed post-CREATE-TABLE. pg_dump emits PKs as a
1489    /// separate ALTER TABLE statement, so this surface lets the
1490    /// dump load straight through.
1491    AddTableConstraint(TableConstraint),
1492    /// v7.39 (round 652) — `OWNER TO <role>`. SPG is single-owner, so
1493    /// there is nothing to record; what PG does that SPG did not is
1494    /// REFUSE a role that does not exist. The name has to reach the
1495    /// engine for that, because only the engine knows the roles.
1496    OwnerTo { role: String },
1497    /// v7.39 (round 652) — `CLUSTER ON <index>` and `SET WITHOUT
1498    /// CLUSTER` (the latter as `None`). SPG has no clustered storage, so
1499    /// the hint is still a no-op; naming an index that does not exist is
1500    /// not.
1501    ClusterOn { index: Option<String> },
1502    /// v7.39 (round 652) — `VALIDATE CONSTRAINT <name>`: scan the rows
1503    /// already in the table against a constraint added `NOT VALID` and,
1504    /// if they all pass, mark it validated. It used to be swallowed as a
1505    /// no-op on the theory that SPG validated at ADD time; SPG did not.
1506    ValidateConstraint { name: String },
1507    /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
1508    /// Renames the column in the schema and propagates the rename
1509    /// to every stored source string that references it as a
1510    /// (potentially-qualified) column identifier: CHECK predicates,
1511    /// partial-index predicates, runtime DEFAULT expressions, and
1512    /// triggers' `UPDATE OF` column lists. Function bodies and
1513    /// trigger bodies are NOT auto-rewritten — they're loose
1514    /// source text and may contain references SPG can't statically
1515    /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
1516    /// the column even if dependents exist; users renaming a
1517    /// column referenced by a function body update the function
1518    /// body separately.
1519    RenameColumn { old: String, new: String },
1520    /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
1521    /// Reachable now that the schema stores user-supplied constraint names.
1522    RenameConstraint { old: String, new: String },
1523    /// v7.22 (round-13 T2) — mark a column auto-incrementing.
1524    /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
1525    /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
1526    /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
1527    /// (identity); both lower to this. SPG's auto-increment is
1528    /// max+1-scan based, so the dump's `setval(…)` calls stay
1529    /// no-ops without losing the sequence position.
1530    SetColumnAutoIncrement {
1531        column: String,
1532        /// The implicit sequence pg_dump names for an identity
1533        /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
1534        /// nextval target for a serial default. The engine creates
1535        /// it if absent so the dump's later `setval(s, …)` lands.
1536        seq_name: Option<String>,
1537    },
1538    /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
1539    /// table itself (mailrs round-10 A.5 carve-out — mailrs's
1540    /// migrate-042 uses it). The engine moves the table entry
1541    /// in the catalog under the new name; child catalog state
1542    /// (FKs pointing at this table, triggers watching this
1543    /// table) tracks the rename through the storage layer.
1544    RenameTable { new: String },
1545    /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
1546    /// { ALL | <name> }`. Toggles whether row-level triggers
1547    /// fire on subsequent INSERT/UPDATE/DELETE on the table.
1548    /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
1549    /// ENABLE epilogue around every table's data block so the
1550    /// rows already-computed in prod don't get re-rewritten
1551    /// (and so trigger-driven side effects like
1552    /// audit/queueing don't re-fire during a bulk reload).
1553    /// `which == TriggerSelector::All` toggles every trigger
1554    /// on the table; `Named(name)` toggles one trigger. The
1555    /// engine persists the disabled state on `TriggerDef.enabled`
1556    /// (catalog FILE_VERSION 25+) and the row-write paths skip
1557    /// the trigger when `!enabled`.
1558    SetTriggerEnabled {
1559        which: TriggerSelector,
1560        enabled: bool,
1561    },
1562    /// v7.39 (RLS) — `ALTER TABLE t { ENABLE | DISABLE | FORCE | NO FORCE }
1563    /// ROW LEVEL SECURITY`. `enabled` = Some for ENABLE/DISABLE (sets
1564    /// `relrowsecurity`); `force` = Some for FORCE/NO FORCE (sets
1565    /// `relforcerowsecurity`). Exactly one is `Some` per statement.
1566    SetRowSecurity {
1567        enabled: Option<bool>,
1568        force: Option<bool>,
1569    },
1570    /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child
1571    /// <bounds>`. Promotes an existing table `child` to a partition
1572    /// of `parent` using PG-style `FOR VALUES …` / `DEFAULT` bounds.
1573    /// Engine validates that `child`'s columns are layout-compatible
1574    /// with `parent` and that every row in `child` satisfies the
1575    /// bound before installing the role.
1576    AttachPartition {
1577        child: String,
1578        bounds: PartitionOfBoundsAst,
1579    },
1580    /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
1581    /// child [CONCURRENTLY] [FINALIZE]`. Demotes a partition back
1582    /// to a standalone table (clears `partition_role`) and removes
1583    /// it from the parent's child set. v7.37.16.5: `CONCURRENTLY`
1584    /// is parser-accepted; engine performs the same atomic detach
1585    /// (single-engine, no replication lag — the PG semantics that
1586    /// require the two-phase split don't apply).
1587    DetachPartition {
1588        child: String,
1589        concurrently: bool,
1590        finalize: bool,
1591    },
1592    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col SET DEFAULT
1593    /// <expr>`. Engine re-parses + freezes the literal at this point,
1594    /// matching CREATE TABLE-side default semantics. Volatile shapes
1595    /// (`now()` / `nextval`) take the runtime-default path.
1596    AlterColumnSetDefault { column: String, default_expr: Expr },
1597    /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col DROP DEFAULT`.
1598    AlterColumnDropDefault { column: String },
1599    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col SET NOT NULL`.
1600    /// Engine validates that no existing row has NULL in that column
1601    /// before flipping the flag (PG semantics — partial NOT NULL
1602    /// would surface inconsistently).
1603    AlterColumnSetNotNull { column: String },
1604    /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col DROP NOT NULL`.
1605    AlterColumnDropNotNull { column: String },
1606    /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN col RESTART
1607    /// [WITH n]` on an identity column (`None` = bare RESTART, from the
1608    /// column's start value = 1). Engine records a next-value floor over
1609    /// SPG's max+1 identity allocation.
1610    AlterColumnRestart { column: String, with: Option<i64> },
1611    /// v7.38 (read01 U10) — `ALTER TABLE … ALTER COLUMN col DROP
1612    /// EXPRESSION` turns a stored generated column into a plain column
1613    /// (its generation expression is removed; existing values are kept).
1614    AlterColumnDropExpression { column: String, if_exists: bool },
1615    /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
1616    /// de-generate an identity column into a plain column.
1617    AlterColumnDropIdentity { column: String, if_exists: bool },
1618    /// v7.38 (read01 U12) — `ALTER TABLE … ALTER COLUMN col SET
1619    /// EXPRESSION AS (expr)` (PG 17) changes a stored generated column's
1620    /// expression and recomputes every existing row.
1621    AlterColumnSetExpression { column: String, expr: Expr },
1622    /// v7.39 (round 710) — `OF <type>` / the type half of the typed-table
1623    /// binding. The BINDING stays a no-op (recorded); the TYPE must exist
1624    /// (PG: `type "x" does not exist`).
1625    OfType { type_name: String },
1626    /// v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`. The
1627    /// identity setting no-ops (SPG has no logical replication consumer);
1628    /// the INDEX must exist on this table (PG: `index "i" for table "t"
1629    /// does not exist`).
1630    ReplicaIdentityUsingIndex { index: String },
1631}
1632
1633/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
1634/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
1635/// modifiers; v7.16.1 ships the two shapes pg_dump actually
1636/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
1637/// shouldn't surface from a dump.
1638#[derive(Debug, Clone, PartialEq, Eq)]
1639pub enum TriggerSelector {
1640    /// Every trigger on the table.
1641    All,
1642    /// A specific trigger by name.
1643    Named(String),
1644}
1645
1646/// Each bool mirrors one independent PG `EXPLAIN (…)` option (ANALYZE,
1647/// SUGGEST, COSTS OFF, BUFFERS, TIMING OFF, …); they compose freely, so a
1648/// bitflags word or a nested options struct would only relocate the lint
1649/// while making the option each caller sets harder to read.
1650#[allow(clippy::struct_excessive_bools)]
1651#[derive(Debug, Clone, PartialEq)]
1652pub struct ExplainStatement {
1653    pub analyze: bool,
1654    /// v7.39 (round 225) — widened from SelectStatement so EXPLAIN
1655    /// INSERT/UPDATE/DELETE parses (PG explains DML); the engine renders
1656    /// `Insert on / Update on / Delete on` trees for them.
1657    pub inner: Box<Statement>,
1658    /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
1659    /// advisor pass: after the regular plan tree, the engine
1660    /// emits one suggestion line per column referenced in the
1661    /// query's WHERE / JOIN that has no covering index on the
1662    /// owning table.
1663    pub suggest: bool,
1664    /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
1665    /// `elapsed=…us` annotations from the Total line (and any
1666    /// future cost-bearing lines). PG-standard option used by
1667    /// regression suites and diff-friendly EXPLAIN output. When
1668    /// `true`, takes precedence over the per-session
1669    /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
1670    pub costs_off: bool,
1671    /// v7.37.22 (22.7) — `EXPLAIN (BUFFERS) <SELECT>`. PG-standard
1672    /// option that surfaces hot/cold/shared block counters. SPG's
1673    /// hot-tier scan path counts examined rows; the BUFFERS option
1674    /// makes that an explicit per-operator annotation.
1675    pub buffers: bool,
1676    /// v7.37.22 (22.7) — `EXPLAIN (TIMING [ON|OFF]) <SELECT>`. PG
1677    /// uses this to disable per-operator timing while still
1678    /// emitting actual-row counts (cheaper than ANALYZE). Default
1679    /// when EXPLAIN ANALYZE is set: TIMING ON. `false` strips the
1680    /// timing portion of the Total line. Decoupled from `costs_off`:
1681    /// PG's COSTS OFF strips estimated cost; TIMING OFF strips
1682    /// measured wall-clock.
1683    pub timing_off: bool,
1684    /// v7.37.22 (22.7) — `EXPLAIN (SETTINGS) <SELECT>`. PG appends
1685    /// modified GUC values to the plan output. SPG emits the
1686    /// session params that diverge from default after the main
1687    /// plan body.
1688    pub settings: bool,
1689    /// v7.37.22 (22.7) — `EXPLAIN (WAL) <SELECT>`. PG counts WAL
1690    /// bytes / records / FPI emitted by the query. SPG's
1691    /// write-side queries (INSERT/UPDATE/DELETE wrapped in EXPLAIN
1692    /// ANALYZE) report against the engine WAL counter delta.
1693    pub wal: bool,
1694    /// v7.39 (round 227) — `EXPLAIN (SUMMARY OFF)` suppresses the trailing
1695    /// `Planning Time:` / `Execution Time:` lines. PG defaults SUMMARY on
1696    /// for ANALYZE and off otherwise; SPG emits them for ANALYZE unless
1697    /// this is set.
1698    pub summary_off: bool,
1699    /// v7.37.23 (23.5) — `EXPLAIN (FORMAT text|json|xml|yaml)`.
1700    /// PG's standard format selector. Default is text. JSON / XML
1701    /// / YAML emit a single-row TEXT result whose body wraps the
1702    /// existing line-per-operator text in the chosen container —
1703    /// PG-compatible just enough for dashboards that parse those
1704    /// container shapes (pgAdmin's JSON path picker, etc.).
1705    pub format: ExplainFormat,
1706}
1707
1708#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1709pub enum ExplainFormat {
1710    #[default]
1711    Text,
1712    Json,
1713    Xml,
1714    Yaml,
1715}
1716
1717/// v7.39 (RLS) — the command a `CREATE POLICY` scopes to. `All` is the default.
1718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1719pub enum PolicyCmd {
1720    All,
1721    Select,
1722    Insert,
1723    Update,
1724    Delete,
1725}
1726
1727/// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
1728/// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`.
1729#[derive(Debug, Clone, PartialEq)]
1730pub struct CreatePolicyStatement {
1731    pub name: String,
1732    pub table: String,
1733    /// `true` = PERMISSIVE (default), `false` = RESTRICTIVE.
1734    pub permissive: bool,
1735    pub cmd: PolicyCmd,
1736    /// Empty = PUBLIC.
1737    pub roles: Vec<String>,
1738    pub using: Option<Expr>,
1739    pub with_check: Option<Expr>,
1740}
1741
1742/// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
1743/// [USING (expr)] [WITH CHECK (expr)] }`. Cannot change PERMISSIVE/RESTRICTIVE
1744/// or the command (matches PG).
1745#[derive(Debug, Clone, PartialEq)]
1746pub struct AlterPolicyStatement {
1747    pub name: String,
1748    pub table: String,
1749    pub rename_to: Option<String>,
1750    pub roles: Option<Vec<String>>,
1751    pub using: Option<Expr>,
1752    pub with_check: Option<Expr>,
1753}
1754
1755/// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
1756#[derive(Debug, Clone, PartialEq, Eq)]
1757pub struct DropPolicyStatement {
1758    pub name: String,
1759    pub table: String,
1760    pub if_exists: bool,
1761}
1762
1763#[derive(Debug, Clone, PartialEq, Eq)]
1764pub struct CreateUserStatement {
1765    pub name: String,
1766    /// Empty when the statement carried no PASSWORD — legal for a bare
1767    /// `CREATE ROLE`, which cannot log in anyway.
1768    pub password: String,
1769    /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
1770    /// the parser; the engine validates against `Role::parse` so a
1771    /// typo lands as a runtime error with a clear message rather than
1772    /// a parse failure.
1773    pub role: String,
1774    /// v7.39 (read01 round 58) — the PG role attributes. `None` = the
1775    /// statement did not say, so the default for its spelling applies:
1776    /// `CREATE USER` is `CREATE ROLE … LOGIN`, `CREATE ROLE` is NOLOGIN;
1777    /// both default to INHERIT and NOSUPERUSER.
1778    pub login: Option<bool>,
1779    pub inherit: Option<bool>,
1780    pub superuser: Option<bool>,
1781    /// `true` when spelled `CREATE USER` (LOGIN by default).
1782    pub is_user: bool,
1783}
1784
1785/// v7.39 (round 322, V46) — PG's function volatility class. Declarative:
1786/// it tells the planner how far a call may be moved or folded. SPG records
1787/// it faithfully (`pg_proc.provolatile`, `pg_get_functiondef`) and does not
1788/// yet exploit it for constant folding.
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1790pub enum FunctionVolatility {
1791    Immutable,
1792    Stable,
1793    #[default]
1794    Volatile,
1795}
1796
1797impl FunctionVolatility {
1798    /// PG's one-character `pg_proc.provolatile` code.
1799    #[must_use]
1800    pub const fn as_pg_char(self) -> &'static str {
1801        match self {
1802            Self::Immutable => "i",
1803            Self::Stable => "s",
1804            Self::Volatile => "v",
1805        }
1806    }
1807
1808    #[must_use]
1809    pub const fn as_sql(self) -> &'static str {
1810        match self {
1811            Self::Immutable => "IMMUTABLE",
1812            Self::Stable => "STABLE",
1813            Self::Volatile => "VOLATILE",
1814        }
1815    }
1816}
1817
1818/// v7.39 (round 322, V46) — PG's parallel-safety class.
1819#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1820pub enum FunctionParallel {
1821    #[default]
1822    Unsafe,
1823    Restricted,
1824    Safe,
1825}
1826
1827impl FunctionParallel {
1828    /// PG's one-character `pg_proc.proparallel` code.
1829    #[must_use]
1830    pub const fn as_pg_char(self) -> &'static str {
1831        match self {
1832            Self::Unsafe => "u",
1833            Self::Restricted => "r",
1834            Self::Safe => "s",
1835        }
1836    }
1837
1838    #[must_use]
1839    pub const fn as_sql(self) -> &'static str {
1840        match self {
1841            Self::Unsafe => "PARALLEL UNSAFE",
1842            Self::Restricted => "PARALLEL RESTRICTED",
1843            Self::Safe => "PARALLEL SAFE",
1844        }
1845    }
1846}
1847
1848/// v7.39 (round 322, V46) — the attribute clauses `CREATE FUNCTION` accepts
1849/// on either side of its body. Defaults are PG's: VOLATILE, called on null
1850/// input, SECURITY INVOKER, not leakproof, PARALLEL UNSAFE, and the
1851/// language's default cost / rows.
1852#[derive(Debug, Clone, Copy, PartialEq, Default)]
1853pub struct FunctionAttrs {
1854    pub volatility: FunctionVolatility,
1855    /// `STRICT` / `RETURNS NULL ON NULL INPUT`: a call with any NULL
1856    /// argument returns NULL without running the body.
1857    pub strict: bool,
1858    pub security_definer: bool,
1859    pub leakproof: bool,
1860    pub parallel: FunctionParallel,
1861    /// `COST n` — `None` leaves PG's per-language default.
1862    pub cost: Option<f64>,
1863    /// `ROWS n` — set-returning functions only; `None` = default.
1864    pub rows: Option<f64>,
1865}
1866
1867impl FunctionAttrs {
1868    /// The attribute words `pg_get_functiondef` puts on their own line,
1869    /// in PG's order (measured on 18.4: volatility, PARALLEL, STRICT,
1870    /// SECURITY DEFINER, LEAKPROOF, COST, ROWS). Empty when everything is
1871    /// at its default — PG then emits no such line at all.
1872    #[must_use]
1873    pub fn render_words(&self) -> alloc::vec::Vec<alloc::string::String> {
1874        let mut out = alloc::vec::Vec::new();
1875        if self.volatility != FunctionVolatility::Volatile {
1876            out.push(alloc::string::String::from(self.volatility.as_sql()));
1877        }
1878        if self.parallel != FunctionParallel::Unsafe {
1879            out.push(alloc::string::String::from(self.parallel.as_sql()));
1880        }
1881        if self.strict {
1882            out.push(alloc::string::String::from("STRICT"));
1883        }
1884        if self.security_definer {
1885            out.push(alloc::string::String::from("SECURITY DEFINER"));
1886        }
1887        if self.leakproof {
1888            out.push(alloc::string::String::from("LEAKPROOF"));
1889        }
1890        if let Some(c) = self.cost {
1891            out.push(alloc::format!("COST {}", render_attr_number(c)));
1892        }
1893        if let Some(r) = self.rows {
1894            out.push(alloc::format!("ROWS {}", render_attr_number(r)));
1895        }
1896        out
1897    }
1898}
1899
1900/// PG prints a whole-numbered cost / rows without a decimal point.
1901fn render_attr_number(v: f64) -> alloc::string::String {
1902    // no_std: `f64::fract` lives in std, so compare against the truncation.
1903    let whole = v as i64;
1904    if v.abs() < 1e15 && (whole as f64) == v {
1905        alloc::format!("{whole}")
1906    } else {
1907        alloc::format!("{v}")
1908    }
1909}
1910
1911/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
1912/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
1913/// (the row-level trigger body the CREATE TRIGGER below references).
1914/// Non-trigger user-defined functions parse but error at execution
1915/// time with a clear unsupported message; that surface lands in
1916/// v7.12.5+.
1917#[derive(Debug, Clone, PartialEq)]
1918pub struct CreateFunctionStatement {
1919    pub name: String,
1920    /// `OR REPLACE` was present; an existing function with the
1921    /// same name is overwritten instead of erroring.
1922    pub or_replace: bool,
1923    /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
1924    /// list `()` (sufficient for trigger functions). Other shapes
1925    /// parse and store the args but the executor refuses to call
1926    /// them.
1927    pub args: Vec<FunctionArg>,
1928    /// `RETURNS <type>` — `trigger` is the supported shape for
1929    /// v7.12.4; arbitrary return types parse to
1930    /// [`FunctionReturn::Other`].
1931    pub returns: FunctionReturn,
1932    /// `LANGUAGE <lang>` clause. PG accepts the clause on either
1933    /// side of `AS $$...$$`; the parser canonicalises to one slot.
1934    /// `plpgsql` and `sql` are the two interesting values.
1935    pub language: String,
1936    /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
1937    /// a structured AST; non-trigger / non-plpgsql bodies stay as
1938    /// the raw source text so the v7.12.5+ executor can pick them
1939    /// up without a parser rev.
1940    pub body: FunctionBody,
1941    /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
1942    /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. PG accepts them
1943    /// on either side of the body; before this they were a parse error, so
1944    /// PG's own `pg_dump` output would not restore.
1945    pub attrs: FunctionAttrs,
1946}
1947
1948/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
1949#[derive(Debug, Clone, PartialEq)]
1950pub struct FunctionArg {
1951    /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
1952    /// (the default); `OUT` / `INOUT` parse but the executor
1953    /// refuses them.
1954    pub mode: FunctionArgMode,
1955    /// Optional arg name. Trigger functions traditionally don't
1956    /// name their args (they read NEW/OLD instead), so `None` is
1957    /// the common case.
1958    pub name: Option<String>,
1959    /// Declared type, normalised to the SPG `DataType` mapping
1960    /// where one exists. Unknown / extension types parse as a
1961    /// raw string under [`FunctionArgType::Raw`].
1962    pub ty: FunctionArgType,
1963}
1964
1965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1966pub enum FunctionArgMode {
1967    In,
1968    Out,
1969    InOut,
1970}
1971
1972#[derive(Debug, Clone, PartialEq)]
1973pub enum FunctionArgType {
1974    Typed(ColumnTypeName),
1975    /// Unknown / extension types — kept as the parser-side raw
1976    /// identifier so error messages can name them precisely.
1977    Raw(String),
1978}
1979
1980#[derive(Debug, Clone, PartialEq)]
1981pub enum FunctionReturn {
1982    /// `RETURNS TRIGGER` — the row-level trigger function shape.
1983    /// v7.12.4 ships exactly this for execution.
1984    Trigger,
1985    /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
1986    /// the function is unused (since v7.12.4 doesn't ship scalar
1987    /// function invocation).
1988    Void,
1989    /// `RETURNS <type>` for any concrete data type. Reserved for
1990    /// v7.12.5+'s scalar UDF surface.
1991    Type(ColumnTypeName),
1992    /// `RETURNS <ident>` for types SPG doesn't know — extension
1993    /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
1994    Other(String),
1995}
1996
1997#[derive(Debug, Clone, PartialEq)]
1998pub enum FunctionBody {
1999    /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
2000    /// trigger-function executor walks this directly without
2001    /// re-parsing.
2002    PlPgSql(PlPgSqlBlock),
2003    /// Raw source text — parser couldn't (or didn't try to)
2004    /// structure-parse the body. Used for `LANGUAGE sql`
2005    /// functions and any PL/pgSQL body that contains v7.12.5+
2006    /// features the v7.12.4 parser doesn't yet recognise. The
2007    /// executor returns an unsupported error when invoked.
2008    Raw(String),
2009}
2010
2011/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
2012/// from assignment + return to a real-PL/pgSQL surface:
2013/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
2014/// control flow, `RAISE` diagnostics, and embedded SQL
2015/// statements that execute through the regular engine path.
2016/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
2017/// which mailrs's trigger doesn't need but other PG customers
2018/// may; deferred to a future minor release.
2019#[derive(Debug, Clone, PartialEq)]
2020pub struct PlPgSqlBlock {
2021    /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
2022    /// preceding `BEGIN`. Empty when the body opens directly with
2023    /// `BEGIN`. Declarations execute in order; each may reference
2024    /// earlier-declared locals in its init expression.
2025    pub declarations: Vec<PlPgSqlDeclare>,
2026    pub statements: Vec<PlPgSqlStmt>,
2027    /// v7.37.20 (20.10) — `EXCEPTION WHEN <cond> [OR <cond>...] THEN
2028    /// <body>` handlers appended to the block. Empty when no
2029    /// EXCEPTION clause is present. When a body statement raises
2030    /// (via RAISE EXCEPTION, ASSERT falsy, or a runtime error),
2031    /// handlers are tried in order; the first matching condition
2032    /// runs its body and the block terminates cleanly. `OTHERS`
2033    /// matches any exception. Unhandled exceptions propagate.
2034    pub exception_handlers: Vec<ExceptionHandler>,
2035}
2036
2037/// v7.37.20 (20.10) — one `WHEN <cond> [OR <cond>...] THEN <body>`
2038/// arm inside an EXCEPTION block.
2039#[derive(Debug, Clone, PartialEq)]
2040pub struct ExceptionHandler {
2041    /// Condition names (`OTHERS`, `unique_violation`, etc.). Multiple
2042    /// conditions joined by `OR` share one handler body.
2043    pub conditions: Vec<String>,
2044    /// Statements to run when a matching exception is caught.
2045    pub body: Vec<PlPgSqlStmt>,
2046}
2047
2048/// v7.12.6 — single `DECLARE` entry: variable name + declared
2049/// type + optional initialiser. Variables default to SQL NULL
2050/// when no init is given (matches PG).
2051#[derive(Debug, Clone, PartialEq)]
2052pub struct PlPgSqlDeclare {
2053    pub name: String,
2054    /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
2055    /// knows it; raw text otherwise).
2056    pub ty: FunctionArgType,
2057    pub default: Option<Expr>,
2058}
2059
2060#[derive(Debug, Clone, PartialEq)]
2061pub enum PlPgSqlStmt {
2062    /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
2063    /// for clarity in error reporting (PG also forbids it) — the
2064    /// executor errors with a clear "OLD is read-only" message.
2065    Assign { target: AssignTarget, value: Expr },
2066    /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
2067    /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
2068    /// the SELECT statement with the INTO clause stripped; the
2069    /// engine runs it via `Engine::execute`, takes the first
2070    /// row's first column, and assigns to the local variable
2071    /// in the DECLARE scope. Single-column / single-row
2072    /// queries only at v7.16.2; multi-target (`INTO a, b`) is
2073    /// a v7.16.x follow-up.
2074    SelectInto {
2075        var: String,
2076        body: Box<SelectStatement>,
2077    },
2078    /// `RETURN <target>;` — trigger functions canonically return
2079    /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
2080    /// expression for forward compatibility with scalar UDFs.
2081    Return(ReturnTarget),
2082    /// v7.39 (read01 round 66) — `RETURN NEXT <expr>;`: append one row to the
2083    /// set a SETOF function is building, and KEEP GOING. Not a return.
2084    ReturnNext(Expr),
2085    /// v7.39 (read01 round 66) — `RETURN QUERY <select>;`: append every row the
2086    /// query yields, and keep going. It used to desugar to a side-effect
2087    /// statement whose result was DISCARDED — in a SETOF function that is the
2088    /// whole answer thrown away.
2089    ReturnQuery(Box<SelectStatement>),
2090    /// v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the dynamic
2091    /// twin. Its rows go to the set too; it used to run and discard them.
2092    ReturnQueryExecute { sql: Expr },
2093    /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
2094    /// [ELSE body] END IF;`. Branches are tried in order; first
2095    /// truthy condition wins; the optional ELSE runs when no
2096    /// condition matched.
2097    If {
2098        branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
2099        else_branch: Vec<PlPgSqlStmt>,
2100    },
2101    /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
2102    /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
2103    /// (logging — observable side effect only) or `EXCEPTION`
2104    /// (aborts the trigger and propagates as an error). v7.12.6
2105    /// supports the basic format-string substitution PG uses
2106    /// (`%` placeholders consumed positionally).
2107    Raise {
2108        level: RaiseLevel,
2109        message: String,
2110        args: Vec<Expr>,
2111    },
2112    /// v7.12.6 — embedded SQL statement inside the trigger body
2113    /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
2114    /// NEW.col / OLD.col references inside the embedded
2115    /// statement's expression tree are substituted with the
2116    /// current trigger context before the engine re-executes the
2117    /// statement. Recursion depth into nested triggers is
2118    /// bounded by the engine's existing trigger-fire guard.
2119    EmbeddedSql(Box<Statement>),
2120    /// v7.37.20 (20.14) — `ASSERT <condition> [, <message>];`. If
2121    /// the condition evaluates falsy the trigger / DO block aborts
2122    /// with the message (defaulting to a generic shape when none
2123    /// is provided). Same propagation shape as `RAISE EXCEPTION`
2124    /// — the error reaches the caller's query path. PG's behaviour
2125    /// is identical except for a `plpgsql.check_asserts` GUC that
2126    /// can disable the check globally; SPG always evaluates.
2127    Assert {
2128        condition: Expr,
2129        message: Option<Expr>,
2130    },
2131    /// v7.37.20 (20.3) — `WHILE <condition> LOOP <body> END LOOP;`.
2132    /// Iterate the body while condition evaluates truthy. Iteration
2133    /// count is bounded by `WHILE_LOOP_BUDGET` to prevent runaway
2134    /// loops; the executor errors out when reached. EXIT / CONTINUE
2135    /// inside the body queue with 20.2.
2136    While {
2137        condition: Expr,
2138        body: Vec<PlPgSqlStmt>,
2139    },
2140    /// v7.37.20 (20.4) — `FOR <var> IN [REVERSE] <start>..<end> LOOP
2141    /// <body> END LOOP;`. Integer iteration; `var` is BigInt-valued;
2142    /// bounds inclusive on both sides. REVERSE walks backward.
2143    /// Iteration budget guards runaway.
2144    ForRange {
2145        var: String,
2146        start: Expr,
2147        end: Expr,
2148        reverse: bool,
2149        body: Vec<PlPgSqlStmt>,
2150    },
2151    /// v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`. Runs the body
2152    /// repeatedly; only `EXIT [WHEN <cond>]` breaks out. Iteration
2153    /// budget guards runaway.
2154    Loop { body: Vec<PlPgSqlStmt> },
2155    /// v7.37.20 (20.2) — `EXIT [WHEN <condition>];` inside a loop.
2156    /// Unconditional (no WHEN) or conditional (only breaks when
2157    /// condition is truthy). Bubbles up as BodyOutcome::Break which
2158    /// the enclosing loop catches. Outside a loop it's a no-op.
2159    Exit { when: Option<Expr> },
2160    /// v7.37.20 (20.2) — `CONTINUE [WHEN <condition>];` inside a
2161    /// loop. Same shape as EXIT but bubbles up as BodyOutcome::Continue
2162    /// which the enclosing loop catches, skipping the remainder of
2163    /// the body and jumping to the next iteration.
2164    Continue { when: Option<Expr> },
2165    /// v7.37.20 (20.13) — `EXECUTE <string_expr>;` runs a runtime-
2166    /// computed SQL statement. The expression is evaluated to a
2167    /// text value, the resulting string is parsed and dispatched
2168    /// through the engine like an EmbeddedSql. USING <param_list>
2169    /// for placeholder binding queues with v7.40 PL/pgSQL epic.
2170    ExecuteDynamic { sql: Expr },
2171    /// v7.37.20 (20.5) — `FOR <var> IN <select_body> LOOP <body>
2172    /// END LOOP;`. Runs the SELECT once, iterates the resulting
2173    /// rows, binds the first column of each row to `var` as a
2174    /// scalar Value, then runs the body per iteration. EXIT /
2175    /// CONTINUE / ASSERT / RAISE etc. propagate through the
2176    /// enclosing loop's BodyOutcome discipline the same way
2177    /// FOR range and WHILE do. Full record-binding (var as
2178    /// composite carrying all columns) queues with v7.40 record
2179    /// type infrastructure.
2180    ForQuery {
2181        var: String,
2182        query: Box<SelectStatement>,
2183        body: Vec<PlPgSqlStmt>,
2184    },
2185    /// v7.37.20 (20.6) — `FOR <var> IN EXECUTE <string_expr> LOOP
2186    /// <body> END LOOP;`. Same shape as ForQuery but the SELECT is
2187    /// computed at runtime from a text expression, parsed on the
2188    /// fly, then iterated. Enables dynamic queries where the
2189    /// projection / FROM / WHERE clauses depend on runtime values.
2190    ForExecute {
2191        var: String,
2192        sql_expr: Expr,
2193        body: Vec<PlPgSqlStmt>,
2194    },
2195}
2196
2197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2198pub enum RaiseLevel {
2199    /// `RAISE NOTICE` — diagnostic message, observable in the
2200    /// server log. Does not affect the trigger's outcome.
2201    Notice,
2202    /// `RAISE WARNING` — like NOTICE, slightly louder severity.
2203    Warning,
2204    /// `RAISE INFO` — like NOTICE, slightly quieter.
2205    Info,
2206    /// `RAISE LOG` — like NOTICE, lower priority.
2207    Log,
2208    /// `RAISE DEBUG` — like NOTICE, lowest priority.
2209    Debug,
2210    /// `RAISE EXCEPTION` — aborts the trigger function with the
2211    /// given message, propagating up to the caller as a query-
2212    /// level error.
2213    Exception,
2214}
2215
2216#[derive(Debug, Clone, PartialEq)]
2217pub enum AssignTarget {
2218    NewColumn(String),
2219    OldColumn(String),
2220    /// Reserved for v7.12.5 DECLARE'd local variables.
2221    Local(String),
2222}
2223
2224#[derive(Debug, Clone, PartialEq)]
2225pub enum ReturnTarget {
2226    /// `RETURN NEW;` — for BEFORE triggers, this is the row that
2227    /// actually gets written (possibly with NEW.col mutations
2228    /// applied). For AFTER triggers, the return value is ignored.
2229    New,
2230    /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
2231    /// the delete proceed; for BEFORE UPDATE / INSERT it's
2232    /// equivalent to dropping the write.
2233    Old,
2234    /// `RETURN NULL;` — for BEFORE triggers, skips the write
2235    /// entirely. For AFTER, the return value is ignored.
2236    Null,
2237    /// `RETURN <expr>;` — non-row return shape; reserved for the
2238    /// scalar UDF surface in v7.12.5+. Executor errors when used
2239    /// inside a trigger function.
2240    Expr(Expr),
2241}
2242
2243/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
2244/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
2245/// but the executor refuses them. `WHEN (cond)` clauses are out
2246/// of scope; the trigger function can short-circuit on a leading
2247/// IF inside its body once v7.12.5 lands IF.
2248#[derive(Debug, Clone, PartialEq)]
2249pub struct CreateTriggerStatement {
2250    pub name: String,
2251    pub or_replace: bool,
2252    pub timing: TriggerTiming,
2253    /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
2254    /// three entries in order.
2255    pub events: Vec<TriggerEvent>,
2256    pub table: String,
2257    /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
2258    /// only `Row`; `Statement` parses but the executor refuses.
2259    pub for_each: TriggerForEach,
2260    /// Name of the function to invoke. The function must exist at
2261    /// CREATE TRIGGER time — PG18-measured (round 753): PG refuses a
2262    /// forward reference (`function no_such_fn() does not exist`), so
2263    /// requiring it IS the PG behaviour (the old note claimed the
2264    /// opposite).
2265    pub function: String,
2266    /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
2267    /// (mailrs round-5 G7). Non-empty only when the events list
2268    /// contains UPDATE and the user wrote the column-list filter.
2269    /// PG fires the trigger only when at least one of these
2270    /// columns appears in the SET clause; SPG conservatively
2271    /// fires on any UPDATE matching the listed columns or
2272    /// rewriting them at the row level. Empty vec = no filter
2273    /// (fire on every UPDATE).
2274    pub update_columns: Vec<String>,
2275    /// v7.39 (round 138) — `WHEN ( condition )` row-level filter: the row
2276    /// trigger fires only when the condition (over NEW / OLD) is true. `None`
2277    /// = no WHEN (fire unconditionally). Not allowed on INSTEAD OF triggers.
2278    pub when_condition: Option<Expr>,
2279}
2280
2281/// v7.39 (round 139) — `CREATE RULE` query-rewrite rule AST node.
2282#[derive(Debug, Clone, PartialEq)]
2283pub struct CreateRuleStatement {
2284    pub name: String,
2285    pub or_replace: bool,
2286    /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
2287    pub event: String,
2288    pub table: String,
2289    /// `true` = `DO INSTEAD` (replace the operation), `false` = `DO ALSO`
2290    /// (run alongside; PG's default when neither keyword is written).
2291    pub instead: bool,
2292    /// Optional `WHERE ( condition )` — the rule applies only when it holds.
2293    pub when_condition: Option<Expr>,
2294    /// The `DO` commands (over NEW / OLD). Empty = `NOTHING`.
2295    pub commands: Vec<Statement>,
2296}
2297
2298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2299pub enum TriggerTiming {
2300    /// Fires before the row is written; the trigger function's
2301    /// return value (NEW or NULL) decides the row content and
2302    /// whether the write proceeds at all.
2303    Before,
2304    /// Fires after the row is written; the return value is
2305    /// ignored.
2306    After,
2307    /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
2308    /// v7.12.4 (SPG has no updatable-view surface).
2309    InsteadOf,
2310}
2311
2312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2313pub enum TriggerEvent {
2314    Insert,
2315    Update,
2316    Delete,
2317    /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
2318    /// so the trigger never fires.
2319    Truncate,
2320}
2321
2322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2323pub enum TriggerForEach {
2324    Row,
2325    Statement,
2326}
2327
2328/// v7.39 (round 537) — a `CREATE INDEX` key column's ordering clause.
2329///
2330/// SPG's index does not scan in a direction, but `indexdef` reproduces
2331/// the DDL and dropping this made `(a DESC NULLS LAST)` read back as
2332/// `(a)`. `nulls_first` is `None` when the statement did not say, in
2333/// which case PG's default applies — LAST for ascending, FIRST for
2334/// descending, and neither is rendered.
2335#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2336pub struct IndexColumnOrder {
2337    pub descending: bool,
2338    pub nulls_first: Option<bool>,
2339}
2340
2341#[derive(Debug, Clone, PartialEq)]
2342pub struct CreateIndexStatement {
2343    pub name: String,
2344    /// `CREATE INDEX CONCURRENTLY`. SPG builds indexes synchronously
2345    /// either way, so this changes nothing about how the index is made
2346    /// — it is carried because PG refuses the CONCURRENTLY form inside
2347    /// a transaction block and accepts the plain one, and the engine
2348    /// cannot tell them apart without it.
2349    pub concurrently: bool,
2350    /// v7.39 (round 537) — the leading key column's ordering clause,
2351    /// which is the column SPG indexes.
2352    pub key_order: IndexColumnOrder,
2353    /// v7.39 (round 538) — an explicit `COLLATE` on that key, as
2354    /// written. SPG orders text by bytes, so honouring it changes
2355    /// nothing; PG prints it, because an explicitly named collation and
2356    /// the one a column inherits are different objects.
2357    pub key_collation: Option<String>,
2358    pub table: String,
2359    pub column: String,
2360    /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2361    /// (PG 15+). Default (`false`) is the SQL-standard NULLS DISTINCT, where
2362    /// any NULL in the key exempts the row from the uniqueness check.
2363    pub nulls_not_distinct: bool,
2364    /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
2365    /// graph for vector kNN); unspecified is the default B-tree index.
2366    pub method: IndexMethod,
2367    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2368    /// index name already exists, instead of raising `DuplicateIndex`.
2369    pub if_not_exists: bool,
2370    /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
2371    /// non-key columns the planner should treat as "covered" by
2372    /// this index when checking whether a query can run as an
2373    /// index-only scan. Empty when no `INCLUDE` clause was given.
2374    pub included_columns: Vec<String>,
2375    /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
2376    /// for which `<expr>` evaluates truthy enter the index;
2377    /// queries whose `WHERE` clause's canonical Display form
2378    /// matches this expression's Display form can be served by the
2379    /// partial index. Stored as a parsed `Expr` so the engine
2380    /// re-uses the existing evaluation path; storage persists the
2381    /// Display form on the catalog snapshot.
2382    pub partial_predicate: Option<Expr>,
2383    /// v6.8.2 — expression-based index. When `Some(expr)`, the
2384    /// index key is the result of `expr` evaluated on each row
2385    /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
2386    /// field still names the *primary* column the expression
2387    /// touches so existing planner shortcuts that resolve a
2388    /// column position stay valid. `None` = plain
2389    /// column-reference index (the legacy shape).
2390    pub expression: Option<Expr>,
2391    /// v7.9.14 — extra column names after the leading column in a
2392    /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
2393    /// planner today still only uses the leading column for index
2394    /// seeks; the extras are tracked verbatim so the same DDL
2395    /// round-trips through WAL replay + catalog snapshot, and so
2396    /// the engine can emit a clear warning at INDEX CREATE time
2397    /// that only the leading column is currently honoured.
2398    /// Composite BTree index keys land in v7.10.
2399    pub extra_columns: Vec<String>,
2400    /// v7.39.11 — each extra column's `ASC` / `DESC` / `NULLS FIRST`
2401    /// / `NULLS LAST`, positionally aligned with `extra_columns`. The
2402    /// parser used to discard these, so a composite index's direction
2403    /// survived only on the leading column and `pg_get_indexdef`
2404    /// rendered `(a, b DESC)` back as `(a, b)`.
2405    pub extra_orders: Vec<IndexColumnOrder>,
2406    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2407    /// enforces uniqueness on the indexed key (combined with the
2408    /// `partial_predicate` filter — only rows where the predicate
2409    /// evaluates truthy enter the uniqueness check). Standard SQL
2410    /// and PG's canonical way to express conditional uniqueness.
2411    /// mailrs K1.
2412    pub is_unique: bool,
2413    /// v7.15.0 — operator class on the leading column, when the
2414    /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2415    /// Lower-cased. Most opclasses are still informational; the
2416    /// engine routes on `gin_trgm_ops` specifically to build a
2417    /// trigram-shingle GIN over a TEXT column, and otherwise
2418    /// keeps the current "accepted and discarded" behaviour for
2419    /// pg_dump compatibility.
2420    pub opclass: Option<String>,
2421    /// r1038 — the access method as WRITTEN, lower-cased; `None` when
2422    /// there was no `USING` clause.
2423    ///
2424    /// `method` cannot answer this: `gist` / `spgist` / `hash` all become
2425    /// `IndexMethod::BTree` so PG schemas naming an AM SPG has no
2426    /// implementation for still load. That degradation is deliberate, but
2427    /// it loses the name — and the operator-class check needs it, both to
2428    /// look the class up under the AM the user actually named and to say
2429    /// which AM it was missing from, the way PG's message does.
2430    pub method_name: Option<String>,
2431}
2432
2433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2434pub enum IndexMethod {
2435    /// Default — B-tree over `IndexKey`. Used for equality / range
2436    /// lookups on scalar columns.
2437    BTree,
2438    /// `USING hnsw` — NSW graph for kNN over a vector column.
2439    Hnsw,
2440    /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2441    /// metadata that records (min_key, max_key) for each page in a
2442    /// cold-tier segment, on the indexed column. The optimizer
2443    /// can use these summaries to skip pages whose range does NOT
2444    /// overlap a query's WHERE predicate. BRIN indexes carry no
2445    /// in-memory data — the summaries live in the segment v2
2446    /// envelope's sidecar. Created via the standard
2447    /// `CREATE INDEX … USING brin (col)` syntax.
2448    Brin,
2449    /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2450    /// column. Posting lists map `lexeme word` → row locators; the
2451    /// planner uses them to narrow `WHERE col @@ tsquery` to the
2452    /// candidate rows whose vectors contain a matching term, then
2453    /// re-evaluates the full `@@` semantics on each candidate.
2454    /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2455    /// silently degraded to a full scan at query time.
2456    Gin,
2457}
2458
2459/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2460/// inside a CREATE TABLE column list.
2461///
2462/// The source table's shape can only be read from the catalog, so the
2463/// parser records the clause and the engine expands it. `at` is how many
2464/// explicit columns preceded it: PG keeps the written order, so
2465/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2466#[derive(Debug, Clone, PartialEq)]
2467pub struct LikeSpec {
2468    pub source: String,
2469    pub at: usize,
2470    pub options: LikeOptions,
2471}
2472
2473/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2474/// types and NOT NULL and nothing else — measured on PG18, where a
2475/// copied generated column becomes a plain one and a copied identity
2476/// column loses its identity.
2477#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2478pub struct LikeOptions {
2479    pub defaults: bool,
2480    pub constraints: bool,
2481    pub identity: bool,
2482    pub generated: bool,
2483    pub indexes: bool,
2484    pub comments: bool,
2485}
2486
2487#[derive(Debug, Clone, PartialEq)]
2488pub struct CreateTableStatement {
2489    /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2490    /// creating session's own namespace: it shadows a permanent table of the
2491    /// same name, other sessions never see it, and it is dropped when the
2492    /// session ends. A `bool` here lands in the struct's existing padding.
2493    pub temporary: bool,
2494    pub name: String,
2495    /// v7.39 — the `ENGINE=` a MySQL dump names. Consumed and discarded
2496    /// before, so `ENGINE=NONSUCH` built a table where MySQL 9.7.2
2497    /// answers `ERROR 1286`, and `sql_mode` claimed
2498    /// `NO_ENGINE_SUBSTITUTION` while doing it.
2499    pub engine: Option<String>,
2500    pub columns: Vec<ColumnDef>,
2501    /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2502    /// the order written. Empty for a table that has none.
2503    pub like_specs: Vec<LikeSpec>,
2504    /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2505    /// Empty for a table that inherits from nothing. Order matters:
2506    /// the child takes each parent's columns in this order before its
2507    /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2508    pub inherits: Vec<String>,
2509    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2510    /// table name already exists, instead of raising `DuplicateTable`.
2511    pub if_not_exists: bool,
2512    /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2513    /// constraints. Column-level `REFERENCES` (single-column inline
2514    /// form) is normalised into this vec at parse time so the engine
2515    /// sees one uniform list.
2516    pub foreign_keys: Vec<ForeignKeyConstraint>,
2517    /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2518    /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2519    /// Engine resolves each into a BTree index named after the
2520    /// constraint's leading column at CREATE TABLE time; INSERT
2521    /// path enforces composite uniqueness via row scan on the
2522    /// leading column index.
2523    pub table_constraints: Vec<TableConstraint>,
2524    /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2525    /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2526    /// the engine creates a parent table whose own rows stay
2527    /// empty and routes INSERT/SELECT through children. Mutually
2528    /// exclusive with `partition_of` (parser enforces).
2529    pub partition_by: Option<PartitionBySpec>,
2530    /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2531    /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2532    /// the table inherits its column list from `parent` (the
2533    /// parser rejects an explicit column list when this is set);
2534    /// engine routes child rows back to the parent at INSERT.
2535    pub partition_of: Option<PartitionOfSpec>,
2536}
2537
2538/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2539/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2540/// future LIST / HASH without breaking the public AST shape.
2541#[derive(Debug, Clone, PartialEq)]
2542pub struct PartitionBySpec {
2543    pub kind: PartitionKindAst,
2544    /// One or more ident references into the parent's column list.
2545    /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2546    /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2547    /// shape PG-compatible.
2548    pub key_columns: Vec<String>,
2549}
2550
2551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2552pub enum PartitionKindAst {
2553    Range,
2554    /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2555    /// `FOR VALUES IN (lit, lit, …)`.
2556    List,
2557    /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2558    /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2559    Hash,
2560}
2561
2562/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2563/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2564/// or the catch-all `DEFAULT` partition.
2565#[derive(Debug, Clone, PartialEq)]
2566pub struct PartitionOfSpec {
2567    pub parent_name: String,
2568    pub bounds: PartitionOfBoundsAst,
2569}
2570
2571#[derive(Debug, Clone, PartialEq)]
2572pub enum PartitionOfBoundsAst {
2573    /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2574    /// (lits include vector bodies), so we box both bounds to keep
2575    /// the variant size in line with `Default` for clippy and to
2576    /// minimise per-statement footprint when the partition shape
2577    /// isn't in use.
2578    Range {
2579        lower: Box<Expr>,
2580        upper: Box<Expr>,
2581    },
2582    /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2583    /// expr resolves to a typed literal at child-create time.
2584    List {
2585        values: Vec<Expr>,
2586    },
2587    /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2588    /// PG enforces `0 ≤ r < m`; m must be positive.
2589    Hash {
2590        modulus: u32,
2591        remainder: u32,
2592    },
2593    Default,
2594}
2595
2596/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2597/// column list. Either a composite PRIMARY KEY or a UNIQUE
2598/// (single- or multi-column).
2599#[derive(Debug, Clone, PartialEq)]
2600pub enum TableConstraint {
2601    /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2602    /// referenced column. Engine builds a BTree index named
2603    /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2604    PrimaryKey {
2605        name: Option<String>,
2606        columns: Vec<String>,
2607        /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2608        /// Round 621 consumed the clauses; these carry them.
2609        deferrable: bool,
2610        initially_deferred: bool,
2611    },
2612    /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2613    /// named `<table>_<leading_col>_key` (single-column) or
2614    /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2615    /// uniqueness on INSERT.
2616    Unique {
2617        name: Option<String>,
2618        columns: Vec<String>,
2619        /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2620        /// G10). PG 15+ flips the NULL handling so any number of
2621        /// NULL rows collide on the constraint. Default is
2622        /// `false` (NULLS DISTINCT, standard SQL behaviour).
2623        nulls_not_distinct: bool,
2624        /// v7.39 (round 711) — see PrimaryKey.
2625        deferrable: bool,
2626        initially_deferred: bool,
2627    },
2628    /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2629    /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2630    /// this same variant at parse time. Engine evaluates the
2631    /// predicate against each INSERT/UPDATE candidate row; a
2632    /// false / NULL result rejects the mutation.
2633    /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2634    /// PG adds such a constraint without scanning the existing rows: new
2635    /// rows are checked, the ones already there are grandfathered in, and
2636    /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2637    /// scans and flips it. pg_dump emits the suffix for exactly those, so
2638    /// validating them on restore would refuse a dump PG itself produced.
2639    Check {
2640        name: Option<String>,
2641        expr: Expr,
2642        not_valid: bool,
2643    },
2644    /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2645    /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2646    /// every element (the booking/scheduling non-overlap constraint,
2647    /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2648    /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2649    /// enforcement doesn't build the index yet). Each element pairs a
2650    /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2651    Exclude {
2652        name: Option<String>,
2653        method: Option<String>,
2654        elements: Vec<(String, String)>,
2655    },
2656    /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2657    /// non-unique secondary-index declaration inline in CREATE
2658    /// TABLE. Engine builds a BTree index on the leading column
2659    /// (composite columns parse but only the leading column is
2660    /// honoured at v7.15 — matches the existing
2661    /// `CreateIndexStatement::extra_columns` semantics). Useful
2662    /// for `mysql/blog`-style schemas that lean on routine
2663    /// secondary indexes for ORM lookups.
2664    Index {
2665        name: Option<String>,
2666        columns: Vec<String>,
2667    },
2668    /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2669    /// (cols)` inline declaration. Pre-v7.17 the parser
2670    /// silently dropped these so MyISAM-imported FULLTEXT
2671    /// indexes vanished; v7.17 routes them through the
2672    /// existing tsvector-GIN engine path so MATCH AGAINST
2673    /// queries get a real inverted index instead of falling
2674    /// back to a full scan. Multi-column FULLTEXT KEYs build
2675    /// one GIN per column at v7.17 (per-column posting lists);
2676    /// the leading column drives query planning.
2677    FulltextIndex {
2678        name: Option<String>,
2679        columns: Vec<String>,
2680    },
2681}
2682
2683#[derive(Debug, Clone, PartialEq)]
2684#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2685pub struct ColumnDef {
2686    pub name: String,
2687    pub ty: ColumnTypeName,
2688    pub nullable: bool,
2689    /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2690    /// evaluates this once (with an empty row) and caches the resulting
2691    /// `Value` on the column schema.
2692    pub default: Option<Expr>,
2693    /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2694    /// per such column and fills the slot when INSERT leaves it
2695    /// unbound (omitted from a column-list INSERT or explicitly NULL).
2696    pub auto_increment: bool,
2697    /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2698    /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2699    /// an implicit BTree index named `<table>_pkey` over this
2700    /// column at CREATE TABLE time, satisfying the parent-side
2701    /// index requirement for any FOREIGN KEY pointing at it.
2702    pub is_primary_key: bool,
2703    /// v7.13.0 — inline `UNIQUE` column constraint
2704    /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2705    /// into a single-column `TableConstraint::Unique` so the
2706    /// engine path stays uniform with table-level UNIQUE.
2707    pub is_unique: bool,
2708    /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2709    /// inline column constraint: treat NULL keys as equal so only one NULL
2710    /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2711    /// `TableConstraint::Unique { nulls_not_distinct }`.
2712    pub unique_nulls_not_distinct: bool,
2713    /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2714    /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2715    /// since this round so the fold into the table-level constraint keeps it.
2716    pub constraint_deferrable: bool,
2717    pub constraint_initially_deferred: bool,
2718    /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2719    /// (mailrs round-5 G3). Stored alongside the column so the
2720    /// CREATE TABLE handler can fold these into table-level
2721    /// CHECK constraints. Multiple inline CHECKs on the same
2722    /// column are concatenated with AND at the table level.
2723    pub check: Option<Expr>,
2724    /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2725    /// parser sees an unknown column-type ident (anything not in
2726    /// the built-in `parse_column_type_name` table), it sets
2727    /// `ty = ColumnTypeName::Text` and records the original name
2728    /// here. The engine resolves at CREATE TABLE time: if a
2729    /// catalog enum/domain with this name exists, the column is
2730    /// bound to it (label-checked on INSERT for enums; CHECK-
2731    /// constrained for domains); otherwise the CREATE TABLE
2732    /// errors with "unknown type".
2733    pub user_type_ref: Option<String>,
2734    /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2735    /// CURRENT_TIMESTAMP` column attribute. When set, an
2736    /// UPDATE that does NOT explicitly bind this column
2737    /// overrides the new value with `now()` (engine clock).
2738    /// Pre-v7.17 SPG silently accepted the syntax and never
2739    /// fired the override — `updated_at` columns from mysqldump
2740    /// stayed pinned at their initial DEFAULT forever, an
2741    /// audit Tier-S silent-failure. Generalised as a stored
2742    /// expression source so future shapes (`ON UPDATE
2743    /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2744    /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2745    pub on_update_runtime: Option<Expr>,
2746    /// v7.17.0 Phase 2.5 — text collation derived from the
2747    /// post-fix `COLLATE <name>` clause (and / or the table-level
2748    /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2749    /// per column). Pre-2.5 SPG accepted the clause and
2750    /// discarded the name, leaving every column byte-compared
2751    /// — a Tier-S silent failure when the customer expected
2752    /// `_ci` / `case_insensitive` semantics. Parser normalises
2753    /// the raw collation name into the variants in `Collation`.
2754    /// Default `Binary` preserves the legacy compare path.
2755    pub collation: Collation,
2756    /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2757    /// explicit `COLLATE <name>` clause rather than the default. Under the
2758    /// MySQL dialect a text column with NO explicit clause takes the
2759    /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2760    /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2761    /// flag is the only thing that tells them apart.
2762    pub collation_explicit: bool,
2763    /// v7.39 (round 676) — the collation name AS WRITTEN, because
2764    /// `collation` above cannot carry it: `Collation` is a two-variant
2765    /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2766    /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2767    /// tell them apart.
2768    pub collation_name: Option<String>,
2769    /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2770    /// 4.4 SPG accepted and discarded the keyword, leaving
2771    /// negative values silently accepted on a column the
2772    /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2773    /// rejects negative INSERT / UPDATE values on UNSIGNED int
2774    /// columns. SPG widening to `u64`-shaped storage is out of
2775    /// v7.17 scope; the upper bound remains the signed-type max
2776    /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2777    /// exceeds what every mailrs / Rails app actually uses.
2778    pub is_unsigned: bool,
2779    /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2780    /// value list captured at parse time. When `Some`, the parser
2781    /// recognised `ENUM(...)` in the type slot; the engine
2782    /// validates INSERT cells against this list at
2783    /// column_def_to_schema time and persists the variants on
2784    /// `ColumnSchema.inline_enum_variants`. None for all
2785    /// non-ENUM columns.
2786    pub inline_enum_variants: Option<Vec<String>>,
2787    /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2788    /// value list. Distinct from ENUM (subset semantics rather
2789    /// than pick-one). None for all non-SET columns.
2790    pub inline_set_variants: Option<Vec<String>>,
2791    /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2792    /// STORED` computed-column source. When `Some`, the engine
2793    /// stores the Display-form of the parsed expression on
2794    /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2795    /// and re-evaluates the expression against every INSERT /
2796    /// UPDATE candidate row, overwriting whatever the caller
2797    /// supplied for this column. Boxed to keep `ColumnDef` from
2798    /// blowing past the `large_enum_variant` clippy ceiling
2799    /// (`Expr` widens with vector literals).
2800    pub generated_stored_expr: Option<Box<Expr>>,
2801    /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2802    /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2803    /// `auto_increment`; this additionally marks the ALWAYS one, whose
2804    /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2805    /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2806    /// VALUE`. Only meaningful when the column is also an identity column.
2807    pub identity_always: bool,
2808    /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2809    /// integer width (TINYINT / MEDIUMINT), captured before the type
2810    /// collapses to SmallInt / Int. The engine copies it to
2811    /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2812    /// path can enforce the real range. None for every other column and
2813    /// under the PG dialect.
2814    pub mysql_int_width: Option<MysqlIntWidth>,
2815    /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2816    /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2817    /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2818    /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2819    /// CREATE TABLE time so the write path can truncate and the render path
2820    /// can pad. None under the PG dialect, where temporal columns keep full
2821    /// microseconds.
2822    pub mysql_fsp: Option<u8>,
2823    /// v7.39.2 — the column was written `TIMESTAMP` rather than
2824    /// `DATETIME` in a MySQL session. The engine copies it to
2825    /// `ColumnSchema.mysql_declared_timestamp` at CREATE TABLE.
2826    pub mysql_declared_timestamp: bool,
2827    /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)` pair, copied to
2828    /// `ColumnSchema.mysql_float_md` at CREATE TABLE.
2829    pub mysql_float_md: Option<(u8, u8)>,
2830}
2831
2832/// v7.17.0 Phase 2.5 — text collation classification surfaced
2833/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2834/// engine bridges between the two at CREATE TABLE time.
2835///
2836/// Recognised collation-name patterns (case-insensitive):
2837///   * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase`         → CaseInsensitive
2838///   * Everything else (`C`, `POSIX`, `default`,
2839///     `pg_catalog.default`, `*_cs`, `*_bin`, unknown names)   → Binary
2840#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2841pub enum Collation {
2842    Binary,
2843    CaseInsensitive,
2844}
2845
2846/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2847/// integer width for a column whose `ColumnTypeName` is too wide to carry
2848/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2849/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2850/// TABLE time. Only recorded under the MySQL dialect.
2851#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2852pub enum MysqlIntWidth {
2853    Tiny,
2854    Small,
2855    Medium,
2856    Int,
2857    /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2858    Big,
2859}
2860
2861#[allow(clippy::derivable_impls)]
2862impl Default for Collation {
2863    fn default() -> Self {
2864        Self::Binary
2865    }
2866}
2867
2868impl Collation {
2869    /// Classify a `COLLATE <name>` ident into one of the supported
2870    /// variants. Empty / unknown names fall back to `Binary` —
2871    /// matches the pre-2.5 silent-accept behaviour for snapshots
2872    /// that load through but don't actually depend on the
2873    /// collation semantics.
2874    #[must_use]
2875    pub fn from_collation_name(name: &str) -> Self {
2876        let lc = name.trim().to_ascii_lowercase();
2877        // Strip any quotes / schema-qualifier the parser left on
2878        // (e.g. `pg_catalog.default`).
2879        let bare = lc
2880            .trim_matches(|c: char| c == '"' || c == '\'')
2881            .rsplit('.')
2882            .next()
2883            .unwrap_or("");
2884        if bare.is_empty() {
2885            return Self::Binary;
2886        }
2887        if bare == "case_insensitive" || bare == "nocase" {
2888            return Self::CaseInsensitive;
2889        }
2890        // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2891        // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2892        if bare.ends_with("_ci") {
2893            return Self::CaseInsensitive;
2894        }
2895        Self::Binary
2896    }
2897}
2898
2899/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2900/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2901/// parse into this shape — the column-level form has a single-entry
2902/// `columns` / `parent_columns`.
2903#[derive(Debug, Clone, PartialEq)]
2904pub struct ForeignKeyConstraint {
2905    /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2906    /// today but parses + stores it so a future ALTER TABLE DROP
2907    /// CONSTRAINT can target by name (v7.6.8).
2908    pub name: Option<String>,
2909    /// Local columns participating in the FK (≥ 1).
2910    pub columns: Vec<String>,
2911    /// Referenced parent table.
2912    pub parent_table: String,
2913    /// Referenced parent columns. Must have the same arity as
2914    /// `columns`; engine validates parent has a PK / UNIQUE index
2915    /// on exactly this column set (v7.6.1).
2916    pub parent_columns: Vec<String>,
2917    /// `ON DELETE` action. Defaults to `Restrict` if absent.
2918    pub on_delete: FkAction,
2919    /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2920    pub on_update: FkAction,
2921    /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2922    pub match_type: MatchType,
2923    /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2924    /// dropped on the floor, so a constraint declared DEFERRABLE was
2925    /// enforced immediately and a circular-FK migration could not load.
2926    pub deferrable: bool,
2927    /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2928    /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2929    pub initially_deferred: bool,
2930}
2931
2932/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2933/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2934/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2935#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2936pub enum MatchType {
2937    #[default]
2938    Simple,
2939    Full,
2940}
2941
2942/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2943#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2944pub enum FkAction {
2945    /// Reject the parent mutation if any child row references it.
2946    /// SQL spec default; SPG default when no clause is given.
2947    Restrict,
2948    /// Recursively propagate the parent's delete / update to the
2949    /// child rows. Same TX.
2950    Cascade,
2951    /// Set the child FK column(s) to NULL. Requires the FK columns
2952    /// to be NULL-able.
2953    SetNull,
2954    /// Set the child FK column(s) to their declared DEFAULT.
2955    /// Requires the child column(s) to have DEFAULT.
2956    SetDefault,
2957    /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2958    /// `Restrict` because the single-writer model has no deferred
2959    /// constraint window; the keyword is accepted for compatibility.
2960    NoAction,
2961}
2962
2963/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2964/// optional `USING <encoding>` clause; omitting it keeps the
2965/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2966/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2967/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2968/// binary16 (2× compression, ~3 decimal digits of precision).
2969#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2970pub enum VecEncoding {
2971    /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
2972    /// uncompressed `vector` type wire / storage layout.
2973    #[default]
2974    F32,
2975    /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
2976    /// `spg_storage::quantize::Sq8Vector` for the math + recall
2977    /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
2978    /// dim ≥ 32).
2979    Sq8,
2980    /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
2981    /// per-element. DDL keyword `HALF` (pgvector convention).
2982    /// Bit-exact dequantise to f32 at the storage layer; no
2983    /// rerank pass needed for kNN search.
2984    F16,
2985}
2986
2987impl fmt::Display for VecEncoding {
2988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2989        match self {
2990            Self::F32 => f.write_str("F32"),
2991            Self::Sq8 => f.write_str("SQ8"),
2992            // pgvector convention: DDL keyword is `HALF`, not `F16`.
2993            Self::F16 => f.write_str("HALF"),
2994        }
2995    }
2996}
2997
2998/// SQL-level type names. The mapping to the storage runtime's `DataType`
2999/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
3000#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3001pub enum ColumnTypeName {
3002    /// v7.39 (round 291) — PG's `name`, the identifier type its
3003    /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
3004    /// answered `type "name" does not exist` to.
3005    Name,
3006    /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
3007    /// 32-bit wrapping counter the row header carries; `xid8` is the
3008    /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
3009    /// SPG answered `type "xid" does not exist` to.
3010    Xid,
3011    Xid8,
3012    /// v7.39 (round 667) — `OID`. `XID` was already a column type here
3013    /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
3014    /// `type "oid" does not exist` while `t(x XID)` built fine.
3015    Oid,
3016    SmallInt,
3017    Int,
3018    BigInt,
3019    Float,
3020    /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
3021    /// IEEE. It used to map to [`Self::Float`] on the theory that a
3022    /// wider float is harmless, but the width is observable: a `real`
3023    /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
3024    /// answered false where PG answers true.
3025    Real,
3026    Text,
3027    /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
3028    Varchar(u32),
3029    /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
3030    Char(u32),
3031    Bool,
3032    /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
3033    /// `USING <encoding>` clause; omitting it surfaces as
3034    /// `encoding = VecEncoding::F32` (the pre-v6 default).
3035    Vector {
3036        dim: u32,
3037        encoding: VecEncoding,
3038    },
3039    /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
3040    /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
3041    /// v7.39 (round 271) — scale widened to u16 alongside the value's.
3042    /// v7.39 (round 272) — precision too: PG's runs to 1000.
3043    /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
3044    /// a negative one rounds to tens / hundreds. A VALUE's display scale
3045    /// stays unsigned.
3046    Numeric(u16, i16),
3047    /// `DATE` — calendar day, no time-of-day component.
3048    Date,
3049    /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
3050    /// precision.
3051    Timestamp,
3052    /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
3053    /// stores all timestamps as UTC microseconds-since-epoch and
3054    /// does not carry per-row offset (PG's internal representation
3055    /// is the same — TZ is a display convention). The distinction
3056    /// from `TIMESTAMP` exists for the PG-wire layer to advertise
3057    /// OID 1184 so sqlx-style clients decode into
3058    /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
3059    Timestamptz,
3060    /// v4.9 `JSON` — text-backed JSON document. No parse-time
3061    /// validation; the engine round-trips the literal verbatim.
3062    /// PG OID 114 on the wire.
3063    Json,
3064    /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
3065    /// PG OID 3802 on the wire so sqlx-style binary-typed clients
3066    /// decode without a custom type registration.
3067    Jsonb,
3068    /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
3069    /// Literal forms (decoded by the engine at coercion time):
3070    ///   - PG hex form: `'\xDEADBEEF'`
3071    ///   - Escape form: `'foo\\000bar'` (backslash octal triples)
3072    Bytes,
3073    /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
3074    /// OID 1009. Literal forms accepted by the parser:
3075    ///   - `ARRAY['a', 'b', NULL]`
3076    ///   - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
3077    ///     form at coerce time)
3078    TextArray,
3079    /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
3080    /// 1007. Same literal forms as TEXT[] (substituting integer
3081    /// elements).
3082    IntArray,
3083    /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
3084    /// OID 1016.
3085    BigIntArray,
3086    /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
3087    /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
3088    /// external form). G-CRIT-3.
3089    TsVector,
3090    /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
3091    /// wire OID 3615.
3092    TsQuery,
3093    /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
3094    /// Literal input accepts canonical hyphenated, unhyphenated,
3095    /// uppercase, and `{...}`-braced forms; display normalises to
3096    /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
3097    /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
3098    /// gen_random_uuid()`.
3099    Uuid,
3100    /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
3101    /// microseconds since 00:00:00. PG wire OID 1083. Literal
3102    /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
3103    /// (6-digit microsecond precision). Display normalises to
3104    /// the canonical `HH:MM:SS[.ffffff]`.
3105    Time,
3106    /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
3107    /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
3108    /// PG OID; advertised as INT4 on the wire. Display always
3109    /// 4 digits zero-padded.
3110    Year,
3111    /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
3112    /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
3113    /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
3114    /// Offset range: ±14 hours.
3115    TimeTz,
3116    /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
3117    /// (locale-independent storage). Wire OID 790. Literal input
3118    /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
3119    /// major units), optional leading `-`. Display: en_US locale.
3120    Money,
3121    /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
3122    /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
3123    /// — the engine bridges to `DataType::Range(RangeKind)`.
3124    Range(RangeKindAst),
3125    /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
3126    /// `text => text` map with NULL value support.
3127    Hstore,
3128    /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
3129    IntArray2D,
3130    BigIntArray2D,
3131    TextArray2D,
3132    /// v7.39 (read01 round 75) — `bool[][]`.
3133    BoolArray2D,
3134    /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
3135    /// three-field {months, days, micros} struct (PG-byte-equal),
3136    /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
3137    /// β-P2 `INTERVAL` was runtime-only — literal in expression
3138    /// position but rejected at CREATE TABLE.
3139    Interval,
3140    /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
3141    /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
3142    /// PG external form quotes each non-NULL element because
3143    /// interval text contains spaces / colons
3144    /// (`{"1 day","24:00:00",NULL}`).
3145    IntervalArray,
3146    /// v7.37.5 γ — full PG array-of-scalar family. Each variant
3147    /// mirrors a scalar `ColumnTypeName` that already existed.
3148    BoolArray,
3149    SmallIntArray,
3150    FloatArray,
3151    NumericArray,
3152    DateArray,
3153    TimestampArray,
3154    TimestamptzArray,
3155    UuidArray,
3156    JsonArray,
3157    JsonbArray,
3158    BytesArray,
3159    VarcharArray,
3160    CharArray,
3161    /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
3162    /// as `Range(RangeKindAst)` — one column type variant covers
3163    /// all six builtin multiranges, kind pins the element type.
3164    /// Wire OIDs in pgwire.
3165    Multirange(RangeKindAst),
3166    /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3167    /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3168    /// Wire OIDs in pgwire.
3169    Point,
3170    Lseg,
3171    Path,
3172    PgBox,
3173    Polygon,
3174    Line,
3175    Circle,
3176    /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3177    Inet,
3178    Cidr,
3179    Macaddr,
3180    Macaddr8,
3181    /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3182    Bit(u32),
3183    /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3184    BitVarying(u32),
3185    Xml,
3186    Char1,
3187    MoneyArray,
3188}
3189
3190/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3191/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3192/// crate doesn't depend on storage. Bridged at engine boundary.
3193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3194pub enum RangeKindAst {
3195    Int4,
3196    Int8,
3197    Num,
3198    Ts,
3199    TsTz,
3200    Date,
3201}
3202
3203impl fmt::Display for ColumnTypeName {
3204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3205        match self {
3206            Self::SmallInt => f.write_str("SMALLINT"),
3207            Self::Int => f.write_str("INT"),
3208            Self::BigInt => f.write_str("BIGINT"),
3209            Self::Float => f.write_str("FLOAT"),
3210            Self::Real => f.write_str("REAL"),
3211            Self::Text => f.write_str("TEXT"),
3212            Self::Name => f.write_str("name"),
3213            Self::Xid => f.write_str("xid"),
3214            Self::Xid8 => f.write_str("xid8"),
3215            Self::Oid => f.write_str("oid"),
3216            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3217            Self::Char(n) => write!(f, "CHAR({n})"),
3218            Self::Bool => f.write_str("BOOL"),
3219            Self::Vector { dim, encoding } => match encoding {
3220                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3221                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3222                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3223            },
3224            Self::Json => f.write_str("JSON"),
3225            Self::Jsonb => f.write_str("JSONB"),
3226            Self::Bytes => f.write_str("BYTEA"),
3227            Self::TextArray => f.write_str("TEXT[]"),
3228            Self::IntArray => f.write_str("INT[]"),
3229            Self::BigIntArray => f.write_str("BIGINT[]"),
3230            Self::TsVector => f.write_str("TSVECTOR"),
3231            Self::TsQuery => f.write_str("TSQUERY"),
3232            Self::Uuid => f.write_str("UUID"),
3233            Self::Numeric(p, s) => {
3234                if *s == 0 {
3235                    write!(f, "NUMERIC({p})")
3236                } else {
3237                    write!(f, "NUMERIC({p}, {s})")
3238                }
3239            }
3240            Self::Date => f.write_str("DATE"),
3241            Self::Timestamp => f.write_str("TIMESTAMP"),
3242            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3243            Self::Time => f.write_str("TIME"),
3244            Self::Year => f.write_str("YEAR"),
3245            Self::TimeTz => f.write_str("TIMETZ"),
3246            Self::Money => f.write_str("MONEY"),
3247            Self::Range(k) => f.write_str(match k {
3248                RangeKindAst::Int4 => "INT4RANGE",
3249                RangeKindAst::Int8 => "INT8RANGE",
3250                RangeKindAst::Num => "NUMRANGE",
3251                RangeKindAst::Ts => "TSRANGE",
3252                RangeKindAst::TsTz => "TSTZRANGE",
3253                RangeKindAst::Date => "DATERANGE",
3254            }),
3255            Self::Hstore => f.write_str("HSTORE"),
3256            Self::Interval => f.write_str("INTERVAL"),
3257            Self::IntervalArray => f.write_str("INTERVAL[]"),
3258            Self::BoolArray => f.write_str("BOOL[]"),
3259            Self::SmallIntArray => f.write_str("SMALLINT[]"),
3260            Self::FloatArray => f.write_str("FLOAT[]"),
3261            Self::NumericArray => f.write_str("NUMERIC[]"),
3262            Self::DateArray => f.write_str("DATE[]"),
3263            Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3264            Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3265            Self::UuidArray => f.write_str("UUID[]"),
3266            Self::JsonArray => f.write_str("JSON[]"),
3267            Self::JsonbArray => f.write_str("JSONB[]"),
3268            Self::BytesArray => f.write_str("BYTEA[]"),
3269            Self::VarcharArray => f.write_str("VARCHAR[]"),
3270            Self::CharArray => f.write_str("CHAR[]"),
3271            Self::Multirange(k) => f.write_str(match k {
3272                RangeKindAst::Int4 => "INT4MULTIRANGE",
3273                RangeKindAst::Int8 => "INT8MULTIRANGE",
3274                RangeKindAst::Num => "NUMMULTIRANGE",
3275                RangeKindAst::Ts => "TSMULTIRANGE",
3276                RangeKindAst::TsTz => "TSTZMULTIRANGE",
3277                RangeKindAst::Date => "DATEMULTIRANGE",
3278            }),
3279            Self::Point => f.write_str("POINT"),
3280            Self::Lseg => f.write_str("LSEG"),
3281            Self::Path => f.write_str("PATH"),
3282            Self::PgBox => f.write_str("BOX"),
3283            Self::Polygon => f.write_str("POLYGON"),
3284            Self::Line => f.write_str("LINE"),
3285            Self::Circle => f.write_str("CIRCLE"),
3286            Self::Inet => f.write_str("INET"),
3287            Self::Cidr => f.write_str("CIDR"),
3288            Self::Macaddr => f.write_str("MACADDR"),
3289            Self::Macaddr8 => f.write_str("MACADDR8"),
3290            Self::Bit(0) => f.write_str("BIT"),
3291            Self::Bit(n) => write!(f, "BIT({n})"),
3292            Self::BitVarying(0) => f.write_str("VARBIT"),
3293            Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3294            Self::Xml => f.write_str("XML"),
3295            Self::Char1 => f.write_str("\"char\""),
3296            Self::MoneyArray => f.write_str("MONEY[]"),
3297            Self::IntArray2D => f.write_str("INT[][]"),
3298            Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3299            Self::TextArray2D => f.write_str("TEXT[][]"),
3300            Self::BoolArray2D => f.write_str("BOOL[][]"),
3301        }
3302    }
3303}
3304
3305/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3306/// engine evaluates `expr` per matched row in the table's row order
3307/// and rewrites cells in place. Indexed columns are dropped + re-
3308/// inserted into the affected B-tree on each row change.
3309/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3310/// tail on a DML statement. Boxed off the statement struct so the PG-only
3311/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3312/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3313/// the identical meaning, so both share this one payload rather than each
3314/// growing its own.
3315#[derive(Debug, Clone, PartialEq)]
3316pub struct DmlOrderLimit {
3317    pub order_by: Vec<OrderBy>,
3318    pub limit: Option<u32>,
3319}
3320
3321/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3322/// FROM, kept so the engine can finish the job.
3323///
3324/// The parser rewrites the statement onto correlated subqueries, and it
3325/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3326/// name belongs to the target or to a source needs their column lists,
3327/// which parse time does not have. Carrying the clause lets the engine
3328/// — which has the catalog — resolve the rest.
3329#[derive(Debug, Clone, PartialEq)]
3330pub struct UpdateFromSources {
3331    pub from: FromClause,
3332    pub sub_where: Option<Expr>,
3333}
3334
3335#[derive(Debug, Clone, PartialEq)]
3336pub struct UpdateStatement {
3337    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3338    /// level UPDATE. Empty for a plain UPDATE.
3339    pub ctes: Vec<Cte>,
3340    pub table: String,
3341    /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3342    /// to `t`'s own rows and not to anything that descends from it.
3343    ///
3344    /// Round 644 taught the FROM clause the keyword and left DML behind
3345    /// because it needed a field here, and this struct carries a warning
3346    /// that round 413 measured widening it in place overflowing the
3347    /// parser's nesting stack. That warning was about `from_sources`, a
3348    /// struct wide enough to need boxing; a `bool` lands in the padding
3349    /// already present — same as `CreateTableStatement::temporary`.
3350    ///
3351    /// It also earns its keep beyond the spelling: the inheritance
3352    /// fan-out needs a way to say "the parent's own rows" as a
3353    /// statement, or running one on the parent recurses forever.
3354    pub only: bool,
3355    /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3356    /// statement's expressions refer to the target row by. PG allows the
3357    /// bare spelling here (unlike INSERT, which requires AS).
3358    pub alias: Option<String>,
3359    pub assignments: Vec<(String, Expr)>,
3360    /// v7.39 (round 533) — boxed: round 413 measured that widening this
3361    /// struct in place overflows the parser's nesting stack.
3362    pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3363    pub where_: Option<Expr>,
3364    /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3365    /// mutate the first `limit` rows in the given order. PG has no such
3366    /// clause; the parser accepts it only under the MySQL dialect. Boxed
3367    /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3368    /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3369    /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3370    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3371    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3372    /// clause (legacy CommandComplete path). Some = engine
3373    /// evaluates the projection over each mutated row and
3374    /// streams the result as a Rows QueryResult.
3375    pub returning: Option<Vec<SelectItem>>,
3376}
3377
3378/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3379/// from the active catalog and prunes them from every index.
3380#[derive(Debug, Clone, PartialEq)]
3381pub struct DeleteStatement {
3382    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3383    /// level DELETE. Empty for a plain DELETE.
3384    pub ctes: Vec<Cte>,
3385    pub table: String,
3386    /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3387    /// to `t`'s own rows and not to anything that descends from it.
3388    ///
3389    /// Round 644 taught the FROM clause the keyword and left DML behind
3390    /// because it needed a field here, and this struct carries a warning
3391    /// that round 413 measured widening it in place overflowing the
3392    /// parser's nesting stack. That warning was about `from_sources`, a
3393    /// struct wide enough to need boxing; a `bool` lands in the padding
3394    /// already present — same as `CreateTableStatement::temporary`.
3395    ///
3396    /// It also earns its keep beyond the spelling: the inheritance
3397    /// fan-out needs a way to say "the parent's own rows" as a
3398    /// statement, or running one on the parent recurses forever.
3399    pub only: bool,
3400    /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3401    /// the WHERE / RETURNING expressions refer to the target row by.
3402    pub alias: Option<String>,
3403    pub where_: Option<Expr>,
3404    /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3405    /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3406    /// form (round 413), so it shares that payload — and it is boxed for
3407    /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3408    /// statement tipped the parser's 512 KiB nesting stack.
3409    pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3410    /// v7.9.4 — `RETURNING <projection>`.
3411    pub returning: Option<Vec<SelectItem>>,
3412}
3413
3414/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3415/// One WHEN clause fires per source row depending on whether the
3416/// `on` condition matched any target row(s); the executor walks
3417/// `clauses` in declaration order and fires the first whose
3418/// `matched` kind and optional `condition` are both satisfied.
3419#[derive(Debug, Clone, PartialEq)]
3420pub struct MergeStatement {
3421    /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3422    /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3423    /// in PG). Each CTE materialises before the merge runs and its alias
3424    /// resolves as a source relation.
3425    pub ctes: Vec<Cte>,
3426    pub target: String,
3427    pub target_alias: Option<String>,
3428    pub source: String,
3429    pub source_alias: Option<String>,
3430    /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3431    /// the engine materialises this SELECT for the source rows and `source`
3432    /// is empty; the alias (required by PG for a subquery source) is in
3433    /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3434    pub source_select: Option<Box<SelectStatement>>,
3435    /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3436    /// positional column-alias list after the source alias. Empty when
3437    /// the statement carries none; the engine renames the materialised
3438    /// source columns positionally (PG's rule).
3439    pub source_column_aliases: Vec<String>,
3440    pub on: Expr,
3441    pub clauses: Vec<MergeWhenClause>,
3442    /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3443    /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3444    /// target/source aliases. `None` = no RETURNING (the common form).
3445    pub returning: Option<Vec<SelectItem>>,
3446}
3447
3448#[derive(Debug, Clone, PartialEq)]
3449pub struct MergeWhenClause {
3450    pub matched: MergeMatched,
3451    /// Optional `AND <expr>` filter — when present, the clause
3452    /// only fires for the source rows whose match-pair satisfies
3453    /// the predicate.
3454    pub condition: Option<Expr>,
3455    pub action: MergeAction,
3456}
3457
3458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3459pub enum MergeMatched {
3460    Matched,
3461    /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3462    /// target row (the classic insert branch).
3463    NotMatched,
3464    /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3465    /// row no source row matches. Actions are UPDATE / DELETE / DO
3466    /// NOTHING only (INSERT is a syntax error, as in PG).
3467    NotMatchedBySource,
3468}
3469
3470#[derive(Debug, Clone, PartialEq)]
3471pub enum MergeAction {
3472    /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3473    /// explicit column list (the bare `INSERT VALUES (vals)`
3474    /// shape lands later).
3475    Insert {
3476        columns: Vec<String>,
3477        values: Vec<Expr>,
3478    },
3479    /// `UPDATE SET col = expr [, …]` — applied to every matched
3480    /// target row for the firing source row.
3481    Update { assignments: Vec<(String, Expr)> },
3482    /// `DELETE` — drop every matched target row.
3483    Delete,
3484    /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3485    /// the clause and SPG mirrors so a customer-side MERGE that
3486    /// uses it for branch-control doesn't error).
3487    DoNothing,
3488}
3489
3490#[derive(Debug, Clone, PartialEq)]
3491pub struct InsertStatement {
3492    /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3493    /// level INSERT (writable CTE outer body). Empty for a plain
3494    /// INSERT. PG semantics: each CTE materialises before the
3495    /// outer INSERT runs, sharing the same transaction.
3496    pub ctes: Vec<Cte>,
3497    pub table: String,
3498    /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3499    /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3500    /// row by. PG requires the AS keyword in this position.
3501    pub alias: Option<String>,
3502    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3503    /// `None`, every tuple is positional and must match the table arity.
3504    /// When `Some`, the engine maps each tuple slot to the named column and
3505    /// fills the rest with NULL (must be nullable).
3506    pub columns: Option<Vec<String>>,
3507    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3508    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3509    /// `select_source` is `Some` (the engine builds rows from the
3510    /// inner SELECT result set instead).
3511    pub rows: Vec<Vec<Expr>>,
3512    /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3513    /// round-5 G4). When present, `rows` is empty and the engine
3514    /// materialises the SELECT result, coerces each output tuple to
3515    /// the target column types, and inserts as a single batch.
3516    pub select_source: Option<Box<SelectStatement>>,
3517    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3518    /// upsert clause. None = legacy INSERT (conflict raises a
3519    /// DuplicateKey error). mailrs migration blocker #2.
3520    pub on_conflict: Option<OnConflictClause>,
3521    /// v7.9.4 — `RETURNING <projection>`.
3522    pub returning: Option<Vec<SelectItem>>,
3523    /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3524    /// between the column list and VALUES. Governs how explicitly-supplied
3525    /// values interact with `GENERATED … AS IDENTITY` columns:
3526    ///   * `None` — default. A `GENERATED ALWAYS` identity column rejects
3527    ///     an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3528    ///   * `System` — override the ALWAYS restriction: the explicit value
3529    ///     is used verbatim, as for a `BY DEFAULT` column.
3530    ///   * `User` — ignore any explicit value on a `BY DEFAULT` identity
3531    ///     column and generate from the sequence instead (no effect on
3532    ///     non-identity columns).
3533    pub overriding: Overriding,
3534    /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3535    /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3536    /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3537    /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3538    /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3539    /// into a NOT NULL column becomes the type's default), and the engine
3540    /// cannot recover that intent from the conflict clause alone. A plain
3541    /// `bool` lands in this struct's existing padding, so the AST does not
3542    /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3543    pub mysql_ignore: bool,
3544}
3545
3546/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3547#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3548pub enum Overriding {
3549    /// No `OVERRIDING` clause.
3550    #[default]
3551    None,
3552    /// `OVERRIDING SYSTEM VALUE`.
3553    System,
3554    /// `OVERRIDING USER VALUE`.
3555    User,
3556}
3557
3558/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3559#[derive(Debug, Clone, PartialEq)]
3560pub struct OnConflictClause {
3561    /// Local columns that identify the conflict (must match a
3562    /// UNIQUE / PRIMARY KEY index on the target table). Empty
3563    /// list means the user wrote `ON CONFLICT DO …` without a
3564    /// target — the engine arbitrates on every unique constraint
3565    /// (round 240).
3566    pub target_columns: Vec<String>,
3567    /// v7.39 (round 240) — the index predicate after the target list
3568    /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3569    /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3570    /// which satisfy any predicate, so it is parsed and carried but not
3571    /// consulted (recorded residual: partial-unique-index arbiters).
3572    pub index_where: Option<Expr>,
3573    /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3574    /// <name>`: the pg_dump conflict-target form. The engine
3575    /// resolves the name to the constraint's columns.
3576    pub constraint_name: Option<String>,
3577    /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3578    /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3579    /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3580    /// `ON CONFLICT DO UPDATE` is refused (42601).
3581    pub mysql_lowered: bool,
3582    /// The action on conflict.
3583    pub action: OnConflictAction,
3584}
3585
3586/// v7.9.7 — action on conflict.
3587#[derive(Debug, Clone, PartialEq)]
3588pub enum OnConflictAction {
3589    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3590    /// silently skips conflicting ones.
3591    Nothing,
3592    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3593    /// may reference `EXCLUDED.col` to read the incoming row's
3594    /// value (engine wires `EXCLUDED` as a virtual table).
3595    Update {
3596        assignments: Vec<(String, Expr)>,
3597        where_: Option<Expr>,
3598    },
3599}
3600
3601/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3602///
3603/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3604/// policies are spelled again here and mapped at the engine boundary.
3605/// v7.39 — the modes `BEGIN` / `START TRANSACTION` / `SET TRANSACTION`
3606/// / `SET SESSION CHARACTERISTICS` accept. `read_only` used to be parsed
3607/// and dropped on the floor, so `BEGIN READ ONLY` opened an ordinary
3608/// read-write transaction and every write in it was accepted.
3609///
3610/// `None` on either field means the statement did not name that mode, so
3611/// the session default applies — which is not the same as naming the
3612/// default explicitly.
3613#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3614pub struct TransactionModes {
3615    pub isolation: Option<IsolationLevel>,
3616    /// `Some(true)` = READ ONLY, `Some(false)` = READ WRITE.
3617    pub read_only: Option<bool>,
3618}
3619
3620/// v7.39 — what a read-only transaction refuses, and what PG calls it.
3621///
3622/// SPG did not enforce read-only transactions at all: `BEGIN READ ONLY;
3623/// INSERT …` answered `INSERT 0 1` and committed, and
3624/// `default_transaction_read_only = on` changed nothing. Both GUCs were
3625/// in the inventory, so a session could set one, read it back, and be
3626/// told it held a guarantee nothing was enforcing. Applications open
3627/// read-only transactions as a SAFETY measure — a reporting connection,
3628/// a read-only leg in a pool, a "this path must not write" discipline —
3629/// so accepting the writes is the worst possible answer.
3630///
3631/// `Some(tag)` means refuse with PG's message, `cannot execute {tag} in
3632/// a read-only transaction` (SQLSTATE 25006). Every tag below was read
3633/// back from PostgreSQL 18.6 by running the statement inside
3634/// `BEGIN READ ONLY`, one statement per transaction so no error could be
3635/// attributed to the wrong line.
3636///
3637/// Several answers were not what one would guess, which is why they were
3638/// measured rather than reasoned:
3639///
3640///   * `CREATE TEMP TABLE` is REFUSED, tagged `CREATE TABLE`.
3641///   * `NOTIFY`, `LISTEN` and `REINDEX` are ALLOWED.
3642///   * `PREPARE` of an INSERT is ALLOWED — only the EXECUTE writes.
3643///   * `UPDATE … WHERE false`, which changes nothing, is still REFUSED:
3644///     the verb decides, not the row count.
3645///   * `GRANT`, `COMMENT ON` and `SELECT … FOR SHARE` are all REFUSED.
3646///
3647/// The match is exhaustive on purpose. A new statement cannot be added
3648/// without deciding here whether it writes, which is the failure this
3649/// repository keeps meeting: one member of a family gets handled and its
3650/// siblings quietly do not.
3651impl Statement {
3652    #[must_use]
3653    pub fn read_only_violation_tag(&self) -> Option<&'static str> {
3654        match self {
3655            // v7.39.9 — MySQL's RENAME TABLE is DDL, refused read-only
3656            // for the same reason ALTER TABLE … RENAME TO is.
3657            Self::RenameTables(_) => Some("RENAME TABLE"),
3658            // ---- writes rows -------------------------------------------
3659            Self::Insert { .. } => Some("INSERT"),
3660            Self::Update { .. } => Some("UPDATE"),
3661            Self::Delete { .. } => Some("DELETE"),
3662            Self::Merge { .. } => Some("MERGE"),
3663            Self::Truncate { .. } => Some("TRUNCATE TABLE"),
3664            Self::CopyFromFile { .. } => Some("COPY FROM"),
3665
3666            // A SELECT that takes row locks writes lock state, and PG
3667            // names the strength it was asked for.
3668            Self::Select(sel) => sel.locking.as_ref().map(|l| match l.strength {
3669                LockStrength::Update => "SELECT FOR UPDATE",
3670                LockStrength::NoKeyUpdate => "SELECT FOR NO KEY UPDATE",
3671                LockStrength::Share => "SELECT FOR SHARE",
3672                LockStrength::KeyShare => "SELECT FOR KEY SHARE",
3673            }),
3674
3675            // ---- changes the catalog -----------------------------------
3676            Self::CreateTable { .. } => Some("CREATE TABLE"),
3677            Self::DropTable { .. } => Some("DROP TABLE"),
3678            Self::AlterTable { .. } => Some("ALTER TABLE"),
3679            Self::CreateIndex { .. } => Some("CREATE INDEX"),
3680            Self::DropIndex { .. } => Some("DROP INDEX"),
3681            Self::AlterIndex { .. } => Some("ALTER INDEX"),
3682            Self::CreateView { .. } => Some("CREATE VIEW"),
3683            Self::DropView { .. } => Some("DROP VIEW"),
3684            Self::CreateMaterializedView { .. } => Some("CREATE MATERIALIZED VIEW"),
3685            Self::RefreshMaterializedView { .. } => Some("REFRESH MATERIALIZED VIEW"),
3686            Self::DropMaterializedView { .. } => Some("DROP MATERIALIZED VIEW"),
3687            Self::CreateSequence { .. } => Some("CREATE SEQUENCE"),
3688            Self::AlterSequence { .. } => Some("ALTER SEQUENCE"),
3689            Self::DropSequence { .. } => Some("DROP SEQUENCE"),
3690            Self::CreateType { .. } => Some("CREATE TYPE"),
3691            Self::DropType { .. } => Some("DROP TYPE"),
3692            Self::AlterTypeAddValue { .. } | Self::AlterTypeRenameValue { .. } => {
3693                Some("ALTER TYPE")
3694            }
3695            Self::CreateDomain { .. } => Some("CREATE DOMAIN"),
3696            Self::AlterDomain { .. } => Some("ALTER DOMAIN"),
3697            Self::DropDomain { .. } => Some("DROP DOMAIN"),
3698            Self::CreateSchema { .. } => Some("CREATE SCHEMA"),
3699            Self::DropSchema { .. } => Some("DROP SCHEMA"),
3700            Self::CreateFunction { .. } => Some("CREATE FUNCTION"),
3701            Self::DropFunction { .. } => Some("DROP FUNCTION"),
3702            Self::CreateTrigger { .. } => Some("CREATE TRIGGER"),
3703            Self::DropTrigger { .. } => Some("DROP TRIGGER"),
3704            Self::CreateRule { .. } => Some("CREATE RULE"),
3705            Self::DropRule { .. } => Some("DROP RULE"),
3706            Self::CreateExtension { .. } => Some("CREATE EXTENSION"),
3707            Self::CreateStatistics { .. } => Some("CREATE STATISTICS"),
3708            Self::DropStatistics { .. } => Some("DROP STATISTICS"),
3709            Self::DropAggregate { .. } => Some("DROP AGGREGATE"),
3710            Self::CommentOn { .. } => Some("COMMENT"),
3711            Self::DropDatabase { .. } => Some("DROP DATABASE"),
3712            Self::CreatePublication { .. } => Some("CREATE PUBLICATION"),
3713            Self::DropPublication { .. } => Some("DROP PUBLICATION"),
3714            Self::CreateSubscription { .. } => Some("CREATE SUBSCRIPTION"),
3715            Self::DropSubscription { .. } => Some("DROP SUBSCRIPTION"),
3716
3717            // ---- changes roles / permissions ---------------------------
3718            Self::CreateUser { .. } => Some("CREATE ROLE"),
3719            Self::DropUser { .. } => Some("DROP ROLE"),
3720            Self::AlterRolePassword { .. } | Self::SetDbRoleSetting { .. } => Some("ALTER ROLE"),
3721            Self::Grant { .. } => Some("GRANT"),
3722            Self::Revoke { .. } => Some("REVOKE"),
3723            Self::CreatePolicy { .. } => Some("CREATE POLICY"),
3724            Self::AlterPolicy { .. } => Some("ALTER POLICY"),
3725            Self::DropPolicy { .. } => Some("DROP POLICY"),
3726            Self::AlterSystem { .. } => Some("ALTER SYSTEM"),
3727
3728            // ---- SPG's own writers -------------------------------------
3729            // Rewrites cold-tier segments on disk. PG has no equivalent to
3730            // ask, so the test is what it does, not what it is called.
3731            Self::CompactColdSegments => Some("COMPACT COLD SEGMENTS"),
3732
3733            // ---- allowed -----------------------------------------------
3734            // Reads, transaction control, session state, cursors, and the
3735            // maintenance statements PG itself permits. `REINDEX` really is
3736            // allowed in a read-only transaction (measured), which is why
3737            // `Maintain` is here.
3738            //
3739            // `Prepare`, `Execute`, `Call` and `DoBlock` are allowed at
3740            // this level for the reason PG allows them: the write inside
3741            // is refused when it runs, by this same check. Measured:
3742            // `PREPARE p AS INSERT …` succeeds; `DO $$ … INSERT … $$`
3743            // fails with `cannot execute INSERT`.
3744            Self::Explain { .. }
3745            | Self::CopyTo { .. }
3746            | Self::CopyToFile { .. }
3747            | Self::Analyze { .. }
3748            | Self::Maintain { .. }
3749            | Self::Vacuum { .. }
3750            | Self::Begin { .. }
3751            | Self::Commit
3752            | Self::Rollback
3753            | Self::Savepoint { .. }
3754            | Self::RollbackToSavepoint { .. }
3755            | Self::ReleaseSavepoint { .. }
3756            | Self::PrepareTransaction { .. }
3757            | Self::SetTransaction { .. }
3758            | Self::SetConstraints { .. }
3759            | Self::SetParameter { .. }
3760            | Self::SetParameterList { .. }
3761            | Self::SetUserVars { .. }
3762            | Self::SetRole { .. }
3763            | Self::ResetParameter { .. }
3764            | Self::ShowParameter { .. }
3765            | Self::Discard { .. }
3766            | Self::Prepare { .. }
3767            | Self::Execute { .. }
3768            | Self::Deallocate { .. }
3769            | Self::Call { .. }
3770            | Self::DoBlock { .. }
3771            | Self::DeclareCursor { .. }
3772            | Self::FetchCursor { .. }
3773            | Self::MoveCursor { .. }
3774            | Self::CloseCursor { .. }
3775            | Self::Listen { .. }
3776            | Self::Notify { .. }
3777            | Self::Unlisten { .. }
3778            | Self::Kill { .. }
3779            | Self::WaitForWalPosition { .. }
3780            | Self::ValidateOnly { .. }
3781            | Self::NoOpPreventedInTransaction { .. }
3782            | Self::Empty
3783            | Self::ShowTables
3784            | Self::ShowDatabases
3785            | Self::UseDatabase(_)
3786            | Self::ShowCreateTable { .. }
3787            | Self::ShowIndexes { .. }
3788            | Self::ShowStatus
3789            | Self::ShowVariables
3790            | Self::ShowVariablesLike { .. }
3791            | Self::ShowProcesslist
3792            | Self::ShowColumns { .. }
3793            | Self::ShowUsers
3794            | Self::ShowPublications
3795            | Self::ShowSubscriptions => None,
3796        }
3797    }
3798}
3799
3800#[derive(Debug, Clone, PartialEq, Eq)]
3801pub struct LockingClause {
3802    pub strength: LockStrength,
3803    /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3804    pub of_tables: Vec<String>,
3805    pub policy: LockWait,
3806}
3807
3808/// PG's four tuple-lock strengths, weakest first.
3809#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3810pub enum LockStrength {
3811    KeyShare,
3812    Share,
3813    NoKeyUpdate,
3814    Update,
3815}
3816
3817/// What to do when the row is already locked.
3818#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3819pub enum LockWait {
3820    /// Block until it is free — PG's default.
3821    #[default]
3822    Wait,
3823    /// `NOWAIT` — fail the statement with 55P03.
3824    NoWait,
3825    /// `SKIP LOCKED` — leave the row out of the result.
3826    SkipLocked,
3827}
3828
3829#[derive(Debug, Clone, PartialEq, Default)]
3830pub struct SelectStatement {
3831    /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3832    /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3833    /// whole syntax and locked nothing: two workers running the classic
3834    /// `SKIP LOCKED` queue take both took the same row.
3835    /// v7.39 (round 305) — boxed. A locking clause appears on a
3836    /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3837    /// cost every `SelectStatement` 32 bytes, and this struct sits in
3838    /// recursive evaluation frames where the engine already runs close to
3839    /// its stack budget (a 512 KB depth guard is the canary).
3840    pub locking: Option<alloc::boxed::Box<LockingClause>>,
3841    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3842    /// expressions, materialised once at query start before the
3843    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3844    /// only — no `WITH RECURSIVE` for v4.x.
3845    pub ctes: Vec<Cte>,
3846    pub distinct: bool,
3847    /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3848    /// keep the first row (per ORDER BY) of each group the
3849    /// expressions define. Empty = no DISTINCT ON.
3850    pub distinct_on: Vec<Expr>,
3851    pub items: Vec<SelectItem>,
3852    pub from: Option<FromClause>,
3853    pub where_: Option<Expr>,
3854    pub group_by: Option<Vec<Expr>>,
3855    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3856    /// expands `group_by` to every non-aggregate SELECT-list item
3857    /// before the executor runs. Mutually exclusive with an
3858    /// explicit `group_by` list (the parser sets exactly one).
3859    pub group_by_all: bool,
3860    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3861    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3862    /// aggregate executor resolves them through the same synthetic
3863    /// schema used for the SELECT items.
3864    pub having: Option<Expr>,
3865    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3866    /// itself a `SelectStatement` with `order_by = None` and `limit =
3867    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3868    /// top of the chain).
3869    pub unions: Vec<(UnionKind, SelectStatement)>,
3870    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3871    /// Keys are matched left-to-right: first key decides, ties break
3872    /// to the second, etc.
3873    pub order_by: Vec<OrderBy>,
3874    /// `LIMIT <n>` — bound on row output. `n` is an integer
3875    /// literal **or** (v7.9.24) a placeholder `$N` resolved
3876    /// against the prepared-statement Bind values. mailrs
3877    /// migration follow-up H2.
3878    pub limit: Option<LimitExpr>,
3879    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3880    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3881    pub offset: Option<LimitExpr>,
3882    /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3883    /// (SQL:2008). When true and an ORDER BY is present, the
3884    /// executor extends past the LIMIT-truncated tail to include
3885    /// every row whose ORDER BY key equals the last-kept row's
3886    /// key. Requires an ORDER BY; the executor errors otherwise
3887    /// (matching PG's `WITH TIES` rule). The parser was already
3888    /// accepting `WITH TIES` since Phase 5.1; this field captures
3889    /// the choice so the executor can act on it.
3890    pub limit_with_ties: bool,
3891    /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3892    /// that NOTHING referenced. PG analyses every definition whether
3893    /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3894    /// and silently succeeded here — the referenced ones get their columns
3895    /// resolved through the WindowFunction nodes they were inlined into,
3896    /// and the unreferenced ones used to be dropped at parse, unexamined.
3897    /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3898    ///
3899    /// Not part of `Display`: an unreferenced definition has no effect on
3900    /// the result, so a deparsed body (a stored view) omits it.
3901    pub window_check_exprs: Vec<Expr>,
3902}
3903
3904impl Expr {
3905    /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3906    /// directly inside this expression to `f`. `f` receives each nested
3907    /// statement once; descending further (into that statement's own
3908    /// clauses) is the caller's job, which keeps this walk finite and
3909    /// lets the caller order the recursion.
3910    ///
3911    /// The match is deliberately **wildcard-free**: a new `Expr` variant
3912    /// does not compile until it says whether it can carry a subquery.
3913    /// The row-count resolution pass is built on this, and a shape it
3914    /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3915    /// which every row-count reader would take as "no limit", i.e. the
3916    /// whole table. Compile-time exhaustiveness is what rules that out.
3917    /// Iterative on purpose. Expression trees here get deep (long
3918    /// boolean chains, big IN lists), and this walk is on the path of
3919    /// every statement; recursing would add a frame per node to a stack
3920    /// budget the engine already runs close to — a depth guard that runs
3921    /// on a deliberately small stack caught exactly that. Depth costs
3922    /// heap here instead.
3923    pub fn for_each_subquery_mut<E>(
3924        &mut self,
3925        f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3926    ) -> Result<(), E> {
3927        let mut stack: Vec<&mut Self> = alloc::vec![self];
3928        while let Some(e) = stack.pop() {
3929            match e {
3930                Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3931                Self::NamedArg { expr, .. }
3932                | Self::Collate { expr, .. }
3933                | Self::Variadic(expr)
3934                | Self::Unary { expr, .. }
3935                | Self::Cast { expr, .. }
3936                | Self::FieldAccess { base: expr, .. }
3937                | Self::IsNull { expr, .. }
3938                | Self::BoolTest { expr, .. }
3939                | Self::Extract { source: expr, .. } => stack.push(expr),
3940                Self::Binary { lhs, rhs, .. } => {
3941                    stack.push(lhs);
3942                    stack.push(rhs);
3943                }
3944                Self::Like { expr, pattern, .. } => {
3945                    stack.push(expr);
3946                    stack.push(pattern);
3947                }
3948                Self::ArraySubscript { target, index } => {
3949                    stack.push(target);
3950                    stack.push(index);
3951                }
3952                Self::ArraySlice { target, lo, hi } => {
3953                    stack.push(target);
3954                    stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
3955                }
3956                Self::AnyAll { expr, array, .. } => {
3957                    stack.push(expr);
3958                    stack.push(array);
3959                }
3960                Self::FunctionCall { args, .. } | Self::Array(args) => {
3961                    stack.extend(args.iter_mut());
3962                }
3963                Self::AggregateOrdered {
3964                    call,
3965                    order_by,
3966                    filter,
3967                    ..
3968                } => {
3969                    stack.push(call);
3970                    stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
3971                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3972                }
3973                Self::WindowFunction {
3974                    args,
3975                    partition_by,
3976                    order_by,
3977                    filter,
3978                    ..
3979                } => {
3980                    // `frame` bounds hold folded numbers / interval
3981                    // parts, never expressions — nothing to visit there.
3982                    stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
3983                    stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
3984                    stack.extend(filter.iter_mut().map(|b| &mut **b));
3985                }
3986                Self::InList { expr, list, .. } => {
3987                    stack.push(expr);
3988                    stack.extend(list.iter_mut());
3989                }
3990                Self::Case {
3991                    operand,
3992                    branches,
3993                    else_branch,
3994                } => {
3995                    stack.extend(
3996                        operand
3997                            .iter_mut()
3998                            .chain(else_branch.iter_mut())
3999                            .map(|b| &mut **b),
4000                    );
4001                    for (when, then) in branches.iter_mut() {
4002                        stack.push(when);
4003                        stack.push(then);
4004                    }
4005                }
4006                Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
4007                Self::InSubquery { expr, subquery, .. } => {
4008                    stack.push(expr);
4009                    f(subquery)?;
4010                }
4011                Self::RowInSubquery { row, subquery, .. }
4012                | Self::RowCmpSubquery { row, subquery, .. } => {
4013                    stack.extend(row.iter_mut());
4014                    f(subquery)?;
4015                }
4016            }
4017        }
4018        Ok(())
4019    }
4020}
4021
4022/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
4023/// time or a placeholder `$N` resolved during extended-query
4024/// Bind. mailrs migration follow-up H2.
4025///
4026/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
4027/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
4028/// made the compiler point at every site that used to duplicate a
4029/// row-count out of the AST, which is exactly the set that must not
4030/// bypass the resolution pre-pass.
4031#[derive(Debug, Clone, PartialEq)]
4032pub enum LimitExpr {
4033    /// `LIMIT 10` — value known at parse time.
4034    Literal(u32),
4035    /// `LIMIT $N` — the 1-based parameter index, resolved against
4036    /// the bind values when the prepared statement executes.
4037    Placeholder(u16),
4038    /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
4039    /// greatest(2,3)`: a row-count expression that isn't constant, so
4040    /// it can't be folded at parse time. Evaluated once, before
4041    /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
4042    /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
4043    /// "no limit"). **No execution path may see this variant** —
4044    /// `as_literal` would report `None`, which every row-count reader
4045    /// takes to mean "unlimited", i.e. the whole table.
4046    Expr(alloc::boxed::Box<Expr>),
4047}
4048
4049impl fmt::Display for LimitExpr {
4050    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4051        match self {
4052            Self::Literal(n) => write!(f, "{n}"),
4053            Self::Placeholder(n) => write!(f, "${n}"),
4054            // Parenthesised so the round-trip text re-parses as one
4055            // row-count expression (`LIMIT (SELECT 4)`), which is also
4056            // the only spelling `FETCH FIRST` accepts.
4057            Self::Expr(e) => write!(f, "({e})"),
4058        }
4059    }
4060}
4061
4062impl LimitExpr {
4063    /// Convenience for the simple-query path where no placeholders
4064    /// can possibly exist. Returns the literal value or `None` if
4065    /// this is a placeholder (caller must surface as Unsupported).
4066    ///
4067    /// v7.39 (round 305) — `None` is read by every row-count consumer as
4068    /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
4069    /// therefore silently return the whole table, so the engine's
4070    /// `resolve_limit_exprs` pre-pass rewrites the variant away before
4071    /// dispatch. The assertion makes a missed nesting site fail loudly
4072    /// in every test build rather than quietly widening a result set.
4073    #[must_use]
4074    pub fn as_literal(&self) -> Option<u32> {
4075        match self {
4076            Self::Literal(n) => Some(*n),
4077            Self::Placeholder(_) => None,
4078            Self::Expr(_) => {
4079                debug_assert!(
4080                    false,
4081                    "LimitExpr::Expr reached execution — resolve_limit_exprs \
4082                     missed a nesting site; treating it as `no limit` would \
4083                     return every row"
4084                );
4085                None
4086            }
4087        }
4088    }
4089}
4090
4091/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
4092/// the engine's `substitute_placeholders` pass these are
4093/// always Literal; in the simple-query path a Placeholder
4094/// shape returns None (executor surfaces as
4095/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
4096impl SelectStatement {
4097    #[must_use]
4098    pub fn limit_literal(&self) -> Option<u32> {
4099        self.limit.as_ref().and_then(LimitExpr::as_literal)
4100    }
4101    #[must_use]
4102    pub fn offset_literal(&self) -> Option<u32> {
4103        self.offset.as_ref().and_then(LimitExpr::as_literal)
4104    }
4105}
4106
4107#[derive(Debug, Clone, PartialEq)]
4108pub struct Cte {
4109    pub name: String,
4110    /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
4111    /// classical case) or a data-modifying statement
4112    /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
4113    /// CTE semantics. The modifying body's RETURNING projection
4114    /// becomes the materialised CTE table the outer query can
4115    /// reference; the modifying statement runs once before the
4116    /// outer query, within the same transaction.
4117    pub body: CteBody,
4118    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
4119    /// RECURSIVE keyword. Applies to every CTE in the clause per
4120    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
4121    /// allowed; the engine just runs it once.
4122    pub recursive: bool,
4123    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
4124    /// non-empty, these override the body's output column names
4125    /// position-by-position; the engine errors out if the count
4126    /// doesn't match the body's projection width.
4127    pub column_overrides: Vec<String>,
4128    /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
4129    /// SET seqcol` on a recursive CTE. Desugared at parse time into an
4130    /// extra ordering column on the body (see `rewrite_search_and_cycle`).
4131    pub search: Option<SearchClause>,
4132    /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
4133    /// USING pathcol` cycle detection, desugared at parse time.
4134    pub cycle: Option<CycleClause>,
4135}
4136
4137/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
4138#[derive(Debug, Clone, PartialEq)]
4139pub struct SearchClause {
4140    /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
4141    pub depth_first: bool,
4142    /// The CTE output columns the search orders by.
4143    pub by_columns: Vec<String>,
4144    /// The new column holding the ordering key (a row-array for depth,
4145    /// a `(depth, keys…)` row for breadth).
4146    pub set_column: String,
4147}
4148
4149/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
4150#[derive(Debug, Clone, PartialEq)]
4151pub struct CycleClause {
4152    /// Columns whose repetition along a path marks a cycle.
4153    pub columns: Vec<String>,
4154    /// The new boolean-ish column set to `mark_value` on a cycle.
4155    pub mark_column: String,
4156    /// Value written to `mark_column` when a cycle is detected (default
4157    /// `true`); `default_value` otherwise. PG allows any type; SPG carries
4158    /// them as literals.
4159    pub mark_value: Option<Literal>,
4160    pub default_value: Option<Literal>,
4161    /// The new column accumulating the visited-row path array.
4162    pub path_column: String,
4163}
4164
4165/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
4166/// (Insert / Update / Delete with optional RETURNING). The
4167/// data-modifying variants must carry a RETURNING projection for the
4168/// outer query to reference the CTE alias by; an empty RETURNING is
4169/// only valid if no outer reference materialises (rare — typically
4170/// caught at planning).
4171#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
4172#[derive(Debug, Clone, PartialEq)]
4173pub enum CteBody {
4174    Select(SelectStatement),
4175    Insert(Box<InsertStatement>),
4176    Update(Box<UpdateStatement>),
4177    Delete(Box<DeleteStatement>),
4178    /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
4179    /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
4180    Merge(Box<MergeStatement>),
4181}
4182
4183impl CteBody {
4184    /// Convenience accessor used by classical (read-only) CTE
4185    /// callsites that still expect a SELECT body. Returns None for
4186    /// data-modifying CTEs; callers must explicitly route those
4187    /// through `exec_with_ctes`'s modifying branch.
4188    #[must_use]
4189    pub fn as_select(&self) -> Option<&SelectStatement> {
4190        match self {
4191            Self::Select(s) => Some(s),
4192            _ => None,
4193        }
4194    }
4195
4196    #[must_use]
4197    pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
4198        match self {
4199            Self::Select(s) => Some(s),
4200            _ => None,
4201        }
4202    }
4203
4204    #[must_use]
4205    pub fn is_modifying(&self) -> bool {
4206        !matches!(self, Self::Select(_))
4207    }
4208}
4209
4210#[derive(Debug, Clone, PartialEq)]
4211pub struct OrderBy {
4212    pub expr: Expr,
4213    /// `false` = ASC (default), `true` = DESC.
4214    pub desc: bool,
4215    /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
4216    /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
4217    /// NULLS FIRST for DESC); the engine resolves the effective
4218    /// value via `nulls_first.unwrap_or(desc)`.
4219    pub nulls_first: Option<bool>,
4220    /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
4221    /// It lives here rather than in the expression for the same reason
4222    /// `desc` does: at an ORDER BY key a collation is ordering
4223    /// information, and nothing downstream of the sort needs it. A new
4224    /// `Expr` variant would instead put a new arm on `eval_expr`, which
4225    /// this repo has measured to overflow the debug stack.
4226    ///
4227    /// `None` means none was written, and the key falls back to whatever
4228    /// its COLUMN declares — which is every key that existed before this.
4229    pub collation: Option<String>,
4230}
4231
4232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4233pub enum UnionKind {
4234    /// `UNION` — dedupes the combined set.
4235    Distinct,
4236    /// `UNION ALL` — concatenates without dedup.
4237    All,
4238    /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
4239    /// present on both sides.
4240    Intersect,
4241    /// `INTERSECT ALL` — multiset intersection (min per-row count).
4242    IntersectAll,
4243    /// `EXCEPT` — distinct left rows absent from the right.
4244    Except,
4245    /// `EXCEPT ALL` — multiset subtraction.
4246    ExceptAll,
4247}
4248
4249#[derive(Debug, Clone, PartialEq)]
4250pub enum SelectItem {
4251    Wildcard,
4252    /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
4253    /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
4254    /// `NEW` pseudo-relation).
4255    QualifiedWildcard(String),
4256    Expr {
4257        expr: Expr,
4258        alias: Option<String>,
4259    },
4260}
4261
4262#[derive(Debug, Clone, PartialEq)]
4263pub struct TableRef {
4264    pub name: String,
4265    pub alias: Option<String>,
4266    /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
4267    /// children.
4268    ///
4269    /// The keyword used to be absorbed at parse time, on the reasoning
4270    /// that SPG's inheritance children are separate relations a plain
4271    /// scan does not descend into — so ONLY already described what the
4272    /// scan did. That stopped being true when a partition parent
4273    /// started unioning its children: measured, `SELECT count(*) FROM
4274    /// ONLY <partitioned parent>` answered 2 where PG answers 0.
4275    pub only: bool,
4276    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
4277    /// When `Some(id)`, the scan restricts to rows that live in
4278    /// segment `<id>` only — useful for forensic inspection of a
4279    /// specific freezer-emitted segment without exposing the hot
4280    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
4281    /// is STABILITY carve-out for v6.10 — needs the freezer to
4282    /// stamp each segment with a wall-clock at creation time.
4283    pub as_of_segment: Option<u32>,
4284    /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
4285    /// source. When `Some`, `name` is the alias (defaulting to
4286    /// `"unnest"` when no `AS` is given) and the engine builds a
4287    /// synthetic single-column table by evaluating the expression
4288    /// once at SELECT entry. Each TEXT[] element becomes one row;
4289    /// NULL elements become NULL cells. v7.11 supported
4290    /// uncorrelated UNNEST only as the FROM primary; v7.13.2
4291    /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
4292    /// position (cross-join with regular tables).
4293    pub unnest_expr: Option<Box<Expr>>,
4294    /// v7.13.2 — mailrs round-6 S5. PG-standard
4295    /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
4296    /// when non-empty, the first entry overrides the projected
4297    /// column name for the unnested column. Empty = fall back to
4298    /// the table alias (pre-v7.13.2 behaviour).
4299    pub unnest_column_aliases: Vec<String>,
4300    /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
4301    /// row-stream gains a trailing BIGINT column counting rows
4302    /// from 1 in element order. PG names it `ordinality`; a second
4303    /// entry in the column-alias list renames it.
4304    pub with_ordinality: bool,
4305    /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
4306    /// [, step])` set-returning source. When `Some`, the engine
4307    /// materialises a single-column virtual table by stepping
4308    /// `start` to `stop` inclusive. Args are the literal arg list
4309    /// (2 for default-step, 3 for explicit-step). Supports:
4310    ///   * SmallInt / Int / BigInt with integer step (default = 1)
4311    ///   * Timestamp with INTERVAL step (PG date-range pattern)
4312    /// Mutually exclusive with `unnest_expr` — both populate the
4313    /// same downstream dispatch slot. `name` defaults to
4314    /// `"generate_series"` when no alias is provided.
4315    pub generate_series_args: Option<Vec<Expr>>,
4316    /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
4317    /// table. When `Some`, the TableRef is a parenthesised SELECT
4318    /// that may reference columns from the preceding FROM items
4319    /// (correlated derived table). The executor materialises the
4320    /// subquery per left-row, substituting outer-column references
4321    /// against the current join row's values before running the
4322    /// inner SELECT, then cross-joins the result back.
4323    /// Mutually exclusive with `name` / `unnest_expr` /
4324    /// `generate_series_args`.
4325    pub lateral_subquery: Option<Box<SelectStatement>>,
4326    /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
4327    /// function as a FROM item. PG semantics: for each key/value
4328    /// pair in the JSONB object argument, emit one (key TEXT,
4329    /// value TEXT) row. When prefixed by `LATERAL` and joined via
4330    /// `CROSS JOIN LATERAL`, the argument may reference columns
4331    /// from a preceding FROM item, in which case the executor
4332    /// evaluates `<expr>` per outer row.
4333    /// Mutually exclusive with `unnest_expr` / `generate_series_args`
4334    /// / `lateral_subquery`. The optional `LATERAL` keyword does not
4335    /// require a separate flag — the executor evaluates per-row
4336    /// whenever the join sits in a JoinKind context.
4337    ///
4338    /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
4339    /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
4340    /// `json_each` / `json_each_text`) so the executor picks the
4341    /// value-column rendering (JSON text vs unwrapped text).
4342    pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
4343    /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
4344    /// function channel: `(lowercase fn name, args)`. Carries
4345    /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
4346    /// dispatches by name.
4347    pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
4348    /// v7.39 (read01 round 78) — this FROM item is a call to a function that
4349    /// returns a BASE type, so the item's row type IS that scalar: a whole-row
4350    /// reference to it yields the value, not a one-field composite
4351    /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
4352    /// desugared shape is indistinguishable from a hand-written
4353    /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
4354    /// only the parser knows which one it built, so it says so here.
4355    pub scalar_fn_item: bool,
4356    /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
4357    /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
4358    /// target-list SRFs follow — see round 67). The array-returning family keeps
4359    /// its own lowering; this channel carries the ones that have no array form
4360    /// (`generate_series`, a user `RETURNS SETOF` function).
4361    pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
4362    /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4363    /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4364    /// tables (implicit LATERAL, like every SRF channel). Executed by
4365    /// walking the row path over the parsed doc, then each column's
4366    /// path per row-item; NESTED expands as a per-parent outer join.
4367    pub json_table: Option<Box<JsonTable>>,
4368}
4369
4370/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4371#[derive(Debug, Clone, PartialEq)]
4372pub struct JsonTable {
4373    /// The document expression (jsonb/json/text). May reference outer
4374    /// columns → implicit LATERAL.
4375    pub doc: Box<Expr>,
4376    /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4377    /// match is one row's context item.
4378    pub row_path: String,
4379    /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4380    pub columns: Vec<JsonTableColumn>,
4381    /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4382    pub passing: Vec<(String, Expr)>,
4383}
4384
4385/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4386#[derive(Debug, Clone, PartialEq)]
4387pub enum JsonTableColumn {
4388    /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4389    Ordinality { name: String },
4390    /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4391    /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4392    /// `<name> <type> EXISTS [PATH '<p>']`.
4393    Regular {
4394        name: String,
4395        ty: ColumnTypeName,
4396        /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4397        path: String,
4398        /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4399        exists: bool,
4400        /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4401        format_json: bool,
4402        /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4403        wrapper: bool,
4404        /// Behaviour when the path matches nothing (default NULL).
4405        on_empty: JsonTableOnBehavior,
4406        /// Behaviour when coercion fails (default NULL).
4407        on_error: JsonTableOnBehavior,
4408    },
4409    /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4410    /// row like a LEFT JOIN (a parent with no nested match still emits one
4411    /// row, nested cols NULL).
4412    Nested {
4413        path: String,
4414        columns: Vec<JsonTableColumn>,
4415    },
4416}
4417
4418/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4419#[derive(Debug, Clone, PartialEq)]
4420pub enum JsonTableOnBehavior {
4421    /// Default: the column value is NULL.
4422    Null,
4423    /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4424    Error,
4425    /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4426    Default(Box<Expr>),
4427}
4428
4429/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4430/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4431/// joins evaluate left-associatively in nested-loop order.
4432#[derive(Debug, Clone, PartialEq)]
4433pub struct FromClause {
4434    pub primary: TableRef,
4435    pub joins: Vec<FromJoin>,
4436}
4437
4438#[derive(Debug, Clone, PartialEq)]
4439pub struct FromJoin {
4440    pub kind: JoinKind,
4441    pub table: TableRef,
4442    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4443    pub on: Option<Expr>,
4444    /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4445    /// USING column list so the executor can perform PG's column-merge
4446    /// (the join columns collapse to a single unqualified output column,
4447    /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4448    /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4449    /// USING into an equivalent `on` predicate so the join filter/count
4450    /// path works unchanged; `using_cols` drives only the output-shape
4451    /// rewrite. Empty/`None` for `ON` and CROSS joins.
4452    pub using_cols: Option<Vec<String>>,
4453    /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4454    /// column names are not known until the table schemas are available
4455    /// (parse time is schema-less), so the parser only sets this flag and
4456    /// leaves `on`/`using_cols` empty; the engine resolves the common
4457    /// columns at execution time, synthesises the `on` predicate + the
4458    /// USING column-merge, and clears the flag. If there are no common
4459    /// columns PG treats it as a CROSS join.
4460    pub natural: bool,
4461}
4462
4463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4464pub enum JoinKind {
4465    Inner,
4466    Left,
4467    Cross,
4468    /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4469    /// NULL-filling the left (drive) columns on unmatched right rows.
4470    /// The executor runs the LEFT algorithm's mirror: it tracks which
4471    /// peer rows matched and emits the unmatched ones with a NULL-left
4472    /// tuple after the probe loop. Output column order is unchanged
4473    /// (left-table cols then right-table cols).
4474    Right,
4475    /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4476    /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4477    FullOuter,
4478    /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4479    /// once, paired with the first peer row that satisfies the ON. Not
4480    /// reachable from SQL — the EXISTS pull-up emits it, which is what
4481    /// frees positive EXISTS from the round-721 uniqueness gate (an
4482    /// INNER join would multiply the outer rows; a semi join cannot).
4483    Semi,
4484}
4485
4486#[derive(Debug, Clone, PartialEq)]
4487pub enum Expr {
4488    Literal(Literal),
4489    /// v7.39.2 — `<expr> COLLATE <name>`: the collation this expression
4490    /// compares under, whatever the column or the database says.
4491    ///
4492    /// The parser used to refuse the locale names in this position and
4493    /// SILENTLY ABSORB the byte-order ones, so `'a' COLLATE "C" < 'B'`
4494    /// answered `t` where PostgreSQL 18.6 answers `f` — the one family
4495    /// it let through is the one where dropping it changes the answer.
4496    ///
4497    /// Whether dropping is safe depends on the DATABASE's own collation,
4498    /// which the parser cannot see: under `SPG_LC_COLLATE=C` absorbing
4499    /// `COLLATE "C"` is exactly right. So the name rides along and the
4500    /// engine, which knows, decides.
4501    Collate {
4502        expr: Box<Expr>,
4503        collation: String,
4504    },
4505    Column(ColumnName),
4506    /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4507    /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4508    /// callee's declared parameter names, and a user function's live in the
4509    /// catalog — which the parser cannot see. So the name rides along in the
4510    /// tree and the evaluator, which has the catalog, does the reordering.
4511    /// Appears only inside a `FunctionCall`'s argument list.
4512    NamedArg {
4513        name: String,
4514        expr: Box<Expr>,
4515    },
4516    /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4517    /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4518    /// expression evaluates to an array whose elements the evaluator splices
4519    /// into the call as individual trailing arguments. Appears only inside a
4520    /// `FunctionCall`'s argument list.
4521    Variadic(Box<Expr>),
4522    /// v6.1.1 — `$N` parameter placeholder for the extended query
4523    /// protocol. The number is 1-based per PostgreSQL convention.
4524    /// Evaluation looks up `params[N-1]` from the prepared-statement
4525    /// bind buffer; out-of-range indices raise a runtime error
4526    /// (same shape as a column-not-found miss).
4527    Placeholder(u16),
4528    Binary {
4529        lhs: Box<Expr>,
4530        op: BinOp,
4531        rhs: Box<Expr>,
4532    },
4533    Unary {
4534        op: UnOp,
4535        expr: Box<Expr>,
4536    },
4537    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4538    /// TEXT, BOOL targets; engine coerces at evaluation time.
4539    Cast {
4540        expr: Box<Expr>,
4541        target: CastTarget,
4542    },
4543    /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4544    /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4545    /// whole-row reference, or a composite-returning function); `field` names
4546    /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4547    /// column names for a whole-row). Only the parenthesised form reaches
4548    /// here — a bare `a.b` is parsed as a qualified column reference.
4549    FieldAccess {
4550        base: Box<Expr>,
4551        field: String,
4552    },
4553    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4554    IsNull {
4555        expr: Box<Expr>,
4556        negated: bool,
4557    },
4558    /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4559    /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4560    /// `Some(false)` for FALSE and `None` for UNKNOWN.
4561    ///
4562    /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4563    /// The semantics were right, but the AST then had no way to say what
4564    /// the user wrote, so every renderer printed the lowering:
4565    /// `CHECK ((a > 1) IS TRUE)` came back as
4566    /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4567    /// dumped view lost the form too.
4568    BoolTest {
4569        expr: Box<Expr>,
4570        value: Option<bool>,
4571        negated: bool,
4572    },
4573    /// Function call `name(args...)`. v1.4 supports a small built-in set
4574    /// (length, upper, lower, abs, coalesce); unknown names error at eval
4575    /// time so the parser stays open for v1.5 aggregates.
4576    FunctionCall {
4577        name: String,
4578        args: Vec<Expr>,
4579    },
4580    /// v7.24 (mailrs round-16 A) — an aggregate call with an
4581    /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4582    /// Wraps the plain [`Expr::FunctionCall`] so every existing
4583    /// FunctionCall consumer stays untouched; only the aggregate
4584    /// executor (and the expression walkers) know the wrapper.
4585    /// Non-aggregate evaluation contexts reject it at eval time.
4586    AggregateOrdered {
4587        call: Box<Expr>,
4588        order_by: Vec<OrderBy>,
4589        /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4590        /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4591        /// aggregate modifier so plain FunctionCall stays untouched.
4592        distinct: bool,
4593        /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4594        /// Only the rows where `cond` is true contribute to this
4595        /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4596        /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4597        /// END)`, which is faithful for NULL-ignoring aggregates but
4598        /// WRONG for `array_agg` (it would collect a NULL per excluded
4599        /// row). The executor instead skips excluded rows before
4600        /// accumulation, which is correct for every aggregate.
4601        filter: Option<Box<Expr>>,
4602    },
4603    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4604    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4605    /// the next char (so `\%` matches a literal `%`).
4606    Like {
4607        expr: Box<Expr>,
4608        pattern: Box<Expr>,
4609        negated: bool,
4610        /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4611        /// match. PG folds both operands.
4612        case_insensitive: bool,
4613    },
4614    /// v4.12 window function call: `name(args) OVER (PARTITION BY
4615    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4616    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4617    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4618    /// unordered windows and "from start of partition through
4619    /// current row" for ordered windows — no explicit ROWS /
4620    /// RANGE clause in v4.12 MVP.
4621    WindowFunction {
4622        name: String,
4623        args: Vec<Expr>,
4624        partition_by: Vec<Expr>,
4625        /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4626        /// (None = PG default, same contract as [`OrderBy`]).
4627        order_by: Vec<(
4628            Expr,
4629            bool,         /* desc */
4630            Option<bool>, /* nulls_first */
4631        )>,
4632        /// v4.20 explicit frame. `None` means "use the default":
4633        /// whole-partition when unordered, running aggregate from
4634        /// partition start through current row when ordered.
4635        frame: Option<WindowFrame>,
4636        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4637        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4638        /// `Respect` (PG / ANSI default — NULLs participate). Other
4639        /// window functions ignore this flag.
4640        null_treatment: NullTreatment,
4641        /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4642        /// = no FILTER. Only aggregate window functions honor it; the
4643        /// predicate restricts which peer rows contribute within the frame.
4644        filter: Option<Box<Expr>>,
4645    },
4646    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4647    /// position. Must return exactly one row × one column at eval
4648    /// time; the engine errors out otherwise. Uncorrelated only —
4649    /// the inner SELECT cannot reference outer columns.
4650    ScalarSubquery(Box<SelectStatement>),
4651    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4652    /// projection is ignored; only row-count matters.
4653    Exists {
4654        subquery: Box<SelectStatement>,
4655        negated: bool,
4656    },
4657    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4658    /// project exactly one column; membership is tested by Eq
4659    /// against each row's value (NULL handling follows ANSI:
4660    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4661    InSubquery {
4662        expr: Box<Expr>,
4663        subquery: Box<SelectStatement>,
4664        negated: bool,
4665    },
4666    /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4667    /// against a multi-column subquery. Row comparisons against a *list*
4668    /// decompose to OR-of-AND at parse time, but the subquery form can't
4669    /// (its rows are only known at runtime), so this survives as its own
4670    /// node evaluated with PG's row-comparison three-valued logic.
4671    RowInSubquery {
4672        row: Vec<Expr>,
4673        subquery: Box<SelectStatement>,
4674        negated: bool,
4675    },
4676    /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4677    /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4678    /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4679    /// subquery form can't, so it survives as its own node. The subquery
4680    /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4681    RowCmpSubquery {
4682        row: Vec<Expr>,
4683        op: BinOp,
4684        subquery: Box<SelectStatement>,
4685    },
4686    /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4687    /// list. Both the parser's literal-list path and the engine's
4688    /// IN-subquery materialisation used to desugar into a left-deep
4689    /// OR-Eq chain, so expression depth scaled with the element count
4690    /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4691    /// (recursive eval AND recursive Box drop) and aborted embedding
4692    /// host processes. The flat node keeps depth constant: eval is an
4693    /// iterative scan with PG three-valued logic, drop is a Vec drop.
4694    InList {
4695        expr: Box<Expr>,
4696        list: Vec<Expr>,
4697        negated: bool,
4698    },
4699    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4700    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4701    /// because the `FROM` keyword is what separates the two halves,
4702    /// not a comma.
4703    Extract {
4704        field: ExtractField,
4705        source: Box<Expr>,
4706    },
4707    /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4708    /// element is evaluated independently; NULLs are allowed.
4709    /// v7.10 supports only single-dimension TEXT[] semantically;
4710    /// non-text elements coerce at engine evaluation time when
4711    /// the surrounding context (column type / cast) makes the
4712    /// target clear.
4713    Array(Vec<Expr>),
4714    /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4715    /// engine returns NULL for out-of-range indices.
4716    ArraySubscript {
4717        target: Box<Expr>,
4718        index: Box<Expr>,
4719    },
4720    /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4721    /// inclusive; a missing bound extends to that end of the
4722    /// array and out-of-range bounds clamp. Returns an array of
4723    /// the same element type.
4724    ArraySlice {
4725        target: Box<Expr>,
4726        lo: Option<Box<Expr>>,
4727        hi: Option<Box<Expr>>,
4728    },
4729    /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4730    /// operator is the comparison binary op (Eq / Ne / Lt / …);
4731    /// the engine desugars: `ANY` returns true if any element
4732    /// satisfies; `ALL` returns true only if every element does.
4733    /// NULL handling follows PG's three-valued logic.
4734    AnyAll {
4735        expr: Box<Expr>,
4736        op: BinOp,
4737        array: Box<Expr>,
4738        /// `true` = ANY, `false` = ALL.
4739        is_any: bool,
4740    },
4741    /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4742    /// (searched form, `operand` is None) and
4743    /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4744    /// `operand` is the lead expression compared against each
4745    /// branch's match). Each `(when_expr, then_expr)` branch
4746    /// stays as written; engine short-circuits on the first match.
4747    /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4748    /// mailrs round-5 G9.
4749    Case {
4750        operand: Option<Box<Expr>>,
4751        branches: Vec<(Expr, Expr)>,
4752        else_branch: Option<Box<Expr>>,
4753    },
4754}
4755
4756/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4757/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4758/// in the offset walk. `Ignore` causes the function to skip NULL
4759/// values in the argument expression, returning the next non-NULL.
4760#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4761pub enum NullTreatment {
4762    #[default]
4763    Respect,
4764    Ignore,
4765}
4766
4767/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4768/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4769/// where end implicitly = CURRENT ROW.
4770#[derive(Debug, Clone, PartialEq, Eq)]
4771pub struct WindowFrame {
4772    pub kind: FrameKind,
4773    pub start: FrameBound,
4774    pub end: Option<FrameBound>,
4775    /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4776    /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4777    /// no-op; CURRENT ROW drops the current row from the frame.
4778    pub exclude: FrameExclusion,
4779}
4780
4781#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4782pub enum FrameExclusion {
4783    /// Default — exclude nothing.
4784    #[default]
4785    NoOthers,
4786    /// Drop the current row from the frame.
4787    CurrentRow,
4788    /// Drop the current row's whole peer group.
4789    Group,
4790    /// Drop the current row's peers but keep the current row.
4791    Ties,
4792}
4793
4794#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4795pub enum FrameKind {
4796    Rows,
4797    Range,
4798    /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4799    /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4800    /// bounds (no explicit integer offsets) GROUPS behaves identically
4801    /// to RANGE — both consult the peer-group of the current row.
4802    /// Integer offsets are not yet supported; the executor rejects
4803    /// them at run time.
4804    Groups,
4805}
4806
4807#[derive(Debug, Clone, PartialEq, Eq)]
4808pub enum FrameBound {
4809    UnboundedPreceding,
4810    OffsetPreceding(u64),
4811    CurrentRow,
4812    OffsetFollowing(u64),
4813    UnboundedFollowing,
4814    /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4815    /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4816    /// interval is folded to its (months, days, micros) components at
4817    /// parse time.
4818    IntervalPreceding {
4819        months: i32,
4820        days: i32,
4821        micros: i64,
4822    },
4823    IntervalFollowing {
4824        months: i32,
4825        days: i32,
4826        micros: i64,
4827    },
4828}
4829
4830impl fmt::Display for FrameBound {
4831    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4832        match self {
4833            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4834            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4835            Self::CurrentRow => f.write_str("CURRENT ROW"),
4836            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4837            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4838            Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4839            Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4840        }
4841    }
4842}
4843
4844#[derive(Debug, Clone, PartialEq, Eq)]
4845pub enum ExtractField {
4846    Year,
4847    Month,
4848    Day,
4849    Hour,
4850    Minute,
4851    Second,
4852    Microsecond,
4853    /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4854    /// SPG keeps the integer convention — truncated seconds).
4855    Epoch,
4856    /// Day of week, 0 = Sunday … 6 = Saturday.
4857    Dow,
4858    /// ISO day of week, 1 = Monday … 7 = Sunday.
4859    Isodow,
4860    /// Day of year, 1-366.
4861    Doy,
4862    /// ISO 8601 week number, 1-53.
4863    Week,
4864    /// ISO 8601 week-numbering year (pairs with `Week`).
4865    Isoyear,
4866    /// Quarter, 1-4.
4867    Quarter,
4868    /// Year divided by 10 (floor).
4869    Decade,
4870    /// Century — 2001-2100 is century 21.
4871    Century,
4872    /// Millennium — 2001-3000 is millennium 3.
4873    Millennium,
4874    /// Julian day number (truncated for timestamps).
4875    Julian,
4876    /// Seconds and fraction in milliseconds (ss·1000 + frac).
4877    Millisecond,
4878    /// UTC offset in seconds — SPG sessions run UTC, so 0.
4879    Timezone,
4880    /// Hour component of the UTC offset — 0.
4881    TimezoneHour,
4882    /// Minute component of the UTC offset — 0.
4883    TimezoneMinute,
4884    /// v7.39 (round 253) — a field name the parser does not know. PG
4885    /// resolves EXTRACT fields at RUNTIME and reports them with the
4886    /// source type (`unit "nosuch" not recognized for type timestamp
4887    /// without time zone`, 22023), so the parser carries the raw name
4888    /// instead of rejecting.
4889    Other(String),
4890}
4891
4892impl fmt::Display for ExtractField {
4893    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4894        f.write_str(match self {
4895            Self::Year => "YEAR",
4896            Self::Month => "MONTH",
4897            Self::Day => "DAY",
4898            Self::Hour => "HOUR",
4899            Self::Minute => "MINUTE",
4900            Self::Second => "SECOND",
4901            Self::Microsecond => "MICROSECOND",
4902            Self::Epoch => "EPOCH",
4903            Self::Dow => "DOW",
4904            Self::Isodow => "ISODOW",
4905            Self::Doy => "DOY",
4906            Self::Week => "WEEK",
4907            Self::Isoyear => "ISOYEAR",
4908            Self::Quarter => "QUARTER",
4909            Self::Decade => "DECADE",
4910            Self::Century => "CENTURY",
4911            Self::Millennium => "MILLENNIUM",
4912            Self::Julian => "JULIAN",
4913            Self::Millisecond => "MILLISECOND",
4914            Self::Timezone => "TIMEZONE",
4915            Self::TimezoneHour => "TIMEZONE_HOUR",
4916            Self::TimezoneMinute => "TIMEZONE_MINUTE",
4917            Self::Other(name) => return f.write_str(name),
4918        })
4919    }
4920}
4921
4922#[derive(Debug, Clone, PartialEq, Eq)]
4923pub enum CastTarget {
4924    Int,
4925    BigInt,
4926    Float,
4927    Text,
4928    Bool,
4929    Vector,
4930    Date,
4931    Timestamp,
4932    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4933    /// H3a. Engine reuses the existing runtime-interval / timestamp
4934    /// paths (parse the text input, return the matching Value).
4935    Interval,
4936    Timestamptz,
4937    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4938    /// types (v7.9.0); the cast just routes Text→Json with the
4939    /// requested OID for the wire layer.
4940    Json,
4941    Jsonb,
4942    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4943    /// compatibility; engine surfaces as Unsupported with a
4944    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4945    RegType,
4946    RegClass,
4947    /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
4948    /// the PG external array form `{a,b,NULL}`.
4949    TextArray,
4950    /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
4951    /// `{1,2,3}` or widens a `TextArray` whose elements are
4952    /// integer-shaped.
4953    IntArray,
4954    BigIntArray,
4955    /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
4956    /// external form text representation. Used by pg_dump output
4957    /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
4958    TsVector,
4959    TsQuery,
4960    /// v7.17.0 — `::uuid`. Decodes the LHS Text via
4961    /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
4962    /// unhyphenated, uppercase, and brace-wrapped forms); malformed
4963    /// input is a SQL error.
4964    Uuid,
4965    /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
4966    /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
4967    /// inputs pass through unchanged. Closes the mailrs D-pre #3
4968    /// reverse-acceptance gap — anywhere a PG schema writes
4969    /// `expr::bytea`, SPG now matches.
4970    Bytea,
4971    /// v7.37.5 ship triage — generic cast target for the long tail
4972    /// of PG type names the parser meets in `expr::TYPE` shapes that
4973    /// don't deserve their own enum variant. The engine routes these
4974    /// through `column_type_to_data_type` + the existing typed
4975    /// `coerce_value` dispatch, so adding a new PG type to SPG
4976    /// implicitly adds its cast-target form too — no parser change
4977    /// per type. The string carries the lowercase PG type ident
4978    /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
4979    /// a clear message when the type isn't known.
4980    Named(String),
4981}
4982
4983impl fmt::Display for CastTarget {
4984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4985        f.write_str(match self {
4986            Self::Int => "int",
4987            Self::BigInt => "bigint",
4988            Self::Float => "float",
4989            Self::Text => "text",
4990            Self::Bool => "bool",
4991            Self::Vector => "vector",
4992            Self::Interval => "interval",
4993            Self::Timestamptz => "timestamptz",
4994            Self::Json => "json",
4995            Self::Jsonb => "jsonb",
4996            Self::RegType => "regtype",
4997            Self::RegClass => "regclass",
4998            Self::Date => "date",
4999            Self::Timestamp => "timestamp",
5000            Self::TextArray => "TEXT[]",
5001            Self::IntArray => "INT[]",
5002            Self::BigIntArray => "BIGINT[]",
5003            Self::TsVector => "tsvector",
5004            Self::TsQuery => "tsquery",
5005            Self::Uuid => "uuid",
5006            Self::Bytea => "bytea",
5007            // v7.37.5 — `Self::Named` carries its own canonical name.
5008            Self::Named(name) => return f.write_str(name),
5009        })
5010    }
5011}
5012
5013#[derive(Debug, Clone, PartialEq)]
5014pub enum Literal {
5015    Integer(i64),
5016    Float(f64),
5017    /// Exact decimal literal — a bare `12.34`-style token, kept as
5018    /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
5019    /// before it becomes a `Value::Numeric`. PG parses such literals as
5020    /// `numeric`, not `double precision`. (Scientific/huge literals stay
5021    /// `Float`.)
5022    Numeric {
5023        unscaled: i128,
5024        /// v7.39 (round 271) — widened to u16. At u8 a literal with more
5025        /// than 255 decimal places could not be represented, and the
5026        /// conversion's `.expect("lexer-validated decimal")` aborted the
5027        /// query with an internal error on SQL PG accepts.
5028        scale: u16,
5029    },
5030    /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
5031    /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
5032    /// `Value::NumericBig` at eval; previously such literals fell back to double.
5033    NumericBig(String),
5034    String(String),
5035    /// v7.38.8 — a temporal constant that has already been decoded.
5036    ///
5037    /// Without these the only way to carry one through the AST was as
5038    /// text, and a predicate comparing a `timestamp` column against a
5039    /// literal then coerced that text back into a timestamp ONCE PER
5040    /// ROW — 32 ns of the 52 a comparison cost, measured on a customer
5041    /// profile. `constfold` produced text for the same reason: its exit
5042    /// had nothing else to hand back.
5043    ///
5044    /// `text` keeps the spelling so `Display` round-trips byte for byte,
5045    /// the way `Interval` already does and for the same reason: this
5046    /// node is printed in EXPLAIN, in dumps and in error messages, and
5047    /// none of those should change because the value stopped being
5048    /// carried as a string. The enum already holds a `String` and an
5049    /// `i128`, so neither variant widens it.
5050    Timestamp {
5051        micros: i64,
5052        text: String,
5053    },
5054    /// Days since the epoch `Value::Date` counts from. See
5055    /// [`Literal::Timestamp`].
5056    Date {
5057        days: i32,
5058        text: String,
5059    },
5060    Bool(bool),
5061    Null,
5062    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
5063    Vector(Vec<f32>),
5064    /// TEXT[] value carried through the prepared-bind path
5065    /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
5066    /// text form, so the array rides the AST natively).
5067    TextArray(Vec<Option<String>>),
5068    /// INT[] value carried through the prepared-bind path.
5069    IntArray(Vec<Option<i32>>),
5070    /// BIGINT[] value carried through the prepared-bind path.
5071    BigIntArray(Vec<Option<i64>>),
5072    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
5073    /// Three independent dimensions: `months` (variable-length;
5074    /// year/month), `days` (fixed 86400 seconds at non-DST, but
5075    /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
5076    /// stays distinguishable), and `micros` (sub-day; can carry).
5077    /// `text` keeps the original spelling so Display round-trips
5078    /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
5079    Interval {
5080        months: i32,
5081        days: i32,
5082        micros: i64,
5083        text: String,
5084    },
5085}
5086
5087#[derive(Debug, Clone, PartialEq, Eq)]
5088pub struct ColumnName {
5089    pub qualifier: Option<String>,
5090    pub name: String,
5091}
5092
5093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5094pub enum BinOp {
5095    Or,
5096    And,
5097    Eq,
5098    NotEq,
5099    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
5100    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
5101    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
5102    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
5103    /// PG-style JOIN ON predicates and pg_dump output.
5104    IsDistinctFrom,
5105    IsNotDistinctFrom,
5106    /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
5107    /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
5108    /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
5109    /// is a real division (round 351).
5110    IntDiv,
5111    Lt,
5112    LtEq,
5113    Gt,
5114    GtEq,
5115    Add,
5116    Sub,
5117    Mul,
5118    Div,
5119    /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
5120    /// precedence as Mul/Div; result type follows left operand.
5121    Mod,
5122    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
5123    /// operands of equal dimension; engine returns `Value::Float(d)`.
5124    L2Distance,
5125    /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
5126    GeomParallel,
5127    /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
5128    OverLeft,
5129    OverRight,
5130    /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
5131    GeomPerp,
5132    /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
5133    GeomSameAs,
5134    /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
5135    /// object to the left-hand one.
5136    ClosestPoint,
5137    /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
5138    GeomHoriz,
5139    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
5140    /// more similar" remains true (matches pgvector's published convention).
5141    InnerProduct,
5142    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
5143    CosineDistance,
5144    /// SQL string concatenation `||`. NULL propagates.
5145    Concat,
5146    /// Bitwise OR `|` on integers.
5147    BitOr,
5148    /// Bitwise AND `&` on integers.
5149    BitAnd,
5150    /// Bitwise XOR `#` on integers and equal-length bit strings.
5151    BitXor,
5152    /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
5153    /// sides as truth values and returns their exclusive-or (`1 XOR 0`
5154    /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
5155    /// MySQL dialect produces it; PG has no logical XOR. Its precedence
5156    /// sits between OR (loosest) and AND.
5157    LogicalXor,
5158    /// v4.14 `json -> key` — element access by string key (object)
5159    /// or integer index (array). Returns a JSON value.
5160    JsonGet,
5161    /// v4.14 `json ->> key` — same access, returns the result as
5162    /// TEXT (unwraps a top-level JSON string; renders other scalars
5163    /// as their canonical text).
5164    JsonGetText,
5165    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
5166    /// text array literal like `'{a,0,b}'`. Returns JSON.
5167    JsonGetPath,
5168    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
5169    JsonGetPathText,
5170    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
5171    /// when every key/value in `sub_json` is structurally present in
5172    /// the left side. Matches PG semantics (top-level + recursive).
5173    JsonContains,
5174    /// `@?` — jsonb path existence (jsonb_path_exists).
5175    JsonPathExists,
5176    /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
5177    /// `a <@ b` is defined as `b @> a` (same semantics, swapped
5178    /// sides). Eval dispatch reuses `JsonContains` with swapped args.
5179    JsonContainedBy,
5180    /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
5181    /// returns BOOL. For an object, true if `key` is an existing
5182    /// member name; for an array, true if any element is the string
5183    /// `key` (PG semantics).
5184    JsonKeyExists,
5185    /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
5186    /// returns BOOL.
5187    JsonKeysAny,
5188    /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
5189    /// returns BOOL.
5190    JsonKeysAll,
5191    /// `jsonb #- path_text[]` — delete the value at a nested path.
5192    /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
5193    JsonDeletePath,
5194    /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
5195    /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
5196    /// tsvector` and engine eval normalises either ordering.
5197    TsMatch,
5198    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
5199    /// `<<`. LHS network is strictly inside RHS network (no equality).
5200    InetContainedBy,
5201    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
5202    /// `<<=`. LHS network ⊆ RHS network.
5203    InetContainedByEq,
5204    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
5205    /// LHS network strictly contains RHS network.
5206    InetContains,
5207    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
5208    /// LHS network ⊇ RHS network.
5209    InetContainsEq,
5210    /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
5211    /// True iff either network contains any address of the other.
5212    InetOverlap,
5213    /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
5214    /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
5215    Intersects,
5216    /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
5217    /// (point, box).
5218    IsBelow,
5219    IsAbove,
5220    /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
5221    /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
5222    /// where `'A' < 'a'` is false under a non-C collation, which is the
5223    /// whole reason the operator family exists — it is what makes a LIKE
5224    /// prefix index-usable. pg_dump writes these into index definitions.
5225    PatternLt,
5226    PatternLtEq,
5227    PatternGt,
5228    PatternGtEq,
5229}
5230
5231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5232pub enum UnOp {
5233    Not,
5234    Neg,
5235    /// Bitwise NOT `~` on integers.
5236    BitNot,
5237    /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
5238    /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
5239    /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
5240    /// while PG18 and MariaDB accept every one of them.
5241    ///
5242    /// It is not a no-op to drop at parse time — PG refuses it on
5243    /// non-numeric operands ("operator does not exist: + boolean"), so the
5244    /// operand's type has to be seen at eval.
5245    Plus,
5246}
5247
5248// --- Display impls (round-trip-safe) --------------------------------------
5249
5250impl Statement {
5251    /// v7.18 — classify whether the statement is read-only at
5252    /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
5253    /// route SELECT-shaped traffic through the fan-out
5254    /// `AsyncReadHandle` (no writer-lock contention) while
5255    /// keeping DML / DDL / TX-control on the single-writer path.
5256    ///
5257    /// The classification matches what
5258    /// `Engine::execute_readonly_with_cancel` accepts: anything
5259    /// that does NOT mutate catalog, statistics, session state,
5260    /// or transaction state. WaitForWalPosition is included
5261    /// (engine returns `Unsupported`, but the classification is
5262    /// semantically read-only — no mutation). Empty is excluded
5263    /// out of an abundance of caution — the no-op routes
5264    /// through the writer so any future side effect lands
5265    /// uniformly.
5266    ///
5267    /// **Not connection-state aware**. `SET LOCAL` / `RESET`
5268    /// affect session parameters and must run on the writer
5269    /// engine that owns the session state; they classify as
5270    /// writer-path here. Same for `BEGIN` / `COMMIT` /
5271    /// `ROLLBACK` / `SAVEPOINT` — transaction control is
5272    /// always writer-path.
5273    /// v7.39 (round 435) — does this statement implicitly COMMIT an open
5274    /// transaction under MySQL?
5275    ///
5276    /// PG runs DDL inside the transaction; MySQL commits before (and after)
5277    /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
5278    /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
5279    /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
5280    /// nested START TRANSACTION; and measured NOT to fire for `CREATE
5281    /// TEMPORARY TABLE`, `SET`, or a SELECT.
5282    ///
5283    /// A positive list, not "everything that is not DML": a statement
5284    /// wrongly listed here commits a client's data early, which is as bad as
5285    /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
5286    /// COMPACT) are left out — a MySQL session never sends them.
5287    #[must_use]
5288    pub fn mysql_implicit_commit(&self) -> bool {
5289        match self {
5290            // MySQL's documented exception, measured on MariaDB 11: a
5291            // TEMPORARY table is not DDL for this purpose and does not
5292            // commit. (Round 435 got this for free because the parser then
5293            // lowered that spelling to `Statement::Empty`; round 436 made it
5294            // a real CREATE TABLE, and the round-435 pin caught it.)
5295            Self::CreateTable(c) => !c.temporary,
5296            // MySQL commits the open transaction and opens a fresh one.
5297            Self::Begin { .. }
5298            | Self::DropTable { .. }
5299            | Self::DropIndex { .. }
5300            | Self::CreateIndex(_)
5301            | Self::AlterIndex { .. }
5302            | Self::AlterTable(_)
5303            | Self::Truncate { .. }
5304            | Self::Analyze { .. }
5305            | Self::CreateStatistics { .. }
5306            | Self::DropStatistics { .. }
5307            | Self::CreateView { .. }
5308            | Self::DropView { .. }
5309            | Self::CreateMaterializedView { .. }
5310            | Self::RefreshMaterializedView { .. }
5311            | Self::DropMaterializedView { .. }
5312            | Self::CreateSequence(_)
5313            | Self::AlterSequence { .. }
5314            | Self::DropSequence { .. }
5315            | Self::CreateFunction(_)
5316            | Self::DropFunction { .. }
5317            | Self::CreateTrigger(_)
5318            | Self::DropTrigger { .. }
5319            | Self::CreateRule(_)
5320            | Self::DropRule { .. }
5321            | Self::CreateType(_)
5322            | Self::DropType { .. }
5323            | Self::AlterTypeAddValue { .. }
5324            | Self::AlterTypeRenameValue { .. }
5325            | Self::CreateDomain(_)
5326            | Self::AlterDomain { .. }
5327            | Self::DropDomain { .. }
5328            | Self::CreateSchema { .. }
5329            | Self::DropSchema { .. }
5330            | Self::CreateUser { .. }
5331            | Self::DropUser { .. }
5332            | Self::Grant { .. }
5333            | Self::Revoke { .. }
5334            | Self::CreatePolicy(_)
5335            | Self::AlterPolicy(_)
5336            | Self::DropPolicy { .. }
5337            | Self::CommentOn { .. }
5338            | Self::CreateExtension { .. } => true,
5339            _ => false,
5340        }
5341    }
5342
5343    #[must_use]
5344    pub fn is_readonly(&self) -> bool {
5345        match self {
5346            Statement::RenameTables(_) => false,
5347            // v7.39 (round 288) — SET CONSTRAINTS changes transaction
5348            // state, and IMMEDIATE can run the deferred checks there and
5349            // then; writer-path.
5350            Statement::SetConstraints { .. } => false,
5351            // v7.39 (round 695) — it writes nothing (SPG has no
5352            // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
5353            // writer and a read-only session refuses it there too.
5354            Statement::AlterSystem { .. } => false,
5355            // Same shape: a no-op here, a writer to PG, so a read-only
5356            // session refuses it as PG's would.
5357            Statement::NoOpPreventedInTransaction { .. } => false,
5358            Statement::DropDatabase { .. } => false,
5359            // v7.39 (round 696) — they perform nothing, so nothing is
5360            // written; PG classes LOCK and the OWNED BY pair as writers and
5361            // a read-only session refuses them there.
5362            Statement::ValidateOnly { .. } => false,
5363            // v7.39 (round 750) — a credential rotation persists.
5364            Statement::AlterRolePassword { .. } => true,
5365            Statement::DropAggregate { .. } => false,
5366            // v7.39 (round 547) — records a GUC default in the catalog.
5367            Statement::SetDbRoleSetting(_) => false,
5368            // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
5369            // but they name a relation and PG refuses one that is not
5370            // there, so they are not read-only in the sense this asks.
5371            Statement::Maintain { .. } => false,
5372            // v7.39 (round 277) — the prepared-statement surface is
5373            // session state, like SET; writer-path so it lands on the
5374            // engine that owns the session. EXECUTE may also run a
5375            // write, and its body is only known at execution time.
5376            Statement::Prepare { .. }
5377            | Statement::Execute { .. }
5378            | Statement::Deallocate(_)
5379            | Statement::Call(_)
5380            | Statement::PrepareTransaction(_)
5381            | Statement::CreateStatistics { .. }
5382            | Statement::DropStatistics { .. }
5383            // v7.39 (round 318, V51) — KILL signals another connection;
5384            // it must run on the writer path that owns the registry hook.
5385            | Statement::Kill { .. }
5386            // v7.39 (round 320, V53) — DISCARD throws session state away;
5387            // writer path, like SET / RESET.
5388            | Statement::Discard(_)
5389            // v7.39.2 — `USE <db>` writes session state, the same way
5390            // SET does, and takes the same path.
5391            | Statement::UseDatabase(_) => false,
5392            // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
5393            // locks MUTATES the lock table, so it is not a read. Left as
5394            // a read it went to the read-only executor and the locking
5395            // pre-pass never ran at all — the clause was honoured only
5396            // inside an explicit transaction, and silently ignored in
5397            // autocommit, which is where a queue worker runs it.
5398            Statement::Select(s) if s.locking.is_some() => false,
5399            Statement::Select(_)
5400            | Statement::CopyTo { .. }
5401            | Statement::CopyToFile { .. }
5402            | Statement::Explain(_)
5403            | Statement::ShowTables
5404            | Statement::ShowDatabases
5405            | Statement::ShowCreateTable(_)
5406            | Statement::ShowIndexes(_)
5407            | Statement::ShowStatus
5408            | Statement::ShowVariables
5409            | Statement::ShowVariablesLike(_)
5410            | Statement::ShowProcesslist
5411            | Statement::ShowColumns(_)
5412            | Statement::ShowUsers
5413            | Statement::ShowPublications
5414            | Statement::ShowSubscriptions
5415            | Statement::WaitForWalPosition { .. } => true,
5416            // Everything else mutates catalog, statistics,
5417            // session state, or transaction state — writer path.
5418            // Listed explicitly so a new Statement variant fails
5419            // the match exhaustiveness check and forces a
5420            // classification decision at add-site.
5421            Statement::Empty
5422            // v7.39 (round 169) — VACUUM mutates storage (reclaims
5423            // tombstoned versions): writer path.
5424            | Statement::Vacuum { .. }
5425            | Statement::DropTable { .. }
5426            | Statement::DropIndex { .. }
5427            | Statement::CreateTable(_)
5428            | Statement::CreateExtension(_)
5429            | Statement::DoBlock(_)
5430            | Statement::CreateIndex(_)
5431            | Statement::Insert(_)
5432            | Statement::Update(_)
5433            | Statement::Delete(_)
5434            | Statement::Merge(_)
5435            | Statement::Begin(_)
5436            | Statement::Commit
5437            | Statement::Rollback
5438            | Statement::Savepoint(_)
5439            | Statement::RollbackToSavepoint(_)
5440            | Statement::ReleaseSavepoint(_)
5441            | Statement::CreateUser(_)
5442            | Statement::DropUser { .. }
5443            | Statement::SetRole(_)
5444            | Statement::Grant(_)
5445            | Statement::Revoke(_)
5446            | Statement::CreatePolicy(_)
5447            | Statement::AlterPolicy(_)
5448            | Statement::DropPolicy(_)
5449            | Statement::AlterIndex(_)
5450            | Statement::AlterTable(_)
5451            | Statement::CreatePublication(_)
5452            | Statement::DropPublication { .. }
5453            | Statement::CreateSubscription(_)
5454            | Statement::DropSubscription { .. }
5455            | Statement::Analyze(_)
5456            | Statement::Truncate { .. }
5457            | Statement::CompactColdSegments
5458            | Statement::SetParameter { .. }
5459            | Statement::SetParameterList(_)
5460            | Statement::SetUserVars(..)
5461            | Statement::SetTransaction { .. }
5462            | Statement::ShowParameter(_)
5463            | Statement::ResetParameter(_)
5464            | Statement::CreateFunction(_)
5465            | Statement::CreateTrigger(_)
5466            | Statement::DropTrigger { .. }
5467            | Statement::CreateRule(_)
5468            | Statement::DropRule { .. }
5469            | Statement::DropFunction { .. }
5470            | Statement::CreateSequence(_)
5471            | Statement::AlterSequence(_)
5472            | Statement::DropSequence { .. }
5473            | Statement::CreateView(_)
5474            | Statement::DropView { .. }
5475            | Statement::CreateMaterializedView(_)
5476            | Statement::RefreshMaterializedView { .. }
5477            | Statement::DropMaterializedView { .. }
5478            | Statement::CreateType(_)
5479            | Statement::AlterTypeAddValue { .. }
5480            | Statement::AlterTypeRenameValue { .. }
5481            | Statement::CommentOn { .. }
5482            | Statement::DropType { .. }
5483            | Statement::CreateDomain(_)
5484            | Statement::DropDomain { .. }
5485            | Statement::CreateSchema { .. }
5486            | Statement::DropSchema { .. }
5487            // v7.39 (round 218) — cursors mutate per-session cursor state
5488            // (open/position/close) on the writer engine: writer path.
5489            | Statement::DeclareCursor { .. }
5490            | Statement::FetchCursor { .. }
5491            | Statement::MoveCursor { .. }
5492            | Statement::CloseCursor { .. }
5493            // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5494            // state / the notification queue: writer path.
5495            | Statement::Listen(_)
5496            | Statement::Notify { .. }
5497            | Statement::Unlisten(_)
5498            | Statement::CopyFromFile { .. }
5499            | Statement::AlterDomain { .. } => false,
5500        }
5501    }
5502}
5503
5504/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5505/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5506#[derive(Debug, Clone, PartialEq, Eq)]
5507pub struct GrantStatement {
5508    /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5509    /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5510    /// is why they keep the case the user typed.
5511    pub privileges: Vec<GrantPriv>,
5512    /// What the privileges are on.
5513    pub object: GrantObject,
5514    /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5515    pub grantees: Vec<String>,
5516    /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5517    /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5518    /// privilege itself).
5519    pub grant_option: bool,
5520}
5521
5522/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5523/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5524/// An empty column list means the privilege is table-wide.
5525#[derive(Debug, Clone, PartialEq, Eq)]
5526pub struct GrantPriv {
5527    pub word: String,
5528    pub columns: Vec<String>,
5529}
5530
5531/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5532/// privileges; every other object class parses and is accepted as a no-op, so
5533/// a pg_dump that grants on schemas / sequences / functions still restores.
5534#[derive(Debug, Clone, PartialEq, Eq)]
5535pub enum GrantObject {
5536    /// `ON [TABLE] a, b` — the enforced case.
5537    Tables(Vec<String>),
5538    /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5539    /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5540    /// granted roles; the grantees are the members.
5541    Roles(Vec<String>),
5542    /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5543    /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5544    Sequences(Vec<String>),
5545    /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5546    Schemas(Vec<String>),
5547    /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5548    Databases(Vec<String>),
5549    /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5550    /// (SPG keys functions by name); the argument list parses and is dropped.
5551    Functions(Vec<(String, Option<Vec<String>>)>),
5552    /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5553    /// every table at GRANT time, exactly like PG.
5554    AllTablesInSchema,
5555    /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5556    /// message.
5557    Other(String),
5558}
5559
5560impl GrantStatement {
5561    /// Round-trip text. `grant = false` renders the REVOKE form.
5562    fn render(&self, grant: bool) -> alloc::string::String {
5563        use core::fmt::Write as _;
5564        let mut s = alloc::string::String::new();
5565        let privs = if self.privileges.is_empty() {
5566            alloc::string::String::from("ALL")
5567        } else {
5568            let parts: Vec<_> = self
5569                .privileges
5570                .iter()
5571                .map(|p| {
5572                    if p.columns.is_empty() {
5573                        p.word.clone()
5574                    } else {
5575                        let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5576                        alloc::format!("{} ({})", p.word, cols.join(", "))
5577                    }
5578                })
5579                .collect();
5580            parts.join(", ")
5581        };
5582        let obj = match &self.object {
5583            GrantObject::Tables(t) => {
5584                let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5585                alloc::format!("TABLE {}", names.join(", "))
5586            }
5587            GrantObject::Roles(r) => {
5588                let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5589                names.join(", ")
5590            }
5591            GrantObject::Sequences(n) => {
5592                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5593                alloc::format!("SEQUENCE {}", names.join(", "))
5594            }
5595            GrantObject::Schemas(n) => {
5596                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5597                alloc::format!("SCHEMA {}", names.join(", "))
5598            }
5599            GrantObject::Databases(n) => {
5600                let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5601                alloc::format!("DATABASE {}", names.join(", "))
5602            }
5603            GrantObject::Functions(n) => {
5604                let names: Vec<_> = n
5605                    .iter()
5606                    .map(|(name, args)| match args {
5607                        Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5608                        None => quote_ident(name),
5609                    })
5610                    .collect();
5611                alloc::format!("FUNCTION {}", names.join(", "))
5612            }
5613            GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5614            GrantObject::Other(k) => k.clone(),
5615        };
5616        let who: Vec<_> = self
5617            .grantees
5618            .iter()
5619            .map(|g| {
5620                if g.is_empty() {
5621                    "PUBLIC".into()
5622                } else {
5623                    quote_ident(g)
5624                }
5625            })
5626            .collect();
5627        if let GrantObject::Roles(_) = &self.object {
5628            let _ = if grant {
5629                write!(s, "GRANT {obj} TO {}", who.join(", "))
5630            } else {
5631                write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5632            };
5633            return s;
5634        }
5635        if grant {
5636            let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5637            if self.grant_option {
5638                s.push_str(" WITH GRANT OPTION");
5639            }
5640        } else {
5641            s.push_str("REVOKE ");
5642            if self.grant_option {
5643                s.push_str("GRANT OPTION FOR ");
5644            }
5645            let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5646        }
5647        s
5648    }
5649}
5650
5651impl fmt::Display for Statement {
5652    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5653        match self {
5654            Self::Empty => Ok(()),
5655            // v7.39 (round 695) — deparsed the way PG writes it.
5656            // v7.39 (round 696) — never deparsed into a dump (nothing is
5657            // stored), so the shortest faithful spelling of what it was.
5658            Self::DropAggregate { if_exists, items } => {
5659                f.write_str("DROP AGGREGATE ")?;
5660                if *if_exists {
5661                    f.write_str("IF EXISTS ")?;
5662                }
5663                for (i, (name, args)) in items.iter().enumerate() {
5664                    if i > 0 {
5665                        f.write_str(", ")?;
5666                    }
5667                    match args {
5668                        Some(a) => write!(f, "{name}({})", a.join(", "))?,
5669                        None => write!(f, "{name}(*)")?,
5670                    }
5671                }
5672                Ok(())
5673            }
5674            Self::AlterRolePassword { name, password } => {
5675                write!(f, "ALTER ROLE {}", quote_ident(name))?;
5676                match password {
5677                    Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5678                    None => f.write_str(" PASSWORD NULL"),
5679                }
5680            }
5681            Self::ValidateOnly { kind, names } => match kind {
5682                ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5683                ValidateOnlyKind::RoleName => {
5684                    write!(f, "DROP OWNED BY {}", names.join(", "))
5685                }
5686                ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5687                ValidateOnlyKind::ExtensionAvailable => {
5688                    write!(f, "CREATE EXTENSION {}", names.join(", "))
5689                }
5690                ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5691                ValidateOnlyKind::CollationName => {
5692                    write!(f, "DROP COLLATION {}", names.join(", "))
5693                }
5694                ValidateOnlyKind::TsConfigName => {
5695                    write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5696                }
5697                ValidateOnlyKind::EventTriggerName => {
5698                    write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5699                }
5700                ValidateOnlyKind::TablespaceName => {
5701                    write!(f, "DROP TABLESPACE {}", names.join(", "))
5702                }
5703                ValidateOnlyKind::LargeObjectOid => {
5704                    write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5705                }
5706                ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5707                ValidateOnlyKind::AggregateName => {
5708                    write!(f, "ALTER AGGREGATE {}", names.join(", "))
5709                }
5710                ValidateOnlyKind::ConversionName => {
5711                    write!(f, "DROP CONVERSION {}", names.join(", "))
5712                }
5713                ValidateOnlyKind::LanguageName => {
5714                    write!(f, "DROP LANGUAGE {}", names.join(", "))
5715                }
5716                ValidateOnlyKind::ExtensionInstalled => {
5717                    write!(f, "DROP EXTENSION {}", names.join(", "))
5718                }
5719            },
5720            Self::AlterSystem { parameter } => match parameter {
5721                Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5722                None => f.write_str("ALTER SYSTEM RESET ALL"),
5723            },
5724            // v7.39 (round 547) — round-trips as PG writes it.
5725            Self::SetDbRoleSetting(st) => {
5726                match (&st.database, &st.role) {
5727                    (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5728                    (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5729                    (None, None) => f.write_str("ALTER ROLE ALL")?,
5730                }
5731                if let (Some(d), Some(_)) = (&st.database, &st.role) {
5732                    write!(f, " IN DATABASE {d}")?;
5733                }
5734                match (&st.param, &st.value) {
5735                    (None, _) => f.write_str(" RESET ALL"),
5736                    (Some(p), None) => write!(f, " RESET {p}"),
5737                    (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5738                }
5739            }
5740            Self::Maintain {
5741                kind,
5742                concurrently,
5743                target,
5744            } => {
5745                f.write_str(match kind {
5746                    crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5747                    _ => "REINDEX ",
5748                })?;
5749                if *concurrently {
5750                    f.write_str("CONCURRENTLY ")?;
5751                }
5752                if let Some(t) = target {
5753                    f.write_str(t)?;
5754                }
5755                Ok(())
5756            }
5757            Self::DropDatabase { name, if_exists } => {
5758                f.write_str("DROP DATABASE ")?;
5759                if *if_exists {
5760                    f.write_str("IF EXISTS ")?;
5761                }
5762                f.write_str(name)
5763            }
5764            Self::NoOpPreventedInTransaction { what, .. } => f.write_str(what),
5765            Self::SetConstraints { names, deferred } => {
5766                f.write_str("SET CONSTRAINTS ")?;
5767                if names.is_empty() {
5768                    f.write_str("ALL")?;
5769                } else {
5770                    for (i, n) in names.iter().enumerate() {
5771                        if i > 0 {
5772                            f.write_str(", ")?;
5773                        }
5774                        f.write_str(n)?;
5775                    }
5776                }
5777                f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5778            }
5779            // v7.39 (round 277) — the source text is kept verbatim so
5780            // `pg_prepared_statements.statement` can report it the way
5781            // PG does (the whole PREPARE statement, not just the body).
5782            Self::Prepare { source, .. } => f.write_str(source),
5783            Self::Execute { name, args } => {
5784                write!(f, "EXECUTE {}", quote_ident(name))?;
5785                if !args.is_empty() {
5786                    f.write_str("(")?;
5787                    for (i, a) in args.iter().enumerate() {
5788                        if i > 0 {
5789                            f.write_str(", ")?;
5790                        }
5791                        write!(f, "{a}")?;
5792                    }
5793                    f.write_str(")")?;
5794                }
5795                Ok(())
5796            }
5797            Self::CreateStatistics {
5798                name,
5799                if_not_exists,
5800                kinds,
5801                columns,
5802                table,
5803            } => {
5804                f.write_str("CREATE STATISTICS ")?;
5805                if *if_not_exists {
5806                    f.write_str("IF NOT EXISTS ")?;
5807                }
5808                write!(f, "{}", quote_ident(name))?;
5809                if !kinds.is_empty() {
5810                    write!(f, " ({})", kinds.join(", "))?;
5811                }
5812                write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5813            }
5814            Self::DropStatistics { name, if_exists } => {
5815                f.write_str("DROP STATISTICS ")?;
5816                if *if_exists {
5817                    f.write_str("IF EXISTS ")?;
5818                }
5819                write!(f, "{}", quote_ident(name))
5820            }
5821            Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5822            Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5823            Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5824            Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5825            Self::DeclareCursor {
5826                name,
5827                scroll,
5828                hold,
5829                query,
5830            } => {
5831                write!(f, "DECLARE {} ", quote_ident(name))?;
5832                match scroll {
5833                    Some(true) => f.write_str("SCROLL ")?,
5834                    Some(false) => f.write_str("NO SCROLL ")?,
5835                    None => {}
5836                }
5837                f.write_str("CURSOR ")?;
5838                if *hold {
5839                    f.write_str("WITH HOLD ")?;
5840                }
5841                write!(f, "FOR {query}")
5842            }
5843            Self::FetchCursor { name, direction } => {
5844                write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5845            }
5846            Self::MoveCursor { name, direction } => {
5847                write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5848            }
5849            Self::CloseCursor { name } => match name {
5850                Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5851                None => f.write_str("CLOSE ALL"),
5852            },
5853            Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5854            Self::Notify { channel, payload } => {
5855                write!(f, "NOTIFY {}", quote_ident(channel))?;
5856                if let Some(p) = payload {
5857                    write!(f, ", '{}'", p.replace('\'', "''"))?;
5858                }
5859                Ok(())
5860            }
5861            Self::Unlisten(ch) => match ch {
5862                Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5863                None => f.write_str("UNLISTEN *"),
5864            },
5865            Self::CopyTo {
5866                table,
5867                columns,
5868                query,
5869                options,
5870            } => {
5871                if let Some(q) = query {
5872                    write!(f, "COPY ({q})")?;
5873                } else {
5874                    write!(f, "COPY {table}")?;
5875                    if let Some(cols) = columns {
5876                        write!(f, " ({})", cols.join(", "))?;
5877                    }
5878                }
5879                write!(f, " TO STDOUT")?;
5880                let mut parts: Vec<String> = Vec::new();
5881                if options.format == CopyFormat::Csv {
5882                    parts.push("FORMAT csv".to_string());
5883                }
5884                if options.header {
5885                    parts.push("HEADER true".to_string());
5886                }
5887                if let Some(d) = options.delimiter {
5888                    parts.push(alloc::format!("DELIMITER '{d}'"));
5889                }
5890                if let Some(n) = &options.null_str {
5891                    parts.push(alloc::format!("NULL '{n}'"));
5892                }
5893                if let Some(q) = options.quote {
5894                    parts.push(alloc::format!("QUOTE '{q}'"));
5895                }
5896                if !parts.is_empty() {
5897                    write!(f, " WITH ({})", parts.join(", "))?;
5898                }
5899                Ok(())
5900            }
5901            Self::CopyFromFile {
5902                table,
5903                columns,
5904                path,
5905                options,
5906            } => {
5907                write!(f, "COPY {table}")?;
5908                if let Some(cols) = columns {
5909                    write!(f, " ({})", cols.join(", "))?;
5910                }
5911                write!(f, " FROM '{path}'")?;
5912                let mut parts: Vec<String> = Vec::new();
5913                if options.format == CopyFormat::Csv {
5914                    parts.push("FORMAT csv".to_string());
5915                }
5916                if options.header {
5917                    parts.push("HEADER true".to_string());
5918                }
5919                if let Some(d) = options.delimiter {
5920                    parts.push(alloc::format!("DELIMITER '{d}'"));
5921                }
5922                if let Some(n) = &options.null_str {
5923                    parts.push(alloc::format!("NULL '{n}'"));
5924                }
5925                if let Some(q) = options.quote {
5926                    parts.push(alloc::format!("QUOTE '{q}'"));
5927                }
5928                if !parts.is_empty() {
5929                    write!(f, " WITH ({})", parts.join(", "))?;
5930                }
5931                Ok(())
5932            }
5933            Self::CopyToFile {
5934                table,
5935                columns,
5936                query,
5937                path,
5938                options,
5939            } => {
5940                if let Some(q) = query {
5941                    write!(f, "COPY ({q})")?;
5942                } else {
5943                    write!(f, "COPY {table}")?;
5944                    if let Some(cols) = columns {
5945                        write!(f, " ({})", cols.join(", "))?;
5946                    }
5947                }
5948                write!(f, " TO '{path}'")?;
5949                let mut parts: Vec<String> = Vec::new();
5950                if options.format == CopyFormat::Csv {
5951                    parts.push("FORMAT csv".to_string());
5952                }
5953                if options.header {
5954                    parts.push("HEADER true".to_string());
5955                }
5956                if let Some(d) = options.delimiter {
5957                    parts.push(alloc::format!("DELIMITER '{d}'"));
5958                }
5959                if let Some(n) = &options.null_str {
5960                    parts.push(alloc::format!("NULL '{n}'"));
5961                }
5962                if let Some(q) = options.quote {
5963                    parts.push(alloc::format!("QUOTE '{q}'"));
5964                }
5965                if !parts.is_empty() {
5966                    write!(f, " WITH ({})", parts.join(", "))?;
5967                }
5968                Ok(())
5969            }
5970            Self::AlterDomain { name, action } => {
5971                write!(f, "ALTER DOMAIN {name} ")?;
5972                match action {
5973                    AlterDomainAction::AddConstraint { name: cn, check } => match cn {
5974                        Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
5975                        None => write!(f, "ADD CHECK ({check})"),
5976                    },
5977                    AlterDomainAction::DropConstraint {
5978                        name: cn,
5979                        if_exists,
5980                    } => {
5981                        if *if_exists {
5982                            write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
5983                        } else {
5984                            write!(f, "DROP CONSTRAINT {cn}")
5985                        }
5986                    }
5987                    AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
5988                    AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
5989                    AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
5990                    AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
5991                    AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
5992                }
5993            }
5994            Self::Truncate {
5995                tables,
5996                restart_identity,
5997                cascade,
5998                only,
5999            } => {
6000                f.write_str("TRUNCATE TABLE ")?;
6001                if *only {
6002                    f.write_str("ONLY ")?;
6003                }
6004                for (i, t) in tables.iter().enumerate() {
6005                    if i > 0 {
6006                        f.write_str(", ")?;
6007                    }
6008                    f.write_str(t)?;
6009                }
6010                if *restart_identity {
6011                    f.write_str(" RESTART IDENTITY")?;
6012                }
6013                if *cascade {
6014                    f.write_str(" CASCADE")?;
6015                }
6016                Ok(())
6017            }
6018            Self::DropTable { names, if_exists } => {
6019                f.write_str("DROP TABLE ")?;
6020                if *if_exists {
6021                    f.write_str("IF EXISTS ")?;
6022                }
6023                for (i, n) in names.iter().enumerate() {
6024                    if i > 0 {
6025                        f.write_str(", ")?;
6026                    }
6027                    write!(f, "{}", quote_ident(n))?;
6028                }
6029                Ok(())
6030            }
6031            Self::DropIndex {
6032                name,
6033                if_exists,
6034                table,
6035            } => {
6036                f.write_str("DROP INDEX ")?;
6037                if *if_exists {
6038                    f.write_str("IF EXISTS ")?;
6039                }
6040                write!(f, "{}", quote_ident(name))?;
6041                if let Some(t) = table {
6042                    write!(f, " ON {}", quote_ident(t))?;
6043                }
6044                Ok(())
6045            }
6046            Self::Select(s) => s.fmt(f),
6047            Self::CreateTable(s) => s.fmt(f),
6048            Self::CreateIndex(s) => s.fmt(f),
6049            Self::Insert(s) => s.fmt(f),
6050            Self::Update(s) => s.fmt(f),
6051            Self::Delete(s) => s.fmt(f),
6052            Self::Merge(s) => s.fmt(f),
6053            Self::Vacuum { table, analyze } => {
6054                f.write_str("VACUUM")?;
6055                if *analyze {
6056                    f.write_str(" ANALYZE")?;
6057                }
6058                if let Some(t) = table {
6059                    write!(f, " {}", quote_ident(t))?;
6060                }
6061                Ok(())
6062            }
6063            Self::Begin(modes) => {
6064                f.write_str("BEGIN")?;
6065                if let Some(level) = modes.isolation {
6066                    write!(f, " ISOLATION LEVEL {level}")?;
6067                }
6068                match modes.read_only {
6069                    Some(true) => f.write_str(" READ ONLY")?,
6070                    Some(false) => f.write_str(" READ WRITE")?,
6071                    None => {}
6072                }
6073                Ok(())
6074            }
6075            Self::Commit => f.write_str("COMMIT"),
6076            Self::Rollback => f.write_str("ROLLBACK"),
6077            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
6078            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
6079            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
6080            Self::ShowTables => f.write_str("SHOW TABLES"),
6081            Self::ShowDatabases => f.write_str("SHOW DATABASES"),
6082            Self::UseDatabase(n) => write!(f, "USE {}", quote_ident(n)),
6083            Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
6084            Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
6085            Self::ShowStatus => f.write_str("SHOW STATUS"),
6086            Self::ShowVariables => f.write_str("SHOW VARIABLES"),
6087            Self::ShowVariablesLike(p) => {
6088                write!(f, "SHOW VARIABLES LIKE '{}'", p.replace('\'', "''"))
6089            }
6090            Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
6091            Self::Discard(t) => write!(f, "DISCARD {t}"),
6092            Self::Kill { query_only, id } => {
6093                if *query_only {
6094                    write!(f, "KILL QUERY {id}")
6095                } else {
6096                    write!(f, "KILL CONNECTION {id}")
6097                }
6098            }
6099            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
6100            Self::CreateUser(s) => write!(
6101                f,
6102                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
6103                quote_ident(&s.name),
6104                s.role
6105            ),
6106            Self::DropUser { name, if_exists } => {
6107                let ie = if *if_exists { "IF EXISTS " } else { "" };
6108                write!(f, "DROP USER {ie}{}", quote_ident(name))
6109            }
6110            Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
6111            Self::SetRole(None) => f.write_str("RESET ROLE"),
6112            Self::Grant(g) => write!(f, "{}", g.render(true)),
6113            Self::Revoke(g) => write!(f, "{}", g.render(false)),
6114            Self::CreatePolicy(s) => {
6115                write!(
6116                    f,
6117                    "CREATE POLICY {} ON {}",
6118                    quote_ident(&s.name),
6119                    quote_ident(&s.table)
6120                )?;
6121                if !s.permissive {
6122                    f.write_str(" AS RESTRICTIVE")?;
6123                }
6124                if !matches!(s.cmd, PolicyCmd::All) {
6125                    let w = match s.cmd {
6126                        PolicyCmd::Select => "SELECT",
6127                        PolicyCmd::Insert => "INSERT",
6128                        PolicyCmd::Update => "UPDATE",
6129                        PolicyCmd::Delete => "DELETE",
6130                        PolicyCmd::All => unreachable!(),
6131                    };
6132                    write!(f, " FOR {w}")?;
6133                }
6134                if !s.roles.is_empty() {
6135                    write!(f, " TO {}", s.roles.join(", "))?;
6136                }
6137                if let Some(u) = &s.using {
6138                    write!(f, " USING ({u})")?;
6139                }
6140                if let Some(c) = &s.with_check {
6141                    write!(f, " WITH CHECK ({c})")?;
6142                }
6143                Ok(())
6144            }
6145            Self::AlterPolicy(s) => {
6146                write!(
6147                    f,
6148                    "ALTER POLICY {} ON {}",
6149                    quote_ident(&s.name),
6150                    quote_ident(&s.table)
6151                )?;
6152                if let Some(nn) = &s.rename_to {
6153                    return write!(f, " RENAME TO {}", quote_ident(nn));
6154                }
6155                if let Some(roles) = &s.roles {
6156                    write!(f, " TO {}", roles.join(", "))?;
6157                }
6158                if let Some(u) = &s.using {
6159                    write!(f, " USING ({u})")?;
6160                }
6161                if let Some(c) = &s.with_check {
6162                    write!(f, " WITH CHECK ({c})")?;
6163                }
6164                Ok(())
6165            }
6166            Self::DropPolicy(s) => {
6167                f.write_str("DROP POLICY ")?;
6168                if s.if_exists {
6169                    f.write_str("IF EXISTS ")?;
6170                }
6171                write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
6172            }
6173            Self::ShowUsers => f.write_str("SHOW USERS"),
6174            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
6175            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
6176            Self::CreateSubscription(s) => {
6177                write!(
6178                    f,
6179                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
6180                    quote_ident(&s.name),
6181                    s.conn_str.replace('\'', "''")
6182                )?;
6183                for (i, p) in s.publications.iter().enumerate() {
6184                    if i > 0 {
6185                        f.write_str(", ")?;
6186                    }
6187                    write!(f, "{}", quote_ident(p))?;
6188                }
6189                Ok(())
6190            }
6191            Self::DropSubscription { name, if_exists } => {
6192                let opt = if *if_exists { "IF EXISTS " } else { "" };
6193                write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
6194            }
6195            Self::WaitForWalPosition { pos, timeout_ms } => {
6196                write!(f, "WAIT FOR WAL POSITION {pos}")?;
6197                if let Some(ms) = timeout_ms {
6198                    write!(f, " WITH TIMEOUT {ms}")?;
6199                }
6200                Ok(())
6201            }
6202            Self::RenameTables(pairs) => {
6203                f.write_str("RENAME TABLE ")?;
6204                for (i, (from, to)) in pairs.iter().enumerate() {
6205                    if i > 0 {
6206                        f.write_str(", ")?;
6207                    }
6208                    write!(f, "{} TO {}", quote_ident(from), quote_ident(to))?;
6209                }
6210                Ok(())
6211            }
6212            Self::Analyze(None) => f.write_str("ANALYZE"),
6213            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
6214            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
6215            Self::Explain(e) => {
6216                if e.suggest {
6217                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
6218                } else if e.analyze {
6219                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
6220                } else {
6221                    write!(f, "EXPLAIN {}", e.inner)
6222                }
6223            }
6224            Self::AlterIndex(a) => {
6225                write!(f, "ALTER INDEX ")?;
6226                match &a.target {
6227                    // Parameters are consumed, not stored; the shortest
6228                    // faithful spelling.
6229                    AlterIndexTarget::StorageParams => {
6230                        write!(f, "{} SET ()", quote_ident(&a.name))
6231                    }
6232                    AlterIndexTarget::Rebuild { encoding } => {
6233                        write!(f, "{} REBUILD", quote_ident(&a.name))?;
6234                        if let Some(enc) = encoding {
6235                            write!(f, " WITH (encoding = {enc})")?;
6236                        }
6237                        Ok(())
6238                    }
6239                    AlterIndexTarget::Rename { new, if_exists } => {
6240                        if *if_exists {
6241                            f.write_str("IF EXISTS ")?;
6242                        }
6243                        write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
6244                    }
6245                }
6246            }
6247            Self::AlterTable(a) => {
6248                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
6249                for (i, t) in a.targets.iter().enumerate() {
6250                    if i > 0 {
6251                        f.write_str(", ")?;
6252                    }
6253                    fmt_alter_target(f, t)?;
6254                }
6255                Ok(())
6256            }
6257            Self::CreatePublication(p) => {
6258                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
6259                match &p.scope {
6260                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
6261                    PublicationScope::ForTables(ts) => {
6262                        f.write_str(" FOR TABLE ")?;
6263                        for (i, t) in ts.iter().enumerate() {
6264                            if i > 0 {
6265                                f.write_str(", ")?;
6266                            }
6267                            write!(f, "{}", quote_ident(t))?;
6268                        }
6269                        Ok(())
6270                    }
6271                    PublicationScope::TablesInSchema(schema) => {
6272                        write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
6273                        Ok(())
6274                    }
6275                    PublicationScope::AllTablesExcept(ts) => {
6276                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
6277                        for (i, t) in ts.iter().enumerate() {
6278                            if i > 0 {
6279                                f.write_str(", ")?;
6280                            }
6281                            write!(f, "{}", quote_ident(t))?;
6282                        }
6283                        Ok(())
6284                    }
6285                }
6286            }
6287            Self::CreateExtension(name) => {
6288                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
6289            }
6290            Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
6291            Self::DropPublication { name, if_exists } => {
6292                let opt = if *if_exists { "IF EXISTS " } else { "" };
6293                write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
6294            }
6295            Self::SetParameter { name, value, local } => {
6296                write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
6297                match value {
6298                    SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
6299                    SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
6300                    SetValue::Default => f.write_str("DEFAULT"),
6301                }
6302            }
6303            Self::SetTransaction { modes } => {
6304                f.write_str("SET TRANSACTION")?;
6305                if let Some(isolation) = modes.isolation {
6306                    let name = match isolation {
6307                        IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
6308                        IsolationLevel::ReadCommitted => "READ COMMITTED",
6309                        IsolationLevel::RepeatableRead => "REPEATABLE READ",
6310                        IsolationLevel::Serializable => "SERIALIZABLE",
6311                    };
6312                    write!(f, " ISOLATION LEVEL {name}")?;
6313                }
6314                match modes.read_only {
6315                    Some(true) => f.write_str(" READ ONLY")?,
6316                    Some(false) => f.write_str(" READ WRITE")?,
6317                    None => {}
6318                }
6319                Ok(())
6320            }
6321            Self::ShowParameter(name) => write!(f, "SHOW {name}"),
6322            Self::SetUserVars(assigns, _) => {
6323                f.write_str("SET ")?;
6324                for (i, (name, value)) in assigns.iter().enumerate() {
6325                    if i > 0 {
6326                        f.write_str(", ")?;
6327                    }
6328                    write!(f, "@{name} = {value}")?;
6329                }
6330                Ok(())
6331            }
6332            Self::SetParameterList(pairs) => {
6333                f.write_str("SET ")?;
6334                for (i, (name, value)) in pairs.iter().enumerate() {
6335                    if i > 0 {
6336                        f.write_str(", ")?;
6337                    }
6338                    write!(f, "{name} = ")?;
6339                    match value {
6340                        SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
6341                        SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
6342                        SetValue::Default => f.write_str("DEFAULT")?,
6343                    }
6344                }
6345                Ok(())
6346            }
6347            Self::ResetParameter(None) => f.write_str("RESET ALL"),
6348            Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
6349            Self::CreateFunction(s) => s.fmt(f),
6350            Self::CreateTrigger(s) => s.fmt(f),
6351            Self::DropTrigger {
6352                name,
6353                table,
6354                if_exists,
6355            } => {
6356                f.write_str("DROP TRIGGER ")?;
6357                if *if_exists {
6358                    f.write_str("IF EXISTS ")?;
6359                }
6360                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6361            }
6362            Self::DropFunction {
6363                name,
6364                args,
6365                if_exists,
6366            } => {
6367                f.write_str("DROP FUNCTION ")?;
6368                if *if_exists {
6369                    f.write_str("IF EXISTS ")?;
6370                }
6371                write!(f, "{}", quote_ident(name))?;
6372                if let Some(a) = args {
6373                    write!(f, "({})", a.join(", "))?;
6374                }
6375                Ok(())
6376            }
6377            Self::CreateSequence(s) => s.fmt(f),
6378            Self::AlterSequence(s) => s.fmt(f),
6379            Self::DropSequence { names, if_exists } => {
6380                f.write_str("DROP SEQUENCE ")?;
6381                if *if_exists {
6382                    f.write_str("IF EXISTS ")?;
6383                }
6384                for (i, n) in names.iter().enumerate() {
6385                    if i > 0 {
6386                        f.write_str(", ")?;
6387                    }
6388                    write!(f, "{}", quote_ident(n))?;
6389                }
6390                Ok(())
6391            }
6392            Self::CreateView(v) => v.fmt(f),
6393            Self::DropView { names, if_exists } => {
6394                f.write_str("DROP VIEW ")?;
6395                if *if_exists {
6396                    f.write_str("IF EXISTS ")?;
6397                }
6398                for (i, n) in names.iter().enumerate() {
6399                    if i > 0 {
6400                        f.write_str(", ")?;
6401                    }
6402                    write!(f, "{}", quote_ident(n))?;
6403                }
6404                Ok(())
6405            }
6406            Self::CreateMaterializedView(v) => v.fmt(f),
6407            Self::RefreshMaterializedView { name, with_data } => {
6408                write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
6409                if !*with_data {
6410                    f.write_str(" WITH NO DATA")?;
6411                }
6412                Ok(())
6413            }
6414            Self::DropMaterializedView { names, if_exists } => {
6415                f.write_str("DROP MATERIALIZED VIEW ")?;
6416                if *if_exists {
6417                    f.write_str("IF EXISTS ")?;
6418                }
6419                for (i, n) in names.iter().enumerate() {
6420                    if i > 0 {
6421                        f.write_str(", ")?;
6422                    }
6423                    write!(f, "{}", quote_ident(n))?;
6424                }
6425                Ok(())
6426            }
6427            Self::CreateType(t) => t.fmt(f),
6428            Self::CommentOn {
6429                kind,
6430                name,
6431                comment,
6432            } => {
6433                let body = match comment {
6434                    Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
6435                    None => "NULL".into(),
6436                };
6437                write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
6438            }
6439            Self::AlterTypeRenameValue {
6440                type_name,
6441                old,
6442                new,
6443            } => write!(
6444                f,
6445                "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
6446                quote_ident(type_name),
6447                old.replace('\'', "''"),
6448                new.replace('\'', "''")
6449            ),
6450            Self::AlterTypeAddValue {
6451                type_name,
6452                label,
6453                if_not_exists,
6454                position,
6455            } => {
6456                write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6457                if *if_not_exists {
6458                    write!(f, "IF NOT EXISTS ")?;
6459                }
6460                write!(f, "'{label}'")?;
6461                if let Some((is_before, anchor)) = position {
6462                    write!(
6463                        f,
6464                        " {} '{anchor}'",
6465                        if *is_before { "BEFORE" } else { "AFTER" }
6466                    )?;
6467                }
6468                Ok(())
6469            }
6470            Self::DropType { names, if_exists } => {
6471                f.write_str("DROP TYPE ")?;
6472                if *if_exists {
6473                    f.write_str("IF EXISTS ")?;
6474                }
6475                for (i, n) in names.iter().enumerate() {
6476                    if i > 0 {
6477                        f.write_str(", ")?;
6478                    }
6479                    write!(f, "{}", quote_ident(n))?;
6480                }
6481                Ok(())
6482            }
6483            Self::CreateDomain(d) => d.fmt(f),
6484            Self::DropDomain { names, if_exists } => {
6485                f.write_str("DROP DOMAIN ")?;
6486                if *if_exists {
6487                    f.write_str("IF EXISTS ")?;
6488                }
6489                for (i, n) in names.iter().enumerate() {
6490                    if i > 0 {
6491                        f.write_str(", ")?;
6492                    }
6493                    write!(f, "{}", quote_ident(n))?;
6494                }
6495                Ok(())
6496            }
6497            Self::CreateSchema {
6498                name,
6499                if_not_exists,
6500            } => {
6501                f.write_str("CREATE SCHEMA ")?;
6502                if *if_not_exists {
6503                    f.write_str("IF NOT EXISTS ")?;
6504                }
6505                write!(f, "{}", quote_ident(name))
6506            }
6507            Self::DropSchema { names, if_exists } => {
6508                f.write_str("DROP SCHEMA ")?;
6509                if *if_exists {
6510                    f.write_str("IF EXISTS ")?;
6511                }
6512                for (i, n) in names.iter().enumerate() {
6513                    if i > 0 {
6514                        f.write_str(", ")?;
6515                    }
6516                    write!(f, "{}", quote_ident(n))?;
6517                }
6518                Ok(())
6519            }
6520            Self::CreateRule(r) => {
6521                f.write_str("CREATE ")?;
6522                if r.or_replace {
6523                    f.write_str("OR REPLACE ")?;
6524                }
6525                write!(
6526                    f,
6527                    "RULE {} AS ON {} TO {}",
6528                    quote_ident(&r.name),
6529                    r.event,
6530                    quote_ident(&r.table)
6531                )?;
6532                if let Some(w) = &r.when_condition {
6533                    write!(f, " WHERE {w}")?;
6534                }
6535                f.write_str(if r.instead {
6536                    " DO INSTEAD "
6537                } else {
6538                    " DO ALSO "
6539                })?;
6540                if r.commands.is_empty() {
6541                    f.write_str("NOTHING")?;
6542                } else if r.commands.len() == 1 {
6543                    write!(f, "{}", r.commands[0])?;
6544                } else {
6545                    f.write_str("(")?;
6546                    for (i, c) in r.commands.iter().enumerate() {
6547                        if i > 0 {
6548                            f.write_str("; ")?;
6549                        }
6550                        write!(f, "{c}")?;
6551                    }
6552                    f.write_str(")")?;
6553                }
6554                Ok(())
6555            }
6556            Self::DropRule {
6557                name,
6558                table,
6559                if_exists,
6560            } => {
6561                f.write_str("DROP RULE ")?;
6562                if *if_exists {
6563                    f.write_str("IF EXISTS ")?;
6564                }
6565                write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6566            }
6567        }
6568    }
6569}
6570
6571impl fmt::Display for CreateDomainStatement {
6572    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6573        write!(
6574            f,
6575            "CREATE DOMAIN {} AS {}",
6576            quote_ident(&self.name),
6577            self.base_type
6578        )?;
6579        if let Some(d) = &self.default {
6580            write!(f, " DEFAULT {d}")?;
6581        }
6582        if self.not_null {
6583            f.write_str(" NOT NULL")?;
6584        }
6585        for c in &self.checks {
6586            write!(f, " CHECK ({c})")?;
6587        }
6588        Ok(())
6589    }
6590}
6591
6592impl fmt::Display for CreateTypeStatement {
6593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6594        write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6595        match &self.kind {
6596            TypeKind::Enum { labels } => {
6597                f.write_str("ENUM (")?;
6598                for (i, l) in labels.iter().enumerate() {
6599                    if i > 0 {
6600                        f.write_str(", ")?;
6601                    }
6602                    write!(f, "'{}'", l.replace('\'', "''"))?;
6603                }
6604                f.write_str(")")
6605            }
6606            TypeKind::Composite { fields, .. } => {
6607                f.write_str("(")?;
6608                for (i, (n, t)) in fields.iter().enumerate() {
6609                    if i > 0 {
6610                        f.write_str(", ")?;
6611                    }
6612                    write!(f, "{} {}", quote_ident(n), t)?;
6613                }
6614                f.write_str(")")
6615            }
6616        }
6617    }
6618}
6619
6620impl fmt::Display for CreateMaterializedViewStatement {
6621    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6622        f.write_str("CREATE MATERIALIZED VIEW ")?;
6623        if self.if_not_exists {
6624            f.write_str("IF NOT EXISTS ")?;
6625        }
6626        write!(f, "{}", quote_ident(&self.name))?;
6627        if !self.columns.is_empty() {
6628            f.write_str(" (")?;
6629            for (i, c) in self.columns.iter().enumerate() {
6630                if i > 0 {
6631                    f.write_str(", ")?;
6632                }
6633                write!(f, "{}", quote_ident(c))?;
6634            }
6635            f.write_str(")")?;
6636        }
6637        write!(f, " AS {}", self.body)?;
6638        if !self.with_data {
6639            f.write_str(" WITH NO DATA")?;
6640        }
6641        Ok(())
6642    }
6643}
6644
6645impl fmt::Display for CreateViewStatement {
6646    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6647        f.write_str("CREATE ")?;
6648        if self.or_replace {
6649            f.write_str("OR REPLACE ")?;
6650        }
6651        if self.temporary {
6652            f.write_str("TEMPORARY ")?;
6653        }
6654        f.write_str("VIEW ")?;
6655        if self.if_not_exists {
6656            f.write_str("IF NOT EXISTS ")?;
6657        }
6658        write!(f, "{}", quote_ident(&self.name))?;
6659        if !self.columns.is_empty() {
6660            f.write_str(" (")?;
6661            for (i, c) in self.columns.iter().enumerate() {
6662                if i > 0 {
6663                    f.write_str(", ")?;
6664                }
6665                write!(f, "{}", quote_ident(c))?;
6666            }
6667            f.write_str(")")?;
6668        }
6669        write!(f, " AS {}", self.body)?;
6670        match self.check_option {
6671            Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6672            Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6673            None => Ok(()),
6674        }
6675    }
6676}
6677
6678impl fmt::Display for CreateSequenceStatement {
6679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6680        f.write_str("CREATE ")?;
6681        if self.temporary {
6682            f.write_str("TEMPORARY ")?;
6683        }
6684        f.write_str("SEQUENCE ")?;
6685        if self.if_not_exists {
6686            f.write_str("IF NOT EXISTS ")?;
6687        }
6688        write!(f, "{}", quote_ident(&self.name))?;
6689        if let Some(dt) = self.data_type {
6690            write!(f, " AS {dt}")?;
6691        }
6692        write_sequence_options(f, &self.options)
6693    }
6694}
6695
6696impl fmt::Display for AlterSequenceStatement {
6697    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6698        f.write_str("ALTER SEQUENCE ")?;
6699        if self.if_exists {
6700            f.write_str("IF EXISTS ")?;
6701        }
6702        write!(f, "{}", quote_ident(&self.name))?;
6703        write_sequence_options(f, &self.options)
6704    }
6705}
6706
6707impl fmt::Display for SequenceDataType {
6708    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6709        f.write_str(match self {
6710            Self::SmallInt => "smallint",
6711            Self::Int => "integer",
6712            Self::BigInt => "bigint",
6713        })
6714    }
6715}
6716
6717fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6718    if let Some(n) = o.increment {
6719        write!(f, " INCREMENT BY {n}")?;
6720    }
6721    match o.min_value {
6722        Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6723        Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6724        None => {}
6725    }
6726    match o.max_value {
6727        Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6728        Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6729        None => {}
6730    }
6731    if let Some(n) = o.start {
6732        write!(f, " START WITH {n}")?;
6733    }
6734    match o.restart {
6735        Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6736        Some(None) => f.write_str(" RESTART")?,
6737        None => {}
6738    }
6739    if let Some(n) = o.cache {
6740        write!(f, " CACHE {n}")?;
6741    }
6742    match o.cycle {
6743        Some(true) => f.write_str(" CYCLE")?,
6744        Some(false) => f.write_str(" NO CYCLE")?,
6745        None => {}
6746    }
6747    if let Some(ob) = &o.owned_by {
6748        match ob {
6749            SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6750            SequenceOwnedBy::Column { table, column } => {
6751                write!(
6752                    f,
6753                    " OWNED BY {}.{}",
6754                    quote_ident(table),
6755                    quote_ident(column)
6756                )?;
6757            }
6758        }
6759    }
6760    Ok(())
6761}
6762
6763impl fmt::Display for CreateFunctionStatement {
6764    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6765        f.write_str("CREATE ")?;
6766        if self.or_replace {
6767            f.write_str("OR REPLACE ")?;
6768        }
6769        write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6770        for (i, arg) in self.args.iter().enumerate() {
6771            if i > 0 {
6772                f.write_str(", ")?;
6773            }
6774            match arg.mode {
6775                FunctionArgMode::In => {}
6776                FunctionArgMode::Out => f.write_str("OUT ")?,
6777                FunctionArgMode::InOut => f.write_str("INOUT ")?,
6778            }
6779            if let Some(name) = &arg.name {
6780                write!(f, "{} ", quote_ident(name))?;
6781            }
6782            match &arg.ty {
6783                FunctionArgType::Typed(t) => write!(f, "{t}")?,
6784                FunctionArgType::Raw(s) => f.write_str(s)?,
6785            }
6786        }
6787        f.write_str(") RETURNS ")?;
6788        match &self.returns {
6789            FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6790            FunctionReturn::Void => f.write_str("VOID")?,
6791            FunctionReturn::Type(t) => write!(f, "{t}")?,
6792            FunctionReturn::Other(s) => f.write_str(s)?,
6793        }
6794        write!(f, " LANGUAGE {} AS $$", self.language)?;
6795        match &self.body {
6796            FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6797            FunctionBody::Raw(s) => f.write_str(s)?,
6798        }
6799        f.write_str("$$")
6800    }
6801}
6802
6803impl fmt::Display for PlPgSqlBlock {
6804    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6805        if !self.declarations.is_empty() {
6806            f.write_str("DECLARE\n")?;
6807            for d in &self.declarations {
6808                write!(f, "  {} ", quote_ident(&d.name))?;
6809                match &d.ty {
6810                    FunctionArgType::Typed(t) => write!(f, "{t}")?,
6811                    FunctionArgType::Raw(s) => f.write_str(s)?,
6812                }
6813                if let Some(e) = &d.default {
6814                    write!(f, " := {e}")?;
6815                }
6816                f.write_str(";\n")?;
6817            }
6818        }
6819        f.write_str("BEGIN\n")?;
6820        for stmt in &self.statements {
6821            writeln!(f, "  {stmt};")?;
6822        }
6823        // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6824        // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6825        // parsed block through it — so every exception handler a function
6826        // declared was thrown away AT STORE TIME. The block executed fine while
6827        // it was still an AST (a DO block never round-trips through text), which
6828        // is why only functions and triggers lost theirs.
6829        if !self.exception_handlers.is_empty() {
6830            f.write_str("EXCEPTION\n")?;
6831            for h in &self.exception_handlers {
6832                writeln!(f, "  WHEN {} THEN", h.conditions.join(" OR "))?;
6833                for stmt in &h.body {
6834                    writeln!(f, "    {stmt};")?;
6835                }
6836            }
6837        }
6838        f.write_str("END")
6839    }
6840}
6841
6842impl fmt::Display for PlPgSqlStmt {
6843    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6844        match self {
6845            Self::Assign { target, value } => write!(f, "{target} := {value}"),
6846            Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6847            Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6848            Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6849            Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6850            Self::Return(t) => match t {
6851                ReturnTarget::New => f.write_str("RETURN NEW"),
6852                ReturnTarget::Old => f.write_str("RETURN OLD"),
6853                ReturnTarget::Null => f.write_str("RETURN NULL"),
6854                ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6855            },
6856            Self::If {
6857                branches,
6858                else_branch,
6859            } => {
6860                for (i, (cond, body)) in branches.iter().enumerate() {
6861                    if i == 0 {
6862                        write!(f, "IF {cond} THEN ")?;
6863                    } else {
6864                        write!(f, " ELSIF {cond} THEN ")?;
6865                    }
6866                    for (j, s) in body.iter().enumerate() {
6867                        if j > 0 {
6868                            f.write_str("; ")?;
6869                        }
6870                        write!(f, "{s}")?;
6871                    }
6872                }
6873                if !else_branch.is_empty() {
6874                    f.write_str(" ELSE ")?;
6875                    for (j, s) in else_branch.iter().enumerate() {
6876                        if j > 0 {
6877                            f.write_str("; ")?;
6878                        }
6879                        write!(f, "{s}")?;
6880                    }
6881                }
6882                f.write_str(" END IF")
6883            }
6884            Self::Raise {
6885                level,
6886                message,
6887                args,
6888            } => {
6889                let lvl = match level {
6890                    RaiseLevel::Notice => "NOTICE",
6891                    RaiseLevel::Warning => "WARNING",
6892                    RaiseLevel::Info => "INFO",
6893                    RaiseLevel::Log => "LOG",
6894                    RaiseLevel::Debug => "DEBUG",
6895                    RaiseLevel::Exception => "EXCEPTION",
6896                };
6897                write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6898                for a in args {
6899                    write!(f, ", {a}")?;
6900                }
6901                Ok(())
6902            }
6903            Self::EmbeddedSql(s) => write!(f, "{s}"),
6904            Self::Assert { condition, message } => {
6905                write!(f, "ASSERT {condition}")?;
6906                if let Some(m) = message {
6907                    write!(f, ", {m}")?;
6908                }
6909                Ok(())
6910            }
6911            Self::While { condition, body } => {
6912                writeln!(f, "WHILE {condition} LOOP")?;
6913                for s in body {
6914                    writeln!(f, "  {s};")?;
6915                }
6916                f.write_str("END LOOP")
6917            }
6918            Self::ForRange {
6919                var,
6920                start,
6921                end,
6922                reverse,
6923                body,
6924            } => {
6925                write!(f, "FOR {var} IN ")?;
6926                if *reverse {
6927                    f.write_str("REVERSE ")?;
6928                }
6929                writeln!(f, "{start}..{end} LOOP")?;
6930                for s in body {
6931                    writeln!(f, "  {s};")?;
6932                }
6933                f.write_str("END LOOP")
6934            }
6935            Self::Loop { body } => {
6936                writeln!(f, "LOOP")?;
6937                for s in body {
6938                    writeln!(f, "  {s};")?;
6939                }
6940                f.write_str("END LOOP")
6941            }
6942            Self::Exit { when } => {
6943                f.write_str("EXIT")?;
6944                if let Some(c) = when {
6945                    write!(f, " WHEN {c}")?;
6946                }
6947                Ok(())
6948            }
6949            Self::Continue { when } => {
6950                f.write_str("CONTINUE")?;
6951                if let Some(c) = when {
6952                    write!(f, " WHEN {c}")?;
6953                }
6954                Ok(())
6955            }
6956            Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
6957            Self::ForQuery { var, query, body } => {
6958                writeln!(f, "FOR {var} IN ({query}) LOOP")?;
6959                for s in body {
6960                    writeln!(f, "  {s};")?;
6961                }
6962                f.write_str("END LOOP")
6963            }
6964            Self::ForExecute {
6965                var,
6966                sql_expr,
6967                body,
6968            } => {
6969                writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
6970                for s in body {
6971                    writeln!(f, "  {s};")?;
6972                }
6973                f.write_str("END LOOP")
6974            }
6975        }
6976    }
6977}
6978
6979impl fmt::Display for AssignTarget {
6980    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6981        match self {
6982            Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
6983            Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
6984            Self::Local(n) => f.write_str(n),
6985        }
6986    }
6987}
6988
6989impl fmt::Display for CreateTriggerStatement {
6990    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6991        f.write_str("CREATE ")?;
6992        if self.or_replace {
6993            f.write_str("OR REPLACE ")?;
6994        }
6995        write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
6996        match self.timing {
6997            TriggerTiming::Before => f.write_str("BEFORE")?,
6998            TriggerTiming::After => f.write_str("AFTER")?,
6999            TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
7000        }
7001        for (i, e) in self.events.iter().enumerate() {
7002            if i == 0 {
7003                f.write_str(" ")?;
7004            } else {
7005                f.write_str(" OR ")?;
7006            }
7007            match e {
7008                TriggerEvent::Insert => f.write_str("INSERT")?,
7009                TriggerEvent::Update => {
7010                    f.write_str("UPDATE")?;
7011                    if !self.update_columns.is_empty() {
7012                        f.write_str(" OF ")?;
7013                        for (j, col) in self.update_columns.iter().enumerate() {
7014                            if j > 0 {
7015                                f.write_str(", ")?;
7016                            }
7017                            f.write_str(&quote_ident(col))?;
7018                        }
7019                    }
7020                }
7021                TriggerEvent::Delete => f.write_str("DELETE")?,
7022                TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
7023            }
7024        }
7025        write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
7026        match self.for_each {
7027            TriggerForEach::Row => f.write_str("ROW")?,
7028            TriggerForEach::Statement => f.write_str("STATEMENT")?,
7029        }
7030        write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
7031    }
7032}
7033
7034impl fmt::Display for CreateIndexStatement {
7035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7036        if self.is_unique {
7037            f.write_str("CREATE UNIQUE INDEX ")?;
7038        } else {
7039            f.write_str("CREATE INDEX ")?;
7040        }
7041        if self.if_not_exists {
7042            f.write_str("IF NOT EXISTS ")?;
7043        }
7044        write!(
7045            f,
7046            "{} ON {} ",
7047            quote_ident(&self.name),
7048            quote_ident(&self.table)
7049        )?;
7050        match self.method {
7051            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
7052            IndexMethod::Brin => f.write_str("USING brin ")?,
7053            IndexMethod::Gin => f.write_str("USING gin ")?,
7054            IndexMethod::BTree => {}
7055        }
7056        if let Some(expr) = &self.expression {
7057            write!(f, "({})", expr)?;
7058        } else if self.extra_columns.is_empty() {
7059            // v7.15.0 — preserve operator class on round-trip
7060            // (`(col opclass)`) so WAL replay reconstructs the
7061            // engine-routing intent (e.g. `gin_trgm_ops` →
7062            // trigram-GIN build path).
7063            if let Some(op) = &self.opclass {
7064                write!(f, "({} {})", quote_ident(&self.column), op)?;
7065            } else {
7066                write!(f, "({})", quote_ident(&self.column))?;
7067            }
7068        } else {
7069            // v7.9.14 — multi-column key. Emit each column quoted
7070            // so the round-tripped form re-parses to identical AST.
7071            f.write_str("(")?;
7072            write!(f, "{}", quote_ident(&self.column))?;
7073            for c in &self.extra_columns {
7074                write!(f, ", {}", quote_ident(c))?;
7075            }
7076            f.write_str(")")?;
7077        }
7078        if !self.included_columns.is_empty() {
7079            f.write_str(" INCLUDE (")?;
7080            for (i, c) in self.included_columns.iter().enumerate() {
7081                if i > 0 {
7082                    f.write_str(", ")?;
7083                }
7084                write!(f, "{}", quote_ident(c))?;
7085            }
7086            f.write_str(")")?;
7087        }
7088        if let Some(pred) = &self.partial_predicate {
7089            write!(f, " WHERE {}", pred)?;
7090        }
7091        Ok(())
7092    }
7093}
7094
7095impl fmt::Display for CreateTableStatement {
7096    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7097        f.write_str("CREATE TABLE ")?;
7098        if self.if_not_exists {
7099            f.write_str("IF NOT EXISTS ")?;
7100        }
7101        write!(f, "{}", quote_ident(&self.name))?;
7102        // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
7103        // no column list and no constraints; the table inherits its
7104        // columns from the parent at engine-DDL time.
7105        if let Some(spec) = &self.partition_of {
7106            write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
7107            return match &spec.bounds {
7108                PartitionOfBoundsAst::Range { lower, upper } => {
7109                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7110                }
7111                PartitionOfBoundsAst::List { values } => {
7112                    f.write_str("FOR VALUES IN (")?;
7113                    for (i, v) in values.iter().enumerate() {
7114                        if i > 0 {
7115                            f.write_str(", ")?;
7116                        }
7117                        write!(f, "{}", v)?;
7118                    }
7119                    f.write_str(")")
7120                }
7121                PartitionOfBoundsAst::Hash { modulus, remainder } => {
7122                    write!(
7123                        f,
7124                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7125                        modulus, remainder
7126                    )
7127                }
7128                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7129            };
7130        }
7131        f.write_str(" (")?;
7132        for (i, col) in self.columns.iter().enumerate() {
7133            if i > 0 {
7134                f.write_str(", ")?;
7135            }
7136            write!(f, "{col}")?;
7137        }
7138        // v7.6.0 — render FK constraints in table-level form, after
7139        // the column list. WAL replay round-trips through Display, so
7140        // every FK must serialise here for replay to reconstruct the
7141        // schema bit-for-bit.
7142        for fk in &self.foreign_keys {
7143            f.write_str(", ")?;
7144            write!(f, "{fk}")?;
7145        }
7146        // v7.13.0 — render table-level constraints (PRIMARY KEY /
7147        // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
7148        // column-level UNIQUE / CHECK get lifted to this list at
7149        // parse time, so emitting only here avoids double-counting.
7150        for tc in &self.table_constraints {
7151            f.write_str(", ")?;
7152            write!(f, "{tc}")?;
7153        }
7154        f.write_str(")")?;
7155        // v7.37.6-B — partition-parent suffix renders after the
7156        // closing column-list paren, before the optional MySQL
7157        // table-options tail (which Display doesn't currently emit).
7158        if let Some(spec) = &self.partition_by {
7159            f.write_str(" PARTITION BY ")?;
7160            match spec.kind {
7161                PartitionKindAst::Range => f.write_str("RANGE ")?,
7162                PartitionKindAst::List => f.write_str("LIST ")?,
7163                PartitionKindAst::Hash => f.write_str("HASH ")?,
7164            }
7165            f.write_str("(")?;
7166            for (i, col) in spec.key_columns.iter().enumerate() {
7167                if i > 0 {
7168                    f.write_str(", ")?;
7169                }
7170                f.write_str(&quote_ident(col))?;
7171            }
7172            f.write_str(")")?;
7173        }
7174        Ok(())
7175    }
7176}
7177
7178fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
7179    match t {
7180        AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
7181        AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
7182            write!(f, "REPLICA IDENTITY USING INDEX {index}")
7183        }
7184        AlterTableTarget::Inherit { parent, detach } => {
7185            if *detach {
7186                write!(f, "NO INHERIT {parent}")
7187            } else {
7188                write!(f, "INHERIT {parent}")
7189            }
7190        }
7191        AlterTableTarget::SetHotTierBytes(n) => {
7192            write!(f, "SET hot_tier_bytes = {n}")
7193        }
7194        AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
7195        AlterTableTarget::DropForeignKey { name, if_exists } => {
7196            f.write_str("DROP CONSTRAINT ")?;
7197            if *if_exists {
7198                f.write_str("IF EXISTS ")?;
7199            }
7200            write!(f, "{}", quote_ident(name))
7201        }
7202        AlterTableTarget::DropIndex { name, if_exists } => {
7203            f.write_str("DROP INDEX ")?;
7204            if *if_exists {
7205                f.write_str("IF EXISTS ")?;
7206            }
7207            write!(f, "{}", quote_ident(name))
7208        }
7209        AlterTableTarget::ModifyColumn {
7210            column,
7211            rename_to,
7212            definition,
7213            position,
7214        } => {
7215            if let Some(new) = rename_to {
7216                write!(
7217                    f,
7218                    "CHANGE COLUMN {} {} {}",
7219                    quote_ident(column),
7220                    quote_ident(new),
7221                    definition.ty
7222                )?;
7223            } else {
7224                write!(f, "MODIFY COLUMN {} {}", quote_ident(column), definition.ty)?;
7225            }
7226            if !definition.nullable {
7227                f.write_str(" NOT NULL")?;
7228            }
7229            write_column_position(f, position.as_ref())
7230        }
7231        AlterTableTarget::RenameIndex { old, new } => {
7232            write!(
7233                f,
7234                "RENAME INDEX {} TO {}",
7235                quote_ident(old),
7236                quote_ident(new)
7237            )
7238        }
7239        AlterTableTarget::SetTableAutoIncrement(n) => write!(f, "AUTO_INCREMENT = {n}"),
7240        AlterTableTarget::SetEngine(name) => write!(f, "ENGINE = {name}"),
7241        AlterTableTarget::ConvertToCharacterSet { charset, collate } => {
7242            write!(f, "CONVERT TO CHARACTER SET {charset}")?;
7243            if let Some(c) = collate {
7244                write!(f, " COLLATE {c}")?;
7245            }
7246            Ok(())
7247        }
7248        AlterTableTarget::AddColumn {
7249            column,
7250            if_not_exists,
7251            position,
7252        } => {
7253            f.write_str("ADD COLUMN ")?;
7254            if *if_not_exists {
7255                f.write_str("IF NOT EXISTS ")?;
7256            }
7257            write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
7258            if !column.nullable {
7259                f.write_str(" NOT NULL")?;
7260            }
7261            if let Some(d) = &column.default {
7262                write!(f, " DEFAULT {d}")?;
7263            }
7264            if column.auto_increment {
7265                f.write_str(" AUTO_INCREMENT")?;
7266            }
7267            if column.is_primary_key {
7268                f.write_str(" PRIMARY KEY")?;
7269            }
7270            Ok(())
7271        }
7272        AlterTableTarget::AlterColumnType {
7273            column,
7274            new_type,
7275            using,
7276            collation,
7277        } => {
7278            write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
7279            if let Some((_, name)) = collation {
7280                write!(f, " COLLATE {}", quote_ident(name))?;
7281            }
7282            if let Some(u) = using {
7283                write!(f, " USING {u}")?;
7284            }
7285            Ok(())
7286        }
7287        AlterTableTarget::DropColumn {
7288            column,
7289            if_exists,
7290            cascade,
7291        } => {
7292            f.write_str("DROP COLUMN ")?;
7293            if *if_exists {
7294                f.write_str("IF EXISTS ")?;
7295            }
7296            write!(f, "{}", quote_ident(column))?;
7297            if *cascade {
7298                f.write_str(" CASCADE")?;
7299            }
7300            Ok(())
7301        }
7302        AlterTableTarget::AddTableConstraint(tc) => {
7303            write!(f, "ADD {tc}")
7304        }
7305        AlterTableTarget::ValidateConstraint { name } => {
7306            write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
7307        }
7308        AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
7309        AlterTableTarget::ClusterOn { index } => match index {
7310            Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
7311            None => f.write_str("SET WITHOUT CLUSTER"),
7312        },
7313        AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
7314            // Round-trip-safe spelling: re-parsing this form lowers
7315            // back to SetColumnAutoIncrement (the nextval default is
7316            // how pg_dump says "serial").
7317            let seq = seq_name
7318                .clone()
7319                .unwrap_or_else(|| alloc::format!("{column}_seq"));
7320            write!(
7321                f,
7322                "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
7323                quote_ident(column)
7324            )
7325        }
7326        AlterTableTarget::RenameColumn { old, new } => {
7327            write!(
7328                f,
7329                "RENAME COLUMN {} TO {}",
7330                quote_ident(old),
7331                quote_ident(new)
7332            )
7333        }
7334        AlterTableTarget::RenameConstraint { old, new } => {
7335            write!(
7336                f,
7337                "RENAME CONSTRAINT {} TO {}",
7338                quote_ident(old),
7339                quote_ident(new)
7340            )
7341        }
7342        AlterTableTarget::RenameTable { new } => {
7343            write!(f, "RENAME TO {}", quote_ident(new))
7344        }
7345        AlterTableTarget::SetTriggerEnabled { which, enabled } => {
7346            f.write_str(if *enabled {
7347                "ENABLE TRIGGER "
7348            } else {
7349                "DISABLE TRIGGER "
7350            })?;
7351            match which {
7352                TriggerSelector::All => f.write_str("ALL"),
7353                TriggerSelector::Named(n) => f.write_str(&quote_ident(n)),
7354            }
7355        }
7356        AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
7357            (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
7358            (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
7359            (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
7360            (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
7361            (None, None) => Ok(()),
7362        },
7363        AlterTableTarget::AttachPartition { child, bounds } => {
7364            write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
7365            match bounds {
7366                PartitionOfBoundsAst::Range { lower, upper } => {
7367                    write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7368                }
7369                PartitionOfBoundsAst::List { values } => {
7370                    f.write_str("FOR VALUES IN (")?;
7371                    for (i, v) in values.iter().enumerate() {
7372                        if i > 0 {
7373                            f.write_str(", ")?;
7374                        }
7375                        write!(f, "{}", v)?;
7376                    }
7377                    f.write_str(")")
7378                }
7379                PartitionOfBoundsAst::Hash { modulus, remainder } => {
7380                    write!(
7381                        f,
7382                        "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7383                        modulus, remainder
7384                    )
7385                }
7386                PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7387            }
7388        }
7389        AlterTableTarget::DetachPartition {
7390            child,
7391            concurrently,
7392            finalize,
7393        } => {
7394            write!(f, "DETACH PARTITION {}", quote_ident(child))?;
7395            if *concurrently {
7396                f.write_str(" CONCURRENTLY")?;
7397            }
7398            if *finalize {
7399                f.write_str(" FINALIZE")?;
7400            }
7401            Ok(())
7402        }
7403        AlterTableTarget::AlterColumnSetDefault {
7404            column,
7405            default_expr,
7406        } => write!(
7407            f,
7408            "ALTER COLUMN {} SET DEFAULT {}",
7409            quote_ident(column),
7410            default_expr
7411        ),
7412        AlterTableTarget::AlterColumnDropDefault { column } => {
7413            write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
7414        }
7415        AlterTableTarget::AlterColumnSetNotNull { column } => {
7416            write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
7417        }
7418        AlterTableTarget::AlterColumnDropNotNull { column } => {
7419            write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
7420        }
7421        AlterTableTarget::AlterColumnRestart { column, with } => {
7422            write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
7423            if let Some(n) = with {
7424                write!(f, " WITH {n}")?;
7425            }
7426            Ok(())
7427        }
7428        AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
7429            write!(
7430                f,
7431                "ALTER COLUMN {} DROP EXPRESSION{}",
7432                quote_ident(column),
7433                if *if_exists { " IF EXISTS" } else { "" }
7434            )
7435        }
7436        AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
7437            write!(
7438                f,
7439                "ALTER COLUMN {} DROP IDENTITY{}",
7440                quote_ident(column),
7441                if *if_exists { " IF EXISTS" } else { "" }
7442            )
7443        }
7444        AlterTableTarget::AlterColumnSetExpression { column, expr } => {
7445            write!(
7446                f,
7447                "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
7448                quote_ident(column)
7449            )
7450        }
7451    }
7452}
7453
7454impl fmt::Display for TableConstraint {
7455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7456        match self {
7457            Self::PrimaryKey { name, columns, .. } => {
7458                if let Some(n) = name {
7459                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7460                }
7461                f.write_str("PRIMARY KEY (")?;
7462                for (i, c) in columns.iter().enumerate() {
7463                    if i > 0 {
7464                        f.write_str(", ")?;
7465                    }
7466                    f.write_str(&quote_ident(c))?;
7467                }
7468                f.write_str(")")
7469            }
7470            Self::Unique {
7471                name,
7472                columns,
7473                nulls_not_distinct,
7474                ..
7475            } => {
7476                if let Some(n) = name {
7477                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7478                }
7479                f.write_str("UNIQUE ")?;
7480                if *nulls_not_distinct {
7481                    f.write_str("NULLS NOT DISTINCT ")?;
7482                }
7483                f.write_str("(")?;
7484                for (i, c) in columns.iter().enumerate() {
7485                    if i > 0 {
7486                        f.write_str(", ")?;
7487                    }
7488                    f.write_str(&quote_ident(c))?;
7489                }
7490                f.write_str(")")
7491            }
7492            Self::Check {
7493                name,
7494                expr,
7495                not_valid,
7496            } => {
7497                if let Some(n) = name {
7498                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7499                }
7500                write!(f, "CHECK ({expr})")?;
7501                if *not_valid {
7502                    write!(f, " NOT VALID")?;
7503                }
7504                Ok(())
7505            }
7506            Self::Index { name, columns } => {
7507                f.write_str("KEY ")?;
7508                if let Some(n) = name {
7509                    write!(f, "{} ", quote_ident(n))?;
7510                }
7511                f.write_str("(")?;
7512                for (i, c) in columns.iter().enumerate() {
7513                    if i > 0 {
7514                        f.write_str(", ")?;
7515                    }
7516                    f.write_str(&quote_ident(c))?;
7517                }
7518                f.write_str(")")
7519            }
7520            Self::FulltextIndex { name, columns } => {
7521                // Mysqldump emits `FULLTEXT KEY name (cols)` —
7522                // Display rounds back to that shape so dump
7523                // replay reproduces the input verbatim.
7524                f.write_str("FULLTEXT KEY ")?;
7525                if let Some(n) = name {
7526                    write!(f, "{} ", quote_ident(n))?;
7527                }
7528                f.write_str("(")?;
7529                for (i, c) in columns.iter().enumerate() {
7530                    if i > 0 {
7531                        f.write_str(", ")?;
7532                    }
7533                    f.write_str(&quote_ident(c))?;
7534                }
7535                f.write_str(")")
7536            }
7537            Self::Exclude {
7538                name,
7539                method,
7540                elements,
7541            } => {
7542                if let Some(n) = name {
7543                    write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7544                }
7545                f.write_str("EXCLUDE ")?;
7546                if let Some(m) = method {
7547                    write!(f, "USING {m} ")?;
7548                }
7549                f.write_str("(")?;
7550                for (i, (col, op)) in elements.iter().enumerate() {
7551                    if i > 0 {
7552                        f.write_str(", ")?;
7553                    }
7554                    write!(f, "{} WITH {op}", quote_ident(col))?;
7555                }
7556                f.write_str(")")
7557            }
7558        }
7559    }
7560}
7561
7562impl fmt::Display for ForeignKeyConstraint {
7563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7564        if let Some(name) = &self.name {
7565            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7566        }
7567        f.write_str("FOREIGN KEY (")?;
7568        for (i, c) in self.columns.iter().enumerate() {
7569            if i > 0 {
7570                f.write_str(", ")?;
7571            }
7572            f.write_str(&quote_ident(c))?;
7573        }
7574        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7575        if !self.parent_columns.is_empty() {
7576            f.write_str(" (")?;
7577            for (i, c) in self.parent_columns.iter().enumerate() {
7578                if i > 0 {
7579                    f.write_str(", ")?;
7580                }
7581                f.write_str(&quote_ident(c))?;
7582            }
7583            f.write_str(")")?;
7584        }
7585        // Only render non-default actions to keep Display output
7586        // close to user input. SPG's default is RESTRICT (matches
7587        // SQL spec).
7588        if self.on_delete != FkAction::Restrict {
7589            write!(f, " ON DELETE {}", self.on_delete)?;
7590        }
7591        if self.on_update != FkAction::Restrict {
7592            write!(f, " ON UPDATE {}", self.on_update)?;
7593        }
7594        Ok(())
7595    }
7596}
7597
7598impl fmt::Display for FkAction {
7599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7600        match self {
7601            Self::Restrict => f.write_str("RESTRICT"),
7602            Self::Cascade => f.write_str("CASCADE"),
7603            Self::SetNull => f.write_str("SET NULL"),
7604            Self::SetDefault => f.write_str("SET DEFAULT"),
7605            Self::NoAction => f.write_str("NO ACTION"),
7606        }
7607    }
7608}
7609
7610impl fmt::Display for ColumnDef {
7611    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7612        // v7.30.1 (mailrs round-24 class audit) — the type position
7613        // must re-parse to the same ColumnDef: a user-defined type
7614        // reference and the MySQL inline ENUM / SET value lists all
7615        // lower `ty` to Text, so rendering `ty` lost them.
7616        write!(f, "{}", quote_ident(&self.name))?;
7617        if let Some(ut) = &self.user_type_ref {
7618            write!(f, " {}", quote_ident(ut))?;
7619        } else if let Some(variants) = &self.inline_enum_variants {
7620            write_variant_list(f, "ENUM", variants)?;
7621        } else if let Some(variants) = &self.inline_set_variants {
7622            write_variant_list(f, "SET", variants)?;
7623        } else {
7624            write!(f, " {}", self.ty)?;
7625        }
7626        if self.is_unsigned {
7627            f.write_str(" UNSIGNED")?;
7628        }
7629        // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7630        // DDL. Only emits when non-default so the typical output
7631        // stays unchanged.
7632        match self.collation {
7633            Collation::Binary => {}
7634            Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7635        }
7636        if let Some(d) = &self.default {
7637            write!(f, " DEFAULT {d}")?;
7638        }
7639        if self.auto_increment {
7640            f.write_str(" AUTO_INCREMENT")?;
7641        }
7642        if !self.nullable {
7643            f.write_str(" NOT NULL")?;
7644        }
7645        // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7646        // is NOT lifted to a table-level constraint at parse time
7647        // (unlike UNIQUE / CHECK), so the WAL round trip of a
7648        // prepared CREATE TABLE silently dropped the primary key.
7649        if self.is_primary_key {
7650            f.write_str(" PRIMARY KEY")?;
7651        }
7652        // The parser accepts only CURRENT_TIMESTAMP here (stored as
7653        // now()), so that spelling is the lossless round trip.
7654        if self.on_update_runtime.is_some() {
7655            f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7656        }
7657        // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7658        // replay reconstructs the computed-column declaration. The
7659        // expression sits inside a single set of parens; STORED is
7660        // the only variant the parser accepts.
7661        if let Some(gen_expr) = &self.generated_stored_expr {
7662            write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7663        }
7664        Ok(())
7665    }
7666}
7667
7668/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7669/// types (MySQL flavour; `ty` is Text underneath).
7670fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7671    write!(f, " {kw}(")?;
7672    for (i, v) in variants.iter().enumerate() {
7673        if i > 0 {
7674            f.write_str(", ")?;
7675        }
7676        write!(f, "'{}'", v.replace('\'', "''"))?;
7677    }
7678    f.write_str(")")
7679}
7680
7681impl fmt::Display for InsertStatement {
7682    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7683        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7684        if let Some(cols) = &self.columns {
7685            f.write_str(" (")?;
7686            for (i, c) in cols.iter().enumerate() {
7687                if i > 0 {
7688                    f.write_str(", ")?;
7689                }
7690                f.write_str(&quote_ident(c))?;
7691            }
7692            f.write_str(")")?;
7693        }
7694        // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7695        // skipping the VALUES list (mailrs round-5 G4).
7696        if let Some(sel) = &self.select_source {
7697            write!(f, " {sel}")?;
7698        } else {
7699            f.write_str(" VALUES ")?;
7700            for (ri, row) in self.rows.iter().enumerate() {
7701                if ri > 0 {
7702                    f.write_str(", ")?;
7703                }
7704                f.write_str("(")?;
7705                for (i, v) in row.iter().enumerate() {
7706                    if i > 0 {
7707                        f.write_str(", ")?;
7708                    }
7709                    write!(f, "{v}")?;
7710                }
7711                f.write_str(")")?;
7712            }
7713        }
7714        // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7715        // Display round trip: WAL persistence renders the bind-final
7716        // AST through this impl, and a replayed bare INSERT turns a
7717        // legal upsert no-op into a UNIQUE violation that refuses to
7718        // open the catalog.
7719        if let Some(oc) = &self.on_conflict {
7720            write!(f, " {oc}")?;
7721        }
7722        write_returning(self.returning.as_deref(), f)?;
7723        Ok(())
7724    }
7725}
7726
7727/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7728/// parser produced, so the AST→SQL round trip preserves upsert
7729/// semantics (WAL replay depends on it).
7730impl fmt::Display for OnConflictClause {
7731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7732        f.write_str("ON CONFLICT")?;
7733        if let Some(name) = &self.constraint_name {
7734            write!(f, " ON CONSTRAINT {name}")?;
7735        }
7736        if !self.target_columns.is_empty() {
7737            f.write_str(" (")?;
7738            for (i, c) in self.target_columns.iter().enumerate() {
7739                if i > 0 {
7740                    f.write_str(", ")?;
7741                }
7742                f.write_str(&quote_ident(c))?;
7743            }
7744            f.write_str(")")?;
7745        }
7746        if let Some(w) = &self.index_where {
7747            write!(f, " WHERE {w}")?;
7748        }
7749        match &self.action {
7750            OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7751            OnConflictAction::Update {
7752                assignments,
7753                where_,
7754            } => {
7755                f.write_str(" DO UPDATE SET ")?;
7756                for (i, (col, expr)) in assignments.iter().enumerate() {
7757                    if i > 0 {
7758                        f.write_str(", ")?;
7759                    }
7760                    write!(f, "{} = {expr}", quote_ident(col))?;
7761                }
7762                if let Some(w) = where_ {
7763                    write!(f, " WHERE {w}")?;
7764                }
7765                Ok(())
7766            }
7767        }
7768    }
7769}
7770
7771/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7772/// tail for the three DML Display impls.
7773fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7774    let Some(items) = ret else {
7775        return Ok(());
7776    };
7777    f.write_str(" RETURNING ")?;
7778    for (i, item) in items.iter().enumerate() {
7779        if i > 0 {
7780            f.write_str(", ")?;
7781        }
7782        write!(f, "{item}")?;
7783    }
7784    Ok(())
7785}
7786
7787impl fmt::Display for UpdateStatement {
7788    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7789        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7790        for (i, (col, expr)) in self.assignments.iter().enumerate() {
7791            if i > 0 {
7792                f.write_str(", ")?;
7793            }
7794            write!(f, "{} = {expr}", quote_ident(col))?;
7795        }
7796        if let Some(w) = &self.where_ {
7797            write!(f, " WHERE {w}")?;
7798        }
7799        // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7800        if let Some(ol) = self.order_limit.as_deref() {
7801            if !ol.order_by.is_empty() {
7802                f.write_str(" ORDER BY ")?;
7803                for (i, o) in ol.order_by.iter().enumerate() {
7804                    if i > 0 {
7805                        f.write_str(", ")?;
7806                    }
7807                    write!(f, "{}", o.expr)?;
7808                    if o.desc {
7809                        f.write_str(" DESC")?;
7810                    }
7811                    match o.nulls_first {
7812                        Some(true) => f.write_str(" NULLS FIRST")?,
7813                        Some(false) => f.write_str(" NULLS LAST")?,
7814                        None => {}
7815                    }
7816                }
7817            }
7818            if let Some(n) = ol.limit {
7819                write!(f, " LIMIT {n}")?;
7820            }
7821        }
7822        write_returning(self.returning.as_deref(), f)?;
7823        Ok(())
7824    }
7825}
7826
7827impl fmt::Display for DeleteStatement {
7828    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7829        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7830        if let Some(w) = &self.where_ {
7831            write!(f, " WHERE {w}")?;
7832        }
7833        write_returning(self.returning.as_deref(), f)?;
7834        Ok(())
7835    }
7836}
7837
7838impl fmt::Display for CteBody {
7839    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7840        match self {
7841            Self::Select(s) => write!(f, "{s}"),
7842            Self::Insert(s) => write!(f, "{s}"),
7843            Self::Update(s) => write!(f, "{s}"),
7844            Self::Delete(s) => write!(f, "{s}"),
7845            Self::Merge(s) => write!(f, "{s}"),
7846        }
7847    }
7848}
7849
7850impl fmt::Display for MergeStatement {
7851    // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7852    // (it round-trips for the cases tests cover, not for
7853    // round-tripping every edge of the surface).
7854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7855        fmt_with_clause(&self.ctes, f)?;
7856        f.write_str("MERGE INTO ")?;
7857        write!(f, "{}", quote_ident(&self.target))?;
7858        if let Some(a) = &self.target_alias {
7859            write!(f, " {}", quote_ident(a))?;
7860        }
7861        f.write_str(" USING ")?;
7862        if let Some(sub) = &self.source_select {
7863            write!(f, "({sub})")?;
7864        } else {
7865            write!(f, "{}", quote_ident(&self.source))?;
7866        }
7867        if let Some(a) = &self.source_alias {
7868            write!(f, " {}", quote_ident(a))?;
7869        }
7870        if !self.source_column_aliases.is_empty() {
7871            f.write_str("(")?;
7872            for (i, c) in self.source_column_aliases.iter().enumerate() {
7873                if i > 0 {
7874                    f.write_str(", ")?;
7875                }
7876                write!(f, "{}", quote_ident(c))?;
7877            }
7878            f.write_str(")")?;
7879        }
7880        write!(f, " ON {}", self.on)?;
7881        for clause in &self.clauses {
7882            f.write_str(" WHEN ")?;
7883            f.write_str(match clause.matched {
7884                MergeMatched::Matched => "MATCHED",
7885                MergeMatched::NotMatched => "NOT MATCHED",
7886                MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7887            })?;
7888            if let Some(c) = &clause.condition {
7889                write!(f, " AND {c}")?;
7890            }
7891            f.write_str(" THEN ")?;
7892            match &clause.action {
7893                MergeAction::Insert { columns, values } => {
7894                    f.write_str("INSERT ")?;
7895                    // A column list is optional (round 146): the bare
7896                    // `INSERT VALUES (…)` form maps positionally.
7897                    if !columns.is_empty() {
7898                        f.write_str("(")?;
7899                        for (i, c) in columns.iter().enumerate() {
7900                            if i > 0 {
7901                                f.write_str(", ")?;
7902                            }
7903                            write!(f, "{}", quote_ident(c))?;
7904                        }
7905                        f.write_str(") ")?;
7906                    }
7907                    f.write_str("VALUES (")?;
7908                    for (i, v) in values.iter().enumerate() {
7909                        if i > 0 {
7910                            f.write_str(", ")?;
7911                        }
7912                        write!(f, "{v}")?;
7913                    }
7914                    f.write_str(")")?;
7915                }
7916                MergeAction::Update { assignments } => {
7917                    f.write_str("UPDATE SET ")?;
7918                    for (i, (c, e)) in assignments.iter().enumerate() {
7919                        if i > 0 {
7920                            f.write_str(", ")?;
7921                        }
7922                        write!(f, "{} = {e}", quote_ident(c))?;
7923                    }
7924                }
7925                MergeAction::Delete => f.write_str("DELETE")?,
7926                MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7927            }
7928        }
7929        if let Some(items) = &self.returning {
7930            f.write_str(" RETURNING ")?;
7931            for (i, it) in items.iter().enumerate() {
7932                if i > 0 {
7933                    f.write_str(", ")?;
7934                }
7935                write!(f, "{it}")?;
7936            }
7937        }
7938        Ok(())
7939    }
7940}
7941
7942/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
7943/// carry a CTE list and must round-trip it identically.
7944fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
7945    if ctes.is_empty() {
7946        return Ok(());
7947    }
7948    f.write_str("WITH ")?;
7949    if ctes.iter().any(|c| c.recursive) {
7950        f.write_str("RECURSIVE ")?;
7951    }
7952    for (i, cte) in ctes.iter().enumerate() {
7953        if i > 0 {
7954            f.write_str(", ")?;
7955        }
7956        f.write_str(&quote_ident(&cte.name))?;
7957        if !cte.column_overrides.is_empty() {
7958            f.write_str(" (")?;
7959            for (ci, c) in cte.column_overrides.iter().enumerate() {
7960                if ci > 0 {
7961                    f.write_str(", ")?;
7962                }
7963                f.write_str(&quote_ident(c))?;
7964            }
7965            f.write_str(")")?;
7966        }
7967        write!(f, " AS ({})", cte.body)?;
7968    }
7969    f.write_str(" ")
7970}
7971
7972impl fmt::Display for SelectStatement {
7973    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7974        // v7.30.1 (mailrs round-24 class audit) — the WITH clause
7975        // must survive the round trip; a CTE-using statement
7976        // re-parsed without it references undefined tables.
7977        fmt_with_clause(&self.ctes, f)?;
7978        write_bare_select(self, f)?;
7979        for (kind, peer) in &self.unions {
7980            f.write_str(match kind {
7981                UnionKind::Distinct => " UNION ",
7982                UnionKind::All => " UNION ALL ",
7983                UnionKind::Intersect => " INTERSECT ",
7984                UnionKind::IntersectAll => " INTERSECT ALL ",
7985                UnionKind::Except => " EXCEPT ",
7986                UnionKind::ExceptAll => " EXCEPT ALL ",
7987            })?;
7988            write_bare_select(peer, f)?;
7989        }
7990        if !self.order_by.is_empty() {
7991            f.write_str(" ORDER BY ")?;
7992            for (i, o) in self.order_by.iter().enumerate() {
7993                if i > 0 {
7994                    f.write_str(", ")?;
7995                }
7996                write!(f, "{}", o.expr)?;
7997                if o.desc {
7998                    f.write_str(" DESC")?;
7999                }
8000                match o.nulls_first {
8001                    Some(true) => f.write_str(" NULLS FIRST")?,
8002                    Some(false) => f.write_str(" NULLS LAST")?,
8003                    None => {}
8004                }
8005            }
8006        }
8007        // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
8008        // exists in the FETCH FIRST spelling; rendering it as LIMIT
8009        // dropped the tie-extension semantics on replay. The parser
8010        // accepts OFFSET before FETCH, so keep that order here.
8011        if self.limit_with_ties {
8012            if let Some(o) = &self.offset {
8013                write!(f, " OFFSET {o}")?;
8014            }
8015            if let Some(n) = &self.limit {
8016                write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
8017            }
8018        } else {
8019            if let Some(n) = &self.limit {
8020                write!(f, " LIMIT {n}")?;
8021            }
8022            if let Some(o) = &self.offset {
8023                write!(f, " OFFSET {o}")?;
8024            }
8025        }
8026        Ok(())
8027    }
8028}
8029
8030fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8031    f.write_str("SELECT ")?;
8032    if s.distinct {
8033        f.write_str("DISTINCT ")?;
8034    }
8035    write_bare_select_body(s, f)
8036}
8037
8038fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8039    for (i, item) in s.items.iter().enumerate() {
8040        if i > 0 {
8041            f.write_str(", ")?;
8042        }
8043        write!(f, "{item}")?;
8044    }
8045    if let Some(t) = &s.from {
8046        write!(f, " FROM {t}")?;
8047    }
8048    if let Some(e) = &s.where_ {
8049        write!(f, " WHERE {e}")?;
8050    }
8051    if let Some(gs) = &s.group_by {
8052        f.write_str(" GROUP BY ")?;
8053        for (i, g) in gs.iter().enumerate() {
8054            if i > 0 {
8055                f.write_str(", ")?;
8056            }
8057            write!(f, "{g}")?;
8058        }
8059    } else if s.group_by_all {
8060        // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
8061        // shortcut parses to group_by: None + this flag; dropping
8062        // it turned an aggregate query into a bare projection on
8063        // re-parse.
8064        f.write_str(" GROUP BY ALL")?;
8065    }
8066    if let Some(h) = &s.having {
8067        write!(f, " HAVING {h}")?;
8068    }
8069    Ok(())
8070}
8071
8072impl fmt::Display for SelectItem {
8073    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8074        match self {
8075            Self::Wildcard => f.write_str("*"),
8076            Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
8077            Self::Expr { expr, alias } => {
8078                write!(f, "{expr}")?;
8079                if let Some(a) = alias {
8080                    write!(f, " AS {}", quote_ident(a))?;
8081                }
8082                Ok(())
8083            }
8084        }
8085    }
8086}
8087
8088impl fmt::Display for FromClause {
8089    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8090        write!(f, "{}", self.primary)?;
8091        for j in &self.joins {
8092            match j.kind {
8093                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
8094                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
8095                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
8096                JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
8097                JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
8098                JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
8099            }
8100            if let Some(on) = &j.on {
8101                write!(f, " ON {on}")?;
8102            }
8103        }
8104        Ok(())
8105    }
8106}
8107
8108/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
8109/// for NESTED). Kept close to the parser's grammar so it re-parses.
8110fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
8111    for (i, c) in cols.iter().enumerate() {
8112        if i > 0 {
8113            f.write_str(", ")?;
8114        }
8115        match c {
8116            JsonTableColumn::Ordinality { name } => {
8117                write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
8118            }
8119            JsonTableColumn::Nested { path, columns } => {
8120                write!(f, "NESTED PATH '{path}' COLUMNS (")?;
8121                fmt_json_table_columns(f, columns)?;
8122                f.write_str(")")?;
8123            }
8124            JsonTableColumn::Regular {
8125                name,
8126                ty,
8127                path,
8128                exists,
8129                format_json,
8130                wrapper,
8131                on_empty,
8132                on_error,
8133            } => {
8134                write!(f, "{} {ty}", quote_ident(name))?;
8135                if *format_json {
8136                    f.write_str(" FORMAT JSON")?;
8137                }
8138                if *exists {
8139                    write!(f, " EXISTS PATH '{path}'")?;
8140                } else {
8141                    write!(f, " PATH '{path}'")?;
8142                }
8143                if *wrapper {
8144                    f.write_str(" WITH WRAPPER")?;
8145                }
8146                if let JsonTableOnBehavior::Error = on_empty {
8147                    f.write_str(" ERROR ON EMPTY")?;
8148                } else if let JsonTableOnBehavior::Default(e) = on_empty {
8149                    write!(f, " DEFAULT {e} ON EMPTY")?;
8150                }
8151                if let JsonTableOnBehavior::Error = on_error {
8152                    f.write_str(" ERROR ON ERROR")?;
8153                } else if let JsonTableOnBehavior::Default(e) = on_error {
8154                    write!(f, " DEFAULT {e} ON ERROR")?;
8155                }
8156            }
8157        }
8158    }
8159    Ok(())
8160}
8161
8162impl fmt::Display for TableRef {
8163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8164        // v7.30.1 (mailrs round-24 class audit) — the dynamic
8165        // table-ref shapes must round-trip: rendering only the
8166        // (synthetic) name turned LATERAL / unnest() /
8167        // generate_series() into references to nonexistent tables
8168        // on re-parse.
8169        // v7.39 (round 205) — JSON_TABLE round-trips through Display
8170        // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
8171        if let Some(jt) = &self.json_table {
8172            write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
8173            if !jt.passing.is_empty() {
8174                f.write_str(" PASSING ")?;
8175                for (i, (n, e)) in jt.passing.iter().enumerate() {
8176                    if i > 0 {
8177                        f.write_str(", ")?;
8178                    }
8179                    write!(f, "{e} AS {}", quote_ident(n))?;
8180                }
8181            }
8182            f.write_str(" COLUMNS (")?;
8183            fmt_json_table_columns(f, &jt.columns)?;
8184            f.write_str(")")?;
8185            if let Some(a) = &self.alias {
8186                write!(f, " AS {}", quote_ident(a))?;
8187            }
8188            return Ok(());
8189        }
8190        if let Some(inner) = &self.lateral_subquery {
8191            write!(f, "LATERAL ({inner})")?;
8192            if let Some(a) = &self.alias {
8193                write!(f, " AS {}", quote_ident(a))?;
8194                // v7.37 D.28 — a derived table on the lateral_subquery channel
8195                // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
8196                // lowers here). Rendering the alias without the column list lost
8197                // the column names on re-parse (a view body round-trips through
8198                // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
8199                if !self.unnest_column_aliases.is_empty() {
8200                    f.write_str(" (")?;
8201                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8202                        if i > 0 {
8203                            f.write_str(", ")?;
8204                        }
8205                        f.write_str(&quote_ident(c))?;
8206                    }
8207                    f.write_str(")")?;
8208                }
8209            }
8210            return Ok(());
8211        }
8212        if let Some(expr) = &self.unnest_expr {
8213            write!(f, "UNNEST({expr})")?;
8214            if let Some(a) = &self.alias {
8215                write!(f, " AS {}", quote_ident(a))?;
8216                if !self.unnest_column_aliases.is_empty() {
8217                    f.write_str(" (")?;
8218                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8219                        if i > 0 {
8220                            f.write_str(", ")?;
8221                        }
8222                        f.write_str(&quote_ident(c))?;
8223                    }
8224                    f.write_str(")")?;
8225                }
8226            }
8227            return Ok(());
8228        }
8229        // 7.38.1 S5.1 — a FROM-position table function must re-render
8230        // as the CALL, not its bare name: ARRAY(subquery) desugars by
8231        // re-parsing the subquery's canonical text, and a dropped
8232        // argument list turned `pg_options_to_table(x)` into a
8233        // relation lookup that does not exist.
8234        if let Some(call) = &self.table_fn_call {
8235            let (fn_name, args) = call.as_ref();
8236            write!(f, "{fn_name}(")?;
8237            for (i, a) in args.iter().enumerate() {
8238                if i > 0 {
8239                    f.write_str(", ")?;
8240                }
8241                write!(f, "{a}")?;
8242            }
8243            f.write_str(")")?;
8244            if let Some(a) = &self.alias {
8245                write!(f, " AS {}", quote_ident(a))?;
8246                if !self.unnest_column_aliases.is_empty() {
8247                    f.write_str("(")?;
8248                    for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8249                        if i > 0 {
8250                            f.write_str(", ")?;
8251                        }
8252                        write!(f, "{}", quote_ident(c))?;
8253                    }
8254                    f.write_str(")")?;
8255                }
8256            }
8257            return Ok(());
8258        }
8259        if let Some(args) = &self.generate_series_args {
8260            f.write_str("generate_series(")?;
8261            for (i, a) in args.iter().enumerate() {
8262                if i > 0 {
8263                    f.write_str(", ")?;
8264                }
8265                write!(f, "{a}")?;
8266            }
8267            f.write_str(")")?;
8268            if let Some(a) = &self.alias {
8269                write!(f, " AS {}", quote_ident(a))?;
8270            }
8271            return Ok(());
8272        }
8273        write!(f, "{}", quote_ident(&self.name))?;
8274        if let Some(seg) = self.as_of_segment {
8275            write!(f, " AS OF SEGMENT {seg}")?;
8276        }
8277        if let Some(a) = &self.alias {
8278            write!(f, " AS {}", quote_ident(a))?;
8279        }
8280        Ok(())
8281    }
8282}
8283
8284impl fmt::Display for ColumnName {
8285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8286        if let Some(q) = &self.qualifier {
8287            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
8288        } else {
8289            write!(f, "{}", quote_ident(&self.name))
8290        }
8291    }
8292}
8293
8294/// v7.39 (round 311) — render the left spine of an AND / OR chain
8295/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
8296/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
8297/// SAME operator flattens; anything else is an ordinary operand.
8298fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
8299    if let Expr::Binary {
8300        lhs,
8301        op: inner,
8302        rhs,
8303    } = e
8304        && *inner == op
8305    {
8306        write_bool_chain(f, lhs, op)?;
8307        return write!(f, " {op} {rhs}");
8308    }
8309    write!(f, "{e}")
8310}
8311
8312/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
8313/// form `pg_get_constraintdef(oid, true)` and friends return.
8314///
8315/// The default [`fmt::Display`] parenthesises every operator node, which
8316/// is what PG's non-pretty deparse does and what makes the text
8317/// round-trip. Pretty drops the pairs the grammar can put back, and the
8318/// rule is NOT plain precedence minimisation — measured against PG 18.4
8319/// across 37 shapes:
8320///
8321///   * the boolean layer follows precedence (NOT > AND > OR): an OR
8322///     under an AND keeps its parens, an AND under an OR does not, and a
8323///     comparison under any of them does not (`NOT a > 1`);
8324///   * an associative chain flattens completely, even where the source
8325///     nested it to the right (`a AND (b AND c)` prints as one chain);
8326///   * but an operand of a comparison or arithmetic operator keeps its
8327///     parens whenever it is itself an operator expression — so
8328///     `(a + b) > 10` and `(- a) + b`, even though precedence alone
8329///     would not require either. A cast, function call, column or
8330///     literal in that position does not (`a::text = t`,
8331///     `length(code) > 2`); a cast counts as compound exactly when the
8332///     thing it casts is (`((a + b)::text) = t`).
8333///
8334/// Anything outside that layer defers to `Display`, which is never
8335/// wrong — only more parenthesised than PG would print.
8336#[must_use]
8337pub fn pretty_expr(e: &Expr) -> String {
8338    let mut out = String::new();
8339    write_pretty(&mut out, e, PrettyParent::None, false, false);
8340    out
8341}
8342
8343/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
8344/// writes it.
8345///
8346/// MariaDB names the offending expression in its out-of-range message
8347/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
8348/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
8349/// MySQL client, for a cast the client had just written the other way.
8350#[must_use]
8351pub fn pretty_expr_mysql(e: &Expr) -> String {
8352    let mut out = String::new();
8353    write_pretty(&mut out, e, PrettyParent::None, false, true);
8354    out
8355}
8356
8357/// v7.39 (round 505) — how strongly an expression suggests its own column
8358/// name. A cast keeps its argument's name only when that name is STRONG;
8359/// otherwise the cast reports the type it casts to.
8360///
8361/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
8362/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
8363/// itself `text` — so `case` and a function name cannot be the same kind of
8364/// answer, even though a bare `CASE …` does report `case`.
8365#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8366enum NameStrength {
8367    /// Nothing to go on — PG reports `?column?`.
8368    None,
8369    /// A name, but one a cast overrides: `case`, or a type name.
8370    Weak,
8371    /// A name a cast keeps: a column, or the function that produced it.
8372    Strong,
8373}
8374
8375/// v7.39 (round 505) — the column name PG18 gives a projected expression
8376/// that carries no `AS` alias. `None` means `?column?`.
8377///
8378/// SPG used to print the parsed expression back out, which matched neither
8379/// oracle and made name-keyed row access miss on both wires:
8380///
8381/// | query        | PG18       | SPG (before) |
8382/// |--------------|------------|--------------|
8383/// | `upper(s)`   | `upper`    | `upper(s)`   |
8384/// | `a+b`        | `?column?` | `(a + b)`    |
8385/// | `'lit'`      | `?column?` | `'lit'`      |
8386/// | `CASE …`     | `case`     | `CASE WHEN (a = 1) THEN …` |
8387///
8388/// Every rule below is one of those measurements, taken with `\gdesc`
8389/// against PG18: a call is named for its function, a cast recurses into its
8390/// argument and falls back to the type, a scalar subquery takes the name of
8391/// the column it selects, and operators have no name at all.
8392#[must_use]
8393pub fn figure_column_name(expr: &Expr) -> Option<String> {
8394    let (name, _) = figure_name_inner(expr);
8395    name
8396}
8397
8398/// The name a function reports, which is not always the name SPG parsed it
8399/// under: `count(*)` is held as `count_star` so the star arity survives the
8400/// AST, and that internal spelling must not reach a client. PG18 reports
8401/// `count`.
8402fn canonical_function_name(name: &str) -> String {
8403    match name {
8404        "count_star" => "count".to_string(),
8405        other => other.to_ascii_lowercase(),
8406    }
8407}
8408
8409/// v7.38.7 — a cast target's `pg_type.typname`, for the name a cast
8410/// reports when its operand has none of its own. Only the spellings that
8411/// differ from what the user writes need an entry; everything else is
8412/// already its own typname.
8413fn cast_target_typname(target: &CastTarget) -> String {
8414    let written = target.to_string().to_ascii_lowercase();
8415    let base = written.strip_suffix("[]").unwrap_or(&written);
8416    let mapped = match base {
8417        "bigint" => "int8",
8418        "integer" | "int" => "int4",
8419        "smallint" => "int2",
8420        "boolean" => "bool",
8421        "double precision" => "float8",
8422        "real" => "float4",
8423        "character varying" => "varchar",
8424        "character" => "bpchar",
8425        "timestamp with time zone" => "timestamptz",
8426        "timestamp without time zone" => "timestamp",
8427        "time without time zone" => "time",
8428        "decimal" => "numeric",
8429        other => other,
8430    };
8431    if written.ends_with("[]") {
8432        alloc::format!("_{mapped}")
8433    } else {
8434        String::from(mapped)
8435    }
8436}
8437
8438fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
8439    let strong = |n: String| (Some(n), NameStrength::Strong);
8440    match expr {
8441        // A column keeps its own name, qualifier and all discarded:
8442        // `lbl.a` reports `a`.
8443        Expr::Column(c) => strong(c.name.clone()),
8444        // Calls are named for the function. This covers the shapes that
8445        // only LOOK like syntax — `EXTRACT(year FROM …)` reports
8446        // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
8447        // because PG resolves them to functions before naming them.
8448        Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
8449            strong(canonical_function_name(name))
8450        }
8451        Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
8452        Expr::Extract { .. } => strong("extract".to_string()),
8453        Expr::Exists { .. } => strong("exists".to_string()),
8454        Expr::Array(_) => strong("array".to_string()),
8455        // `(expr).field` is named for the field, as a column would be.
8456        Expr::FieldAccess { field, .. } => strong(field.clone()),
8457        // A cast prefers its argument's name and settles for the type:
8458        // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
8459        Expr::Cast {
8460            expr: inner,
8461            target,
8462        } => match figure_name_inner(inner) {
8463            (Some(n), NameStrength::Strong) => strong(n),
8464            // v7.38.7 — the fallback is the target type's INTERNAL name,
8465            // which is what PG reports: `SELECT 7::bigint` is `int8`, not
8466            // the `bigint` the user typed. Measured on PG18 alongside
8467            // `CAST(7 AS bigint)`, which answers `int8` too.
8468            _ => (Some(cast_target_typname(target)), NameStrength::Weak),
8469        },
8470        // A scalar subquery reports whatever its single output column
8471        // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
8472        Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
8473        // `CASE …` names itself, but weakly — a cast around it wins.
8474        Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
8475        // A literal that carries its own type names itself for that type:
8476        // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
8477        // reports nothing. Weak, like any other type name.
8478        Expr::Literal(Literal::Interval { .. }) => {
8479            (Some("interval".to_string()), NameStrength::Weak)
8480        }
8481        // A wrapper that adds no name of its own.
8482        Expr::Variadic(inner) => figure_name_inner(inner),
8483        Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
8484        // Everything else — operators, comparisons, IS NULL, LIKE, IN,
8485        // literals, placeholders — reports `?column?`.
8486        _ => (None, NameStrength::None),
8487    }
8488}
8489
8490/// The name a scalar subquery's single projected column reports.
8491fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
8492    match sel.items.as_slice() {
8493        [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
8494        [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
8495        _ => (None, NameStrength::None),
8496    }
8497}
8498
8499/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
8500fn pretty_prec(e: &Expr) -> u8 {
8501    match e {
8502        Expr::Binary { op, .. } => match op {
8503            // v7.39 (round 407) — this deparse ladder mirrors the parser's:
8504            // OR < XOR < AND < NOT < comparison < additive < multiplicative.
8505            // XOR (MySQL-only) sits between OR and AND, so AND and everything
8506            // above shifted +1 to open rung 2 for it.
8507            BinOp::Or => 1,
8508            BinOp::LogicalXor => 2,
8509            BinOp::And => 3,
8510            BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
8511            BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
8512            // Everything else in this enum is a comparison-shaped
8513            // operator; they share one level, as in the grammar.
8514            _ => 5,
8515        },
8516        Expr::Unary { op, .. } => match op {
8517            UnOp::Not => 4,
8518            UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
8519        },
8520        _ => u8::MAX,
8521    }
8522}
8523
8524/// Is this node an operator expression — the thing an arithmetic or
8525/// comparison parent keeps parentheses around? A cast inherits the
8526/// answer from what it casts.
8527fn pretty_is_compound(e: &Expr) -> bool {
8528    match e {
8529        Expr::Binary { .. } | Expr::Unary { .. } => true,
8530        Expr::Cast { expr, .. } => pretty_is_compound(expr),
8531        _ => false,
8532    }
8533}
8534
8535/// `parent` describes the enclosing operator: its binding power, and
8536/// whether it is a comparison (which keeps parens around any operator
8537/// operand) or a NOT (which keeps them at equal power too).
8538#[derive(Clone, Copy, PartialEq)]
8539enum PrettyParent {
8540    /// Nothing encloses this node.
8541    None,
8542    /// A comparison-shaped operator: an operator operand always keeps
8543    /// its parens, whatever precedence would allow.
8544    Comparison,
8545    /// Arithmetic / concatenation: precedence decides.
8546    Arith(u8),
8547    /// A boolean connective: precedence decides.
8548    Bool(u8),
8549    /// `NOT`: precedence decides, but equal power still needs parens so
8550    /// `NOT (NOT a > 1)` does not collapse.
8551    Not,
8552}
8553
8554fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8555    let prec = pretty_prec(e);
8556    let is_unary_sign = matches!(
8557        e,
8558        Expr::Unary {
8559            op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8560            ..
8561        }
8562    );
8563    let needs = match parent {
8564        PrettyParent::None => false,
8565        PrettyParent::Comparison => pretty_is_compound(e),
8566        // A sign always keeps its parens under an operator — PG writes
8567        // `(- a) + b` even though precedence would not require it.
8568        PrettyParent::Arith(p) => {
8569            is_unary_sign
8570                || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8571                    && (prec < p || (prec == p && is_rhs)))
8572        }
8573        PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8574        PrettyParent::Not => {
8575            matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8576        }
8577    };
8578    if needs {
8579        out.push('(');
8580    }
8581    match e {
8582        Expr::Binary { lhs, op, rhs } => {
8583            let child = match op {
8584                BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8585                BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8586                    PrettyParent::Arith(prec)
8587                }
8588                _ => PrettyParent::Comparison,
8589            };
8590            write_pretty(out, lhs, child, false, mysql);
8591            out.push(' ');
8592            out.push_str(&alloc::format!("{op}"));
8593            out.push(' ');
8594            // AND / OR are associative, so an explicitly right-nested
8595            // chain still prints as one chain.
8596            let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8597            write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8598        }
8599        Expr::Unary { op, expr } => match op {
8600            UnOp::Not => {
8601                out.push_str("NOT ");
8602                write_pretty(out, expr, PrettyParent::Not, false, mysql);
8603            }
8604            UnOp::Neg => {
8605                out.push_str("- ");
8606                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8607            }
8608            UnOp::Plus => {
8609                out.push_str("+ ");
8610                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8611            }
8612            UnOp::BitNot => {
8613                out.push('~');
8614                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8615            }
8616        },
8617        Expr::Cast { expr, target } => {
8618            if mysql {
8619                // MySQL's own spelling, which is what its error messages
8620                // quote back.
8621                out.push_str("cast(");
8622                write_pretty(out, expr, PrettyParent::None, false, mysql);
8623                out.push_str(&alloc::format!(
8624                    " as {})",
8625                    target.to_string().to_lowercase()
8626                ));
8627            } else {
8628                write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8629                out.push_str(&alloc::format!("::{target}"));
8630            }
8631        }
8632        Expr::IsNull { expr, negated } => {
8633            write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8634            out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8635        }
8636        other => out.push_str(&alloc::format!("{other}")),
8637    }
8638    if needs {
8639        out.push(')');
8640    }
8641}
8642
8643const fn pretty_prec_not() -> u8 {
8644    // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8645    // when the XOR insertion shifted the deparse ladder up by one).
8646    4
8647}
8648
8649impl fmt::Display for Expr {
8650    #[allow(clippy::too_many_lines)]
8651    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8652        match self {
8653            Self::Literal(l) => write!(f, "{l}"),
8654            Self::Column(c) => write!(f, "{c}"),
8655            Self::Placeholder(n) => write!(f, "${n}"),
8656            // Round-trips as the spelling PG's docs lead with.
8657            Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8658            Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8659            // Round-trips with the name quoted, which is how PG spells a
8660            // collation everywhere: `"en_US.utf8"`, `"C"`.
8661            Self::Collate { expr, collation } => {
8662                write!(f, "{expr} COLLATE {}", quote_ident(collation))
8663            }
8664            // v7.39 (round 311) — an AND / OR chain that nests to the
8665            // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8666            // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8667            // its parentheses, because that is a different grouping as
8668            // written. Both halves measured against PG 18.4's deparse,
8669            // which flattens a same-operator left chain at parse time and
8670            // leaves `a AND (b AND c)` alone.
8671            Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8672                f.write_str("(")?;
8673                write_bool_chain(f, lhs, *op)?;
8674                write!(f, " {op} {rhs}")?;
8675                f.write_str(")")
8676            }
8677            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8678            Self::Unary { op, expr } => match op {
8679                UnOp::Not => write!(f, "(NOT {expr})"),
8680                // A space after the sign, as PG's deparse writes it.
8681                UnOp::Neg => write!(f, "(- {expr})"),
8682                UnOp::Plus => write!(f, "(+ {expr})"),
8683                UnOp::BitNot => write!(f, "(~{expr})"),
8684            },
8685            // The OPERAND carries the parentheses, not the cast:
8686            // `(a)::text`, `((a + b))::text`. PG words it this way, and
8687            // it is what keeps `a::text = t` from reading as a cast of
8688            // the comparison.
8689            Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8690            Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8691            Self::AggregateOrdered {
8692                call,
8693                order_by,
8694                distinct,
8695                filter,
8696            } => {
8697                let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8698                    for (i, o) in order_by.iter().enumerate() {
8699                        if i > 0 {
8700                            f.write_str(", ")?;
8701                        }
8702                        write!(f, "{}", o.expr)?;
8703                        if o.desc {
8704                            f.write_str(" DESC")?;
8705                        }
8706                        match o.nulls_first {
8707                            Some(true) => f.write_str(" NULLS FIRST")?,
8708                            Some(false) => f.write_str(" NULLS LAST")?,
8709                            None => {}
8710                        }
8711                    }
8712                    Ok(())
8713                };
8714                // Ordered-set aggregates (`percentile_cont(f) WITHIN
8715                // GROUP (ORDER BY x)`) render the in-parens args as the
8716                // direct argument and the sort spec under WITHIN GROUP —
8717                // not as an in-argument ORDER BY.
8718                let ordered_set = matches!(
8719                    call.as_ref(),
8720                    Expr::FunctionCall { name, .. }
8721                        if matches!(
8722                            name.to_ascii_lowercase().as_str(),
8723                            "percentile_cont" | "percentile_disc" | "mode"
8724                        )
8725                );
8726                if ordered_set {
8727                    write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8728                    fmt_order_by(f)?;
8729                    f.write_str(")")?;
8730                } else {
8731                    // `name([DISTINCT ]args [ORDER BY …])` — peel the
8732                    // inner call's parens to splice modifiers.
8733                    let inner = alloc::format!("{call}");
8734                    let body = inner.strip_suffix(')').unwrap_or(&inner);
8735                    let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8736                    write!(f, "{head}(")?;
8737                    if *distinct {
8738                        f.write_str("DISTINCT ")?;
8739                    }
8740                    write!(f, "{args_part}")?;
8741                    if !order_by.is_empty() {
8742                        f.write_str(" ORDER BY ")?;
8743                        fmt_order_by(f)?;
8744                    }
8745                    f.write_str(")")?;
8746                }
8747                if let Some(cond) = filter {
8748                    write!(f, " FILTER (WHERE {cond})")?;
8749                }
8750                Ok(())
8751            }
8752            Self::IsNull { expr, negated } => {
8753                if *negated {
8754                    write!(f, "({expr} IS NOT NULL)")
8755                } else {
8756                    write!(f, "({expr} IS NULL)")
8757                }
8758            }
8759            Self::BoolTest {
8760                expr,
8761                value,
8762                negated,
8763            } => {
8764                let word = match value {
8765                    Some(true) => "TRUE",
8766                    Some(false) => "FALSE",
8767                    None => "UNKNOWN",
8768                };
8769                if *negated {
8770                    write!(f, "({expr} IS NOT {word})")
8771                } else {
8772                    write!(f, "({expr} IS {word})")
8773                }
8774            }
8775            Self::FunctionCall { name, args } => {
8776                write!(f, "{name}(")?;
8777                for (i, a) in args.iter().enumerate() {
8778                    if i > 0 {
8779                        f.write_str(", ")?;
8780                    }
8781                    write!(f, "{a}")?;
8782                }
8783                f.write_str(")")
8784            }
8785            Self::Like {
8786                expr,
8787                pattern,
8788                negated,
8789                case_insensitive,
8790            } => {
8791                let op = match (negated, case_insensitive) {
8792                    (false, false) => "LIKE",
8793                    (true, false) => "NOT LIKE",
8794                    (false, true) => "ILIKE",
8795                    (true, true) => "NOT ILIKE",
8796                };
8797                write!(f, "({expr} {op} {pattern})")
8798            }
8799            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8800            Self::WindowFunction {
8801                name,
8802                args,
8803                partition_by,
8804                order_by,
8805                frame,
8806                null_treatment,
8807                filter,
8808            } => {
8809                write!(f, "{name}(")?;
8810                for (i, a) in args.iter().enumerate() {
8811                    if i > 0 {
8812                        f.write_str(", ")?;
8813                    }
8814                    write!(f, "{a}")?;
8815                }
8816                f.write_str(")")?;
8817                // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8818                // OVER; it round-trips so a window body's Display re-parses.
8819                if let Some(cond) = filter {
8820                    write!(f, " FILTER (WHERE {cond})")?;
8821                }
8822                // v7.30.1 (mailrs round-24 class audit) — IGNORE
8823                // NULLS sits between the arg list and OVER; dropping
8824                // it reverted replayed queries to RESPECT NULLS.
8825                if matches!(null_treatment, NullTreatment::Ignore) {
8826                    f.write_str(" IGNORE NULLS")?;
8827                }
8828                f.write_str(" OVER (")?;
8829                if !partition_by.is_empty() {
8830                    f.write_str("PARTITION BY ")?;
8831                    for (i, p) in partition_by.iter().enumerate() {
8832                        if i > 0 {
8833                            f.write_str(", ")?;
8834                        }
8835                        write!(f, "{p}")?;
8836                    }
8837                }
8838                if !order_by.is_empty() {
8839                    if !partition_by.is_empty() {
8840                        f.write_str(" ")?;
8841                    }
8842                    f.write_str("ORDER BY ")?;
8843                    for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8844                        if i > 0 {
8845                            f.write_str(", ")?;
8846                        }
8847                        write!(f, "{e}")?;
8848                        if *desc {
8849                            f.write_str(" DESC")?;
8850                        }
8851                        match nulls_first {
8852                            Some(true) => f.write_str(" NULLS FIRST")?,
8853                            Some(false) => f.write_str(" NULLS LAST")?,
8854                            None => {}
8855                        }
8856                    }
8857                }
8858                if let Some(fr) = frame {
8859                    if !partition_by.is_empty() || !order_by.is_empty() {
8860                        f.write_str(" ")?;
8861                    }
8862                    let k = match fr.kind {
8863                        FrameKind::Rows => "ROWS",
8864                        FrameKind::Range => "RANGE",
8865                        FrameKind::Groups => "GROUPS",
8866                    };
8867                    if let Some(end) = &fr.end {
8868                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8869                    } else {
8870                        write!(f, "{k} {}", fr.start)?;
8871                    }
8872                }
8873                f.write_str(")")
8874            }
8875            Self::ScalarSubquery(s) => write!(f, "({s})"),
8876            Self::Exists { subquery, negated } => {
8877                if *negated {
8878                    write!(f, "NOT EXISTS ({subquery})")
8879                } else {
8880                    write!(f, "EXISTS ({subquery})")
8881                }
8882            }
8883            Self::InSubquery {
8884                expr,
8885                subquery,
8886                negated,
8887            } => {
8888                if *negated {
8889                    write!(f, "({expr} NOT IN ({subquery}))")
8890                } else {
8891                    write!(f, "({expr} IN ({subquery}))")
8892                }
8893            }
8894            Self::RowInSubquery {
8895                row,
8896                subquery,
8897                negated,
8898            } => {
8899                write!(f, "(")?;
8900                for (i, e) in row.iter().enumerate() {
8901                    if i > 0 {
8902                        write!(f, ", ")?;
8903                    }
8904                    write!(f, "{e}")?;
8905                }
8906                let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8907                write!(f, "{kw}{subquery})")
8908            }
8909            Self::RowCmpSubquery { row, op, subquery } => {
8910                write!(f, "(")?;
8911                for (i, e) in row.iter().enumerate() {
8912                    if i > 0 {
8913                        write!(f, ", ")?;
8914                    }
8915                    write!(f, "{e}")?;
8916                }
8917                write!(f, ") {op} ({subquery})")
8918            }
8919            Self::InList {
8920                expr,
8921                list,
8922                negated,
8923            } => {
8924                let kw = if *negated { " NOT IN (" } else { " IN (" };
8925                write!(f, "({expr}{kw}")?;
8926                for (i, e) in list.iter().enumerate() {
8927                    if i > 0 {
8928                        f.write_str(", ")?;
8929                    }
8930                    write!(f, "{e}")?;
8931                }
8932                f.write_str("))")
8933            }
8934            Self::Array(items) => {
8935                f.write_str("ARRAY[")?;
8936                for (i, e) in items.iter().enumerate() {
8937                    if i > 0 {
8938                        f.write_str(", ")?;
8939                    }
8940                    write!(f, "{e}")?;
8941                }
8942                f.write_str("]")
8943            }
8944            Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
8945            Self::ArraySlice { target, lo, hi } => {
8946                write!(f, "({target}[")?;
8947                if let Some(l) = lo {
8948                    write!(f, "{l}")?;
8949                }
8950                write!(f, ":")?;
8951                if let Some(h) = hi {
8952                    write!(f, "{h}")?;
8953                }
8954                write!(f, "])")
8955            }
8956            Self::AnyAll {
8957                expr,
8958                op,
8959                array,
8960                is_any,
8961            } => {
8962                let kw = if *is_any { "ANY" } else { "ALL" };
8963                write!(f, "({expr} {op} {kw}({array}))")
8964            }
8965            Self::Case {
8966                operand,
8967                branches,
8968                else_branch,
8969            } => {
8970                f.write_str("CASE")?;
8971                if let Some(op) = operand {
8972                    write!(f, " {op}")?;
8973                }
8974                for (w, t) in branches {
8975                    write!(f, " WHEN {w} THEN {t}")?;
8976                }
8977                if let Some(e) = else_branch {
8978                    write!(f, " ELSE {e}")?;
8979                }
8980                f.write_str(" END")
8981            }
8982        }
8983    }
8984}
8985
8986/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
8987/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
8988pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
8989    use alloc::string::ToString;
8990    if scale == 0 {
8991        return alloc::format!("{unscaled}");
8992    }
8993    let neg = unscaled < 0;
8994    let digits = alloc::format!("{}", unscaled.unsigned_abs());
8995    let scale = scale as usize;
8996    let (int_part, frac_part) = if digits.len() > scale {
8997        (
8998            digits[..digits.len() - scale].to_string(),
8999            digits[digits.len() - scale..].to_string(),
9000        )
9001    } else {
9002        ("0".to_string(), alloc::format!("{digits:0>scale$}"))
9003    };
9004    alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
9005}
9006
9007/// A single-quoted SQL string, with an embedded quote doubled.
9008fn write_quoted(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
9009    f.write_str("'")?;
9010    for c in s.chars() {
9011        if c == '\'' {
9012            f.write_str("''")?;
9013        } else {
9014            write!(f, "{c}")?;
9015        }
9016    }
9017    f.write_str("'")
9018}
9019
9020impl fmt::Display for Literal {
9021    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9022        match self {
9023            Self::Integer(n) => write!(f, "{n}"),
9024            Self::Float(x) => {
9025                let s = format!("{x}");
9026                // Default Display for an integral f64 (e.g. 1.0) emits "1",
9027                // which would round-trip back to Integer. Force a dot.
9028                if s.contains('.') || s.contains('e') || s.contains('E') {
9029                    f.write_str(&s)
9030                } else {
9031                    write!(f, "{s}.0")
9032                }
9033            }
9034            Self::Numeric { unscaled, scale } => {
9035                // Render the exact decimal `unscaled / 10^scale`, preserving
9036                // scale (trailing zeros) — round-trips to the same literal.
9037                f.write_str(&render_exact_decimal(*unscaled, *scale))
9038            }
9039            Self::NumericBig(s) => f.write_str(s),
9040            // Printed exactly as the text form was, so a reader cannot
9041            // tell whether the constant was decoded or not.
9042            Self::Timestamp { text, .. } | Self::Date { text, .. } => write_quoted(f, text),
9043            Self::String(s) => write_quoted(f, s),
9044            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
9045            Self::Null => f.write_str("NULL"),
9046            // PG external array form. Display round-trip re-enters
9047            // through the column-typed text coerce, same as pgwire.
9048            Self::TextArray(items) => {
9049                f.write_str("'{")?;
9050                for (i, it) in items.iter().enumerate() {
9051                    if i > 0 {
9052                        f.write_str(",")?;
9053                    }
9054                    match it {
9055                        None => f.write_str("NULL")?,
9056                        Some(s) => {
9057                            f.write_str("\"")?;
9058                            for c in s.chars() {
9059                                match c {
9060                                    // array-element escapes
9061                                    '"' | '\\' => write!(f, "\\{c}")?,
9062                                    // the OUTER wrapper is a SQL string
9063                                    // literal — embedded quotes must
9064                                    // double, or the rendered form
9065                                    // (WAL replay parses it back) is
9066                                    // invalid SQL
9067                                    '\'' => f.write_str("''")?,
9068                                    _ => write!(f, "{c}")?,
9069                                }
9070                            }
9071                            f.write_str("\"")?;
9072                        }
9073                    }
9074                }
9075                f.write_str("}'")
9076            }
9077            Self::IntArray(items) => {
9078                f.write_str("'{")?;
9079                for (i, it) in items.iter().enumerate() {
9080                    if i > 0 {
9081                        f.write_str(",")?;
9082                    }
9083                    match it {
9084                        None => f.write_str("NULL")?,
9085                        Some(n) => write!(f, "{n}")?,
9086                    }
9087                }
9088                f.write_str("}'")
9089            }
9090            Self::BigIntArray(items) => {
9091                f.write_str("'{")?;
9092                for (i, it) in items.iter().enumerate() {
9093                    if i > 0 {
9094                        f.write_str(",")?;
9095                    }
9096                    match it {
9097                        None => f.write_str("NULL")?,
9098                        Some(n) => write!(f, "{n}")?,
9099                    }
9100                }
9101                f.write_str("}'")
9102            }
9103            Self::Vector(v) => {
9104                f.write_str("[")?;
9105                for (i, x) in v.iter().enumerate() {
9106                    if i > 0 {
9107                        f.write_str(", ")?;
9108                    }
9109                    let s = format!("{x}");
9110                    // Mirror Float Display: force a dot so re-parse stays
9111                    // numerically literal.
9112                    if s.contains('.') || s.contains('e') || s.contains('E') {
9113                        f.write_str(&s)?;
9114                    } else {
9115                        write!(f, "{s}.0")?;
9116                    }
9117                }
9118                f.write_str("]")
9119            }
9120            Self::Interval { text, .. } => {
9121                f.write_str("INTERVAL '")?;
9122                for c in text.chars() {
9123                    if c == '\'' {
9124                        f.write_str("''")?;
9125                    } else {
9126                        write!(f, "{c}")?;
9127                    }
9128                }
9129                f.write_str("'")
9130            }
9131        }
9132    }
9133}
9134
9135impl fmt::Display for BinOp {
9136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9137        f.write_str(match self {
9138            Self::Or => "OR",
9139            Self::And => "AND",
9140            Self::Eq => "=",
9141            Self::NotEq => "<>",
9142            Self::IsDistinctFrom => "IS DISTINCT FROM",
9143            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
9144            Self::IntDiv => "DIV",
9145            Self::Lt => "<",
9146            Self::LtEq => "<=",
9147            Self::Gt => ">",
9148            Self::GtEq => ">=",
9149            Self::Add => "+",
9150            Self::Sub => "-",
9151            Self::Mul => "*",
9152            Self::Div => "/",
9153            Self::Mod => "%",
9154            Self::L2Distance => "<->",
9155            Self::GeomParallel => "?||",
9156            Self::OverLeft => "&<",
9157            Self::OverRight => "&>",
9158            Self::GeomPerp => "?-|",
9159            Self::GeomSameAs => "~=",
9160            Self::ClosestPoint => "##",
9161            Self::GeomHoriz => "?-",
9162            Self::InnerProduct => "<#>",
9163            Self::CosineDistance => "<=>",
9164            Self::Concat => "||",
9165            Self::BitOr => "|",
9166            Self::BitAnd => "&",
9167            Self::BitXor => "#",
9168            Self::LogicalXor => "xor",
9169            Self::JsonGet => "->",
9170            Self::JsonGetText => "->>",
9171            Self::JsonGetPath => "#>",
9172            Self::JsonGetPathText => "#>>",
9173            Self::JsonContains => "@>",
9174            Self::JsonPathExists => "@?",
9175            Self::JsonContainedBy => "<@",
9176            Self::JsonKeyExists => "?",
9177            Self::JsonKeysAny => "?|",
9178            Self::JsonKeysAll => "?&",
9179            Self::JsonDeletePath => "#-",
9180            Self::TsMatch => "@@",
9181            Self::InetContainedBy => "<<",
9182            Self::InetContainedByEq => "<<=",
9183            Self::InetContains => ">>",
9184            Self::InetContainsEq => ">>=",
9185            Self::InetOverlap => "&&",
9186            Self::Intersects => "?#",
9187            Self::IsBelow => "<^",
9188            Self::IsAbove => ">^",
9189            Self::PatternLt => "~<~",
9190            Self::PatternLtEq => "~<=~",
9191            Self::PatternGt => "~>~",
9192            Self::PatternGtEq => "~>=~",
9193        })
9194    }
9195}
9196
9197/// Quote `s` as a PG double-quoted identifier when required (keyword,
9198/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
9199/// Otherwise return it as-is. Returns an owned `String` to keep the call site
9200/// uniform.
9201pub(crate) fn quote_ident(s: &str) -> String {
9202    let needs_quote = match s.chars().next() {
9203        None => true,
9204        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
9205        _ => {
9206            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
9207                || s.chars().any(|c| c.is_ascii_uppercase())
9208                || is_keyword(s)
9209        }
9210    };
9211    if !needs_quote {
9212        return s.to_string();
9213    }
9214    let mut out = String::with_capacity(s.len() + 2);
9215    out.push('"');
9216    for c in s.chars() {
9217        if c == '"' {
9218            out.push_str("\"\"");
9219        } else {
9220            out.push(c);
9221        }
9222    }
9223    out.push('"');
9224    out
9225}
9226
9227fn is_keyword(s: &str) -> bool {
9228    matches!(
9229        &*s.to_ascii_lowercase(),
9230        "select"
9231            | "from"
9232            | "where"
9233            | "as"
9234            | "null"
9235            | "true"
9236            | "false"
9237            | "and"
9238            | "or"
9239            | "not"
9240            | "create"
9241            | "table"
9242            | "insert"
9243            | "into"
9244            | "values"
9245            | "index"
9246            | "on"
9247            | "begin"
9248            | "commit"
9249            | "rollback"
9250            | "is"
9251            | "between"
9252            | "in"
9253            | "like"
9254            | "group"
9255            | "distinct"
9256            | "union"
9257            | "all"
9258            | "join"
9259            | "inner"
9260            | "left"
9261            | "cross"
9262            | "outer"
9263            | "default"
9264            | "savepoint"
9265            | "release"
9266            | "to"
9267            | "having"
9268            | "show"
9269            | "extract"
9270            | "offset"
9271            | "asc"
9272            | "desc"
9273            | "interval"
9274    )
9275}
9276
9277#[cfg(test)]
9278mod tests {
9279    use super::*;
9280    use alloc::vec;
9281
9282    #[test]
9283    fn integer_literal_renders_without_dot() {
9284        assert_eq!(Literal::Integer(42).to_string(), "42");
9285    }
9286
9287    #[test]
9288    fn integral_float_keeps_dot() {
9289        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
9290        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
9291        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
9292    }
9293
9294    #[test]
9295    fn string_literal_doubles_quote() {
9296        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
9297    }
9298
9299    #[test]
9300    fn bool_and_null_render_uppercase() {
9301        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
9302        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
9303        assert_eq!(Literal::Null.to_string(), "NULL");
9304    }
9305
9306    #[test]
9307    fn binary_op_always_parenthesised() {
9308        let e = Expr::Binary {
9309            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
9310            op: BinOp::Add,
9311            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
9312        };
9313        assert_eq!(e.to_string(), "(1 + 2)");
9314    }
9315
9316    #[test]
9317    fn select_star_from_table() {
9318        let s = SelectStatement {
9319            locking: None,
9320            items: vec![SelectItem::Wildcard],
9321            from: Some(FromClause {
9322                primary: TableRef {
9323                    name: "users".into(),
9324                    alias: None,
9325                    only: false,
9326                    as_of_segment: None,
9327                    unnest_expr: None,
9328                    unnest_column_aliases: Vec::new(),
9329                    with_ordinality: false,
9330                    generate_series_args: None,
9331                    lateral_subquery: None,
9332                    jsonb_each_text_arg: None,
9333                    table_fn_call: None,
9334                    rows_from: None,
9335                    json_table: None,
9336                    scalar_fn_item: false,
9337                },
9338                joins: vec![],
9339            }),
9340            where_: None,
9341            group_by: None,
9342            group_by_all: false,
9343            having: None,
9344            unions: vec![],
9345            order_by: Vec::new(),
9346            limit: None,
9347            offset: None,
9348            limit_with_ties: false,
9349            window_check_exprs: Vec::new(),
9350            distinct: false,
9351            distinct_on: Vec::new(),
9352            ctes: vec![],
9353        };
9354        assert_eq!(s.to_string(), "SELECT * FROM users");
9355    }
9356
9357    #[test]
9358    fn quote_ident_for_uppercase_and_keyword() {
9359        assert_eq!(quote_ident("foo"), "foo");
9360        assert_eq!(quote_ident("Foo"), "\"Foo\"");
9361        assert_eq!(quote_ident("select"), "\"select\"");
9362        assert_eq!(quote_ident(""), "\"\"");
9363        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
9364    }
9365}