Skip to main content

spg_sql/
ast.rs

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