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    Select(SelectStatement),
18    CreateTable(CreateTableStatement),
19    /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
20    /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
21    /// no-op so PG dumps that include extension declarations
22    /// (notably `pgvector`) load against SPG without splitting
23    /// init scripts. mailrs migration follow-up F3.
24    CreateExtension(String),
25    /// v7.9.27 — PG `DO $$ … $$ [LANGUAGE plpgsql];` block. SPG
26    /// has no PL/pgSQL; engine returns CommandOk no-op so
27    /// `pg_dump` output with idempotent DO migrations loads
28    /// against SPG without splitting scripts. The lexer
29    /// consumes the dollar-quoted body into a discarded
30    /// Token::String. mailrs migration follow-up H1.
31    DoBlock,
32    CreateIndex(CreateIndexStatement),
33    Insert(InsertStatement),
34    /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
35    Update(UpdateStatement),
36    /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
37    Delete(DeleteStatement),
38    Begin,
39    Commit,
40    Rollback,
41    /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
42    /// stack so a later `ROLLBACK TO <name>` can undo just the work
43    /// since this point.
44    Savepoint(String),
45    /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
46    /// named savepoint and discard later savepoints. Does not end the
47    /// transaction.
48    RollbackToSavepoint(String),
49    /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
50    /// rolling back. Keeps the work done since then.
51    ReleaseSavepoint(String),
52    /// `SHOW TABLES` — return the list of tables in the catalog.
53    ShowTables,
54    /// `SHOW COLUMNS FROM <table>` — return one row per column with
55    /// its declared name / type / nullability.
56    ShowColumns(String),
57    /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
58    /// Role is optional; defaults to `readonly` when omitted.
59    CreateUser(CreateUserStatement),
60    /// `DROP USER 'name'` (v4.1).
61    DropUser(String),
62    /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
63    ShowUsers,
64    /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
65    /// single-column text table describing the rewritten plan tree
66    /// for `inner`. `analyze` triggers an actual exec to attach
67    /// observed row counts and elapsed micros to each node.
68    Explain(ExplainStatement),
69    /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
70    /// Synchronous rebuild of an NSW index. With the optional
71    /// encoding clause, every stored cell at the indexed column is
72    /// also re-encoded through `coerce_value` before the new graph
73    /// builds.
74    AlterIndex(AlterIndexStatement),
75    /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
76    /// The only setting in v6.7.2 is `hot_tier_bytes`, which
77    /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
78    /// for the named table.
79    AlterTable(AlterTableStatement),
80    /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
81    /// The catalog row lives in `spg_publications`. Publisher-side
82    /// WAL filtering arrives in v6.1.5.
83    CreatePublication(CreatePublicationStatement),
84    /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
85    /// no-op when the publication does not exist.
86    DropPublication(String),
87    /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
88    /// publication ordered by name with `(name, scope_summary,
89    /// table_count)` columns. The scope summary is the human-
90    /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
91    /// TABLES EXCEPT …`; `table_count` is `NULL` for the
92    /// `AllTables` scope and the table-list length otherwise.
93    ShowPublications,
94    /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
95    /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
96    /// in `spg_subscriptions`; when the subscription is
97    /// `enabled = true` (default) the server spawns a
98    /// background worker that connects to `conn` and drains the
99    /// requested publication(s) into the local engine.
100    CreateSubscription(CreateSubscriptionStatement),
101    /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
102    /// PUBLICATION, silent no-op when absent. Stops the
103    /// associated worker thread before removing the row.
104    DropSubscription(String),
105    /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
106    /// subscription ordered by name with `(name, conn_str,
107    /// publications, enabled, last_received_pos)`.
108    ShowSubscriptions,
109    /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
110    /// Blocks until the local server's apply position reaches
111    /// `<pos>` or `<ms>` elapses. Server-layer command: the
112    /// engine refuses it (`EngineError::Unsupported`) since
113    /// `lag_state` lives in `spg-server`'s `ServerState`.
114    WaitForWalPosition {
115        pos: u64,
116        /// `None` → wait forever; `Some(ms)` → return after `ms`
117        /// milliseconds even if the target isn't reached.
118        timeout_ms: Option<u64>,
119    },
120    /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
121    /// table; `ANALYZE <name>` re-stats just one. Populates
122    /// `spg_statistic` with per-column null_frac + n_distinct +
123    /// 100-bucket equi-depth histogram.
124    Analyze(Option<String>),
125    /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
126    /// BTree-cold indices and merges small cold-tier segments
127    /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
128    /// 4 MiB) into a single larger segment per (table, index).
129    /// `WHERE` predicate filtering on which tables to compact is
130    /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
131    /// v6.7.3 only supports the bare form.
132    CompactColdSegments,
133}
134
135/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
136/// single fixed-shape DDL; the WITH-clause options PG supports
137/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
138/// scope for v6.1.4 — `enabled` defaults to true and there are
139/// no other knobs to set in v6.1.x.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct CreateSubscriptionStatement {
142    pub name: String,
143    /// Connection string in PG keyword=value form (e.g.
144    /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
145    /// `host` and `port` fields; the rest is reserved for
146    /// future v6.1.x options.
147    pub conn_str: String,
148    /// One or more publications on the remote side. Order is
149    /// preserved verbatim from the DDL; the worker requests them
150    /// in this order. v6.1.4 records the list; v6.1.5
151    /// publisher-side filtering enforces it.
152    pub publications: Vec<String>,
153}
154
155/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
156/// the [`PublicationScope`] shape. v6.1.2 only accepted
157/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
158/// variants by flipping the parser gate (no AST migration).
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct CreatePublicationStatement {
161    pub name: String,
162    pub scope: PublicationScope,
163}
164
165/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
166/// flips the parser gate for the `ForTables` / `AllTablesExcept`
167/// variants — the on-disk shape, snapshot serialisation, and the
168/// AST round-trip Display path were already in place in v6.1.2
169/// so this is a parser-only widening.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub enum PublicationScope {
172    AllTables,
173    ForTables(Vec<String>),
174    AllTablesExcept(Vec<String>),
175}
176
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct AlterIndexStatement {
179    pub name: String,
180    pub target: AlterIndexTarget,
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum AlterIndexTarget {
185    /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
186    /// rebuilds the existing graph in place without touching the
187    /// column encoding; `Some(enc)` re-encodes every cell first.
188    Rebuild { encoding: Option<VecEncoding> },
189}
190
191/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
192/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
193/// can add more SET subjects without changing the dispatch shape.
194#[derive(Debug, Clone, PartialEq)]
195pub struct AlterTableStatement {
196    pub name: String,
197    pub target: AlterTableTarget,
198}
199
200#[derive(Debug, Clone, PartialEq)]
201pub enum AlterTableTarget {
202    /// Per-table hot-tier byte budget override. The freezer
203    /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
204    SetHotTierBytes(u64),
205    /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
206    /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
207    /// Engine validates existing rows against the new constraint
208    /// before installing it.
209    AddForeignKey(ForeignKeyConstraint),
210    /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT name`. Removes the
211    /// constraint by user-supplied name; raises if no FK with that
212    /// name exists on the table.
213    DropForeignKey(String),
214}
215
216#[derive(Debug, Clone, PartialEq)]
217pub struct ExplainStatement {
218    pub analyze: bool,
219    pub inner: Box<SelectStatement>,
220    /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
221    /// advisor pass: after the regular plan tree, the engine
222    /// emits one suggestion line per column referenced in the
223    /// query's WHERE / JOIN that has no covering index on the
224    /// owning table.
225    pub suggest: bool,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct CreateUserStatement {
230    pub name: String,
231    pub password: String,
232    /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
233    /// the parser; the engine validates against `Role::parse` so a
234    /// typo lands as a runtime error with a clear message rather than
235    /// a parse failure.
236    pub role: String,
237}
238
239#[derive(Debug, Clone, PartialEq)]
240pub struct CreateIndexStatement {
241    pub name: String,
242    pub table: String,
243    pub column: String,
244    /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
245    /// graph for vector kNN); unspecified is the default B-tree index.
246    pub method: IndexMethod,
247    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
248    /// index name already exists, instead of raising `DuplicateIndex`.
249    pub if_not_exists: bool,
250    /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
251    /// non-key columns the planner should treat as "covered" by
252    /// this index when checking whether a query can run as an
253    /// index-only scan. Empty when no `INCLUDE` clause was given.
254    pub included_columns: Vec<String>,
255    /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
256    /// for which `<expr>` evaluates truthy enter the index;
257    /// queries whose `WHERE` clause's canonical Display form
258    /// matches this expression's Display form can be served by the
259    /// partial index. Stored as a parsed `Expr` so the engine
260    /// re-uses the existing evaluation path; storage persists the
261    /// Display form on the catalog snapshot.
262    pub partial_predicate: Option<Expr>,
263    /// v6.8.2 — expression-based index. When `Some(expr)`, the
264    /// index key is the result of `expr` evaluated on each row
265    /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
266    /// field still names the *primary* column the expression
267    /// touches so existing planner shortcuts that resolve a
268    /// column position stay valid. `None` = plain
269    /// column-reference index (the legacy shape).
270    pub expression: Option<Expr>,
271    /// v7.9.14 — extra column names after the leading column in a
272    /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
273    /// planner today still only uses the leading column for index
274    /// seeks; the extras are tracked verbatim so the same DDL
275    /// round-trips through WAL replay + catalog snapshot, and so
276    /// the engine can emit a clear warning at INDEX CREATE time
277    /// that only the leading column is currently honoured.
278    /// Composite BTree index keys land in v7.10.
279    pub extra_columns: Vec<String>,
280    /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
281    /// enforces uniqueness on the indexed key (combined with the
282    /// `partial_predicate` filter — only rows where the predicate
283    /// evaluates truthy enter the uniqueness check). Standard SQL
284    /// and PG's canonical way to express conditional uniqueness.
285    /// mailrs K1.
286    pub is_unique: bool,
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290pub enum IndexMethod {
291    /// Default — B-tree over `IndexKey`. Used for equality / range
292    /// lookups on scalar columns.
293    BTree,
294    /// `USING hnsw` — NSW graph for kNN over a vector column.
295    Hnsw,
296    /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
297    /// metadata that records (min_key, max_key) for each page in a
298    /// cold-tier segment, on the indexed column. The optimizer
299    /// can use these summaries to skip pages whose range does NOT
300    /// overlap a query's WHERE predicate. BRIN indexes carry no
301    /// in-memory data — the summaries live in the segment v2
302    /// envelope's sidecar. Created via the standard
303    /// `CREATE INDEX … USING brin (col)` syntax.
304    Brin,
305}
306
307#[derive(Debug, Clone, PartialEq)]
308pub struct CreateTableStatement {
309    pub name: String,
310    pub columns: Vec<ColumnDef>,
311    /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
312    /// table name already exists, instead of raising `DuplicateTable`.
313    pub if_not_exists: bool,
314    /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
315    /// constraints. Column-level `REFERENCES` (single-column inline
316    /// form) is normalised into this vec at parse time so the engine
317    /// sees one uniform list.
318    pub foreign_keys: Vec<ForeignKeyConstraint>,
319    /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
320    /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
321    /// Engine resolves each into a BTree index named after the
322    /// constraint's leading column at CREATE TABLE time; INSERT
323    /// path enforces composite uniqueness via row scan on the
324    /// leading column index.
325    pub table_constraints: Vec<TableConstraint>,
326}
327
328/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
329/// column list. Either a composite PRIMARY KEY or a UNIQUE
330/// (single- or multi-column).
331#[derive(Debug, Clone, PartialEq)]
332pub enum TableConstraint {
333    /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
334    /// referenced column. Engine builds a BTree index named
335    /// `<table>_pkey` and enforces composite uniqueness on INSERT.
336    PrimaryKey {
337        name: Option<String>,
338        columns: Vec<String>,
339    },
340    /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
341    /// named `<table>_<leading_col>_key` (single-column) or
342    /// `<table>_<leading_col>_<…>_key` (composite) and enforces
343    /// uniqueness on INSERT.
344    Unique {
345        name: Option<String>,
346        columns: Vec<String>,
347    },
348}
349
350#[derive(Debug, Clone, PartialEq)]
351pub struct ColumnDef {
352    pub name: String,
353    pub ty: ColumnTypeName,
354    pub nullable: bool,
355    /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
356    /// evaluates this once (with an empty row) and caches the resulting
357    /// `Value` on the column schema.
358    pub default: Option<Expr>,
359    /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
360    /// per such column and fills the slot when INSERT leaves it
361    /// unbound (omitted from a column-list INSERT or explicitly NULL).
362    pub auto_increment: bool,
363    /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
364    /// migration follow-up F1. Implies `NOT NULL`. Engine creates
365    /// an implicit BTree index named `<table>_pkey` over this
366    /// column at CREATE TABLE time, satisfying the parent-side
367    /// index requirement for any FOREIGN KEY pointing at it.
368    pub is_primary_key: bool,
369}
370
371/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
372/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
373/// parse into this shape — the column-level form has a single-entry
374/// `columns` / `parent_columns`.
375#[derive(Debug, Clone, PartialEq)]
376pub struct ForeignKeyConstraint {
377    /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
378    /// today but parses + stores it so a future ALTER TABLE DROP
379    /// CONSTRAINT can target by name (v7.6.8).
380    pub name: Option<String>,
381    /// Local columns participating in the FK (≥ 1).
382    pub columns: Vec<String>,
383    /// Referenced parent table.
384    pub parent_table: String,
385    /// Referenced parent columns. Must have the same arity as
386    /// `columns`; engine validates parent has a PK / UNIQUE index
387    /// on exactly this column set (v7.6.1).
388    pub parent_columns: Vec<String>,
389    /// `ON DELETE` action. Defaults to `Restrict` if absent.
390    pub on_delete: FkAction,
391    /// `ON UPDATE` action. Defaults to `Restrict` if absent.
392    pub on_update: FkAction,
393}
394
395/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
396#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub enum FkAction {
398    /// Reject the parent mutation if any child row references it.
399    /// SQL spec default; SPG default when no clause is given.
400    Restrict,
401    /// Recursively propagate the parent's delete / update to the
402    /// child rows. Same TX.
403    Cascade,
404    /// Set the child FK column(s) to NULL. Requires the FK columns
405    /// to be NULL-able.
406    SetNull,
407    /// Set the child FK column(s) to their declared DEFAULT.
408    /// Requires the child column(s) to have DEFAULT.
409    SetDefault,
410    /// SQL spec `NO ACTION` (deferred check). SPG treats this as
411    /// `Restrict` because the single-writer model has no deferred
412    /// constraint window; the keyword is accepted for compatibility.
413    NoAction,
414}
415
416/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
417/// optional `USING <encoding>` clause; omitting it keeps the
418/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
419/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
420/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
421/// binary16 (2× compression, ~3 decimal digits of precision).
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
423pub enum VecEncoding {
424    /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
425    /// uncompressed `vector` type wire / storage layout.
426    #[default]
427    F32,
428    /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
429    /// `spg_storage::quantize::Sq8Vector` for the math + recall
430    /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
431    /// dim ≥ 32).
432    Sq8,
433    /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
434    /// per-element. DDL keyword `HALF` (pgvector convention).
435    /// Bit-exact dequantise to f32 at the storage layer; no
436    /// rerank pass needed for kNN search.
437    F16,
438}
439
440impl fmt::Display for VecEncoding {
441    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442        match self {
443            Self::F32 => f.write_str("F32"),
444            Self::Sq8 => f.write_str("SQ8"),
445            // pgvector convention: DDL keyword is `HALF`, not `F16`.
446            Self::F16 => f.write_str("HALF"),
447        }
448    }
449}
450
451/// SQL-level type names. The mapping to the storage runtime's `DataType`
452/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454pub enum ColumnTypeName {
455    SmallInt,
456    Int,
457    BigInt,
458    Float,
459    Text,
460    /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
461    Varchar(u32),
462    /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
463    Char(u32),
464    Bool,
465    /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
466    /// `USING <encoding>` clause; omitting it surfaces as
467    /// `encoding = VecEncoding::F32` (the pre-v6 default).
468    Vector {
469        dim: u32,
470        encoding: VecEncoding,
471    },
472    /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
473    /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
474    Numeric(u8, u8),
475    /// `DATE` — calendar day, no time-of-day component.
476    Date,
477    /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
478    /// precision.
479    Timestamp,
480    /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
481    /// stores all timestamps as UTC microseconds-since-epoch and
482    /// does not carry per-row offset (PG's internal representation
483    /// is the same — TZ is a display convention). The distinction
484    /// from `TIMESTAMP` exists for the PG-wire layer to advertise
485    /// OID 1184 so sqlx-style clients decode into
486    /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
487    Timestamptz,
488    /// v4.9 `JSON` — text-backed JSON document. No parse-time
489    /// validation; the engine round-trips the literal verbatim.
490    /// PG OID 114 on the wire.
491    Json,
492    /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
493    /// PG OID 3802 on the wire so sqlx-style binary-typed clients
494    /// decode without a custom type registration.
495    Jsonb,
496    /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
497    /// Literal forms (decoded by the engine at coercion time):
498    ///   - PG hex form: `'\xDEADBEEF'`
499    ///   - Escape form: `'foo\\000bar'` (backslash octal triples)
500    Bytes,
501    /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
502    /// OID 1009. Literal forms accepted by the parser:
503    ///   - `ARRAY['a', 'b', NULL]`
504    ///   - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
505    ///     form at coerce time)
506    TextArray,
507}
508
509impl fmt::Display for ColumnTypeName {
510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511        match self {
512            Self::SmallInt => f.write_str("SMALLINT"),
513            Self::Int => f.write_str("INT"),
514            Self::BigInt => f.write_str("BIGINT"),
515            Self::Float => f.write_str("FLOAT"),
516            Self::Text => f.write_str("TEXT"),
517            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
518            Self::Char(n) => write!(f, "CHAR({n})"),
519            Self::Bool => f.write_str("BOOL"),
520            Self::Vector { dim, encoding } => match encoding {
521                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
522                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
523                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
524            },
525            Self::Json => f.write_str("JSON"),
526            Self::Jsonb => f.write_str("JSONB"),
527            Self::Bytes => f.write_str("BYTEA"),
528            Self::TextArray => f.write_str("TEXT[]"),
529            Self::Numeric(p, s) => {
530                if *s == 0 {
531                    write!(f, "NUMERIC({p})")
532                } else {
533                    write!(f, "NUMERIC({p}, {s})")
534                }
535            }
536            Self::Date => f.write_str("DATE"),
537            Self::Timestamp => f.write_str("TIMESTAMP"),
538            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
539        }
540    }
541}
542
543/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
544/// engine evaluates `expr` per matched row in the table's row order
545/// and rewrites cells in place. Indexed columns are dropped + re-
546/// inserted into the affected B-tree on each row change.
547#[derive(Debug, Clone, PartialEq)]
548pub struct UpdateStatement {
549    pub table: String,
550    pub assignments: Vec<(String, Expr)>,
551    pub where_: Option<Expr>,
552    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
553    /// clause (legacy CommandComplete path). Some = engine
554    /// evaluates the projection over each mutated row and
555    /// streams the result as a Rows QueryResult.
556    pub returning: Option<Vec<SelectItem>>,
557}
558
559/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
560/// from the active catalog and prunes them from every index.
561#[derive(Debug, Clone, PartialEq)]
562pub struct DeleteStatement {
563    pub table: String,
564    pub where_: Option<Expr>,
565    /// v7.9.4 — `RETURNING <projection>`.
566    pub returning: Option<Vec<SelectItem>>,
567}
568
569#[derive(Debug, Clone, PartialEq)]
570pub struct InsertStatement {
571    pub table: String,
572    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
573    /// `None`, every tuple is positional and must match the table arity.
574    /// When `Some`, the engine maps each tuple slot to the named column and
575    /// fills the rest with NULL (must be nullable).
576    pub columns: Option<Vec<String>>,
577    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
578    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`.
579    pub rows: Vec<Vec<Expr>>,
580    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
581    /// upsert clause. None = legacy INSERT (conflict raises a
582    /// DuplicateKey error). mailrs migration blocker #2.
583    pub on_conflict: Option<OnConflictClause>,
584    /// v7.9.4 — `RETURNING <projection>`.
585    pub returning: Option<Vec<SelectItem>>,
586}
587
588/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
589#[derive(Debug, Clone, PartialEq)]
590pub struct OnConflictClause {
591    /// Local columns that identify the conflict (must match a
592    /// UNIQUE / PRIMARY KEY index on the target table). Empty
593    /// list means the user wrote `ON CONFLICT DO …` without a
594    /// target — engine picks the table's first BTree index by
595    /// convention.
596    pub target_columns: Vec<String>,
597    /// The action on conflict.
598    pub action: OnConflictAction,
599}
600
601/// v7.9.7 — action on conflict.
602#[derive(Debug, Clone, PartialEq)]
603pub enum OnConflictAction {
604    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
605    /// silently skips conflicting ones.
606    Nothing,
607    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
608    /// may reference `EXCLUDED.col` to read the incoming row's
609    /// value (engine wires `EXCLUDED` as a virtual table).
610    Update {
611        assignments: Vec<(String, Expr)>,
612        where_: Option<Expr>,
613    },
614}
615
616#[derive(Debug, Clone, PartialEq)]
617pub struct SelectStatement {
618    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
619    /// expressions, materialised once at query start before the
620    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
621    /// only — no `WITH RECURSIVE` for v4.x.
622    pub ctes: Vec<Cte>,
623    pub distinct: bool,
624    pub items: Vec<SelectItem>,
625    pub from: Option<FromClause>,
626    pub where_: Option<Expr>,
627    pub group_by: Option<Vec<Expr>>,
628    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
629    /// expands `group_by` to every non-aggregate SELECT-list item
630    /// before the executor runs. Mutually exclusive with an
631    /// explicit `group_by` list (the parser sets exactly one).
632    pub group_by_all: bool,
633    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
634    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
635    /// aggregate executor resolves them through the same synthetic
636    /// schema used for the SELECT items.
637    pub having: Option<Expr>,
638    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
639    /// itself a `SelectStatement` with `order_by = None` and `limit =
640    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
641    /// top of the chain).
642    pub unions: Vec<(UnionKind, SelectStatement)>,
643    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
644    /// Keys are matched left-to-right: first key decides, ties break
645    /// to the second, etc.
646    pub order_by: Vec<OrderBy>,
647    /// `LIMIT <n>` — bound on row output. `n` is an integer
648    /// literal **or** (v7.9.24) a placeholder `$N` resolved
649    /// against the prepared-statement Bind values. mailrs
650    /// migration follow-up H2.
651    pub limit: Option<LimitExpr>,
652    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
653    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
654    pub offset: Option<LimitExpr>,
655}
656
657/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
658/// time or a placeholder `$N` resolved during extended-query
659/// Bind. mailrs migration follow-up H2.
660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661pub enum LimitExpr {
662    /// `LIMIT 10` — value known at parse time.
663    Literal(u32),
664    /// `LIMIT $N` — the 1-based parameter index, resolved against
665    /// the bind values when the prepared statement executes.
666    Placeholder(u16),
667}
668
669impl fmt::Display for LimitExpr {
670    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
671        match self {
672            Self::Literal(n) => write!(f, "{n}"),
673            Self::Placeholder(n) => write!(f, "${n}"),
674        }
675    }
676}
677
678impl LimitExpr {
679    /// Convenience for the simple-query path where no placeholders
680    /// can possibly exist. Returns the literal value or `None` if
681    /// this is a placeholder (caller must surface as Unsupported).
682    pub fn as_literal(self) -> Option<u32> {
683        match self {
684            Self::Literal(n) => Some(n),
685            Self::Placeholder(_) => None,
686        }
687    }
688}
689
690/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
691/// the engine's `substitute_placeholders` pass these are
692/// always Literal; in the simple-query path a Placeholder
693/// shape returns None (executor surfaces as
694/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
695impl SelectStatement {
696    #[must_use]
697    pub fn limit_literal(&self) -> Option<u32> {
698        self.limit.and_then(LimitExpr::as_literal)
699    }
700    #[must_use]
701    pub fn offset_literal(&self) -> Option<u32> {
702        self.offset.and_then(LimitExpr::as_literal)
703    }
704}
705
706#[derive(Debug, Clone, PartialEq)]
707pub struct Cte {
708    pub name: String,
709    pub body: SelectStatement,
710    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
711    /// RECURSIVE keyword. Applies to every CTE in the clause per
712    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
713    /// allowed; the engine just runs it once.
714    pub recursive: bool,
715    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
716    /// non-empty, these override the body's output column names
717    /// position-by-position; the engine errors out if the count
718    /// doesn't match the body's projection width.
719    pub column_overrides: Vec<String>,
720}
721
722#[derive(Debug, Clone, PartialEq)]
723pub struct OrderBy {
724    pub expr: Expr,
725    /// `false` = ASC (default), `true` = DESC.
726    pub desc: bool,
727}
728
729#[derive(Debug, Clone, Copy, PartialEq, Eq)]
730pub enum UnionKind {
731    /// `UNION` — dedupes the combined set.
732    Distinct,
733    /// `UNION ALL` — concatenates without dedup.
734    All,
735}
736
737#[derive(Debug, Clone, PartialEq)]
738pub enum SelectItem {
739    Wildcard,
740    Expr { expr: Expr, alias: Option<String> },
741}
742
743#[derive(Debug, Clone, PartialEq)]
744pub struct TableRef {
745    pub name: String,
746    pub alias: Option<String>,
747    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
748    /// When `Some(id)`, the scan restricts to rows that live in
749    /// segment `<id>` only — useful for forensic inspection of a
750    /// specific freezer-emitted segment without exposing the hot
751    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
752    /// is STABILITY carve-out for v6.10 — needs the freezer to
753    /// stamp each segment with a wall-clock at creation time.
754    pub as_of_segment: Option<u32>,
755}
756
757/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
758/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
759/// joins evaluate left-associatively in nested-loop order.
760#[derive(Debug, Clone, PartialEq)]
761pub struct FromClause {
762    pub primary: TableRef,
763    pub joins: Vec<FromJoin>,
764}
765
766#[derive(Debug, Clone, PartialEq)]
767pub struct FromJoin {
768    pub kind: JoinKind,
769    pub table: TableRef,
770    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
771    pub on: Option<Expr>,
772}
773
774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
775pub enum JoinKind {
776    Inner,
777    Left,
778    Cross,
779}
780
781#[derive(Debug, Clone, PartialEq)]
782pub enum Expr {
783    Literal(Literal),
784    Column(ColumnName),
785    /// v6.1.1 — `$N` parameter placeholder for the extended query
786    /// protocol. The number is 1-based per PostgreSQL convention.
787    /// Evaluation looks up `params[N-1]` from the prepared-statement
788    /// bind buffer; out-of-range indices raise a runtime error
789    /// (same shape as a column-not-found miss).
790    Placeholder(u16),
791    Binary {
792        lhs: Box<Expr>,
793        op: BinOp,
794        rhs: Box<Expr>,
795    },
796    Unary {
797        op: UnOp,
798        expr: Box<Expr>,
799    },
800    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
801    /// TEXT, BOOL targets; engine coerces at evaluation time.
802    Cast {
803        expr: Box<Expr>,
804        target: CastTarget,
805    },
806    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
807    IsNull {
808        expr: Box<Expr>,
809        negated: bool,
810    },
811    /// Function call `name(args...)`. v1.4 supports a small built-in set
812    /// (length, upper, lower, abs, coalesce); unknown names error at eval
813    /// time so the parser stays open for v1.5 aggregates.
814    FunctionCall {
815        name: String,
816        args: Vec<Expr>,
817    },
818    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
819    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
820    /// the next char (so `\%` matches a literal `%`).
821    Like {
822        expr: Box<Expr>,
823        pattern: Box<Expr>,
824        negated: bool,
825    },
826    /// v4.12 window function call: `name(args) OVER (PARTITION BY
827    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
828    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
829    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
830    /// unordered windows and "from start of partition through
831    /// current row" for ordered windows — no explicit ROWS /
832    /// RANGE clause in v4.12 MVP.
833    WindowFunction {
834        name: String,
835        args: Vec<Expr>,
836        partition_by: Vec<Expr>,
837        order_by: Vec<(Expr, bool /* desc */)>,
838        /// v4.20 explicit frame. `None` means "use the default":
839        /// whole-partition when unordered, running aggregate from
840        /// partition start through current row when ordered.
841        frame: Option<WindowFrame>,
842        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
843        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
844        /// `Respect` (PG / ANSI default — NULLs participate). Other
845        /// window functions ignore this flag.
846        null_treatment: NullTreatment,
847    },
848    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
849    /// position. Must return exactly one row × one column at eval
850    /// time; the engine errors out otherwise. Uncorrelated only —
851    /// the inner SELECT cannot reference outer columns.
852    ScalarSubquery(Box<SelectStatement>),
853    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
854    /// projection is ignored; only row-count matters.
855    Exists {
856        subquery: Box<SelectStatement>,
857        negated: bool,
858    },
859    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
860    /// project exactly one column; membership is tested by Eq
861    /// against each row's value (NULL handling follows ANSI:
862    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
863    InSubquery {
864        expr: Box<Expr>,
865        subquery: Box<SelectStatement>,
866        negated: bool,
867    },
868    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
869    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
870    /// because the `FROM` keyword is what separates the two halves,
871    /// not a comma.
872    Extract {
873        field: ExtractField,
874        source: Box<Expr>,
875    },
876    /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
877    /// element is evaluated independently; NULLs are allowed.
878    /// v7.10 supports only single-dimension TEXT[] semantically;
879    /// non-text elements coerce at engine evaluation time when
880    /// the surrounding context (column type / cast) makes the
881    /// target clear.
882    Array(Vec<Expr>),
883    /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
884    /// engine returns NULL for out-of-range indices.
885    ArraySubscript {
886        target: Box<Expr>,
887        index: Box<Expr>,
888    },
889    /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
890    /// operator is the comparison binary op (Eq / Ne / Lt / …);
891    /// the engine desugars: `ANY` returns true if any element
892    /// satisfies; `ALL` returns true only if every element does.
893    /// NULL handling follows PG's three-valued logic.
894    AnyAll {
895        expr: Box<Expr>,
896        op: BinOp,
897        array: Box<Expr>,
898        /// `true` = ANY, `false` = ALL.
899        is_any: bool,
900    },
901}
902
903/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
904/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
905/// in the offset walk. `Ignore` causes the function to skip NULL
906/// values in the argument expression, returning the next non-NULL.
907#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
908pub enum NullTreatment {
909    #[default]
910    Respect,
911    Ignore,
912}
913
914/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
915/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
916/// where end implicitly = CURRENT ROW.
917#[derive(Debug, Clone, PartialEq, Eq)]
918pub struct WindowFrame {
919    pub kind: FrameKind,
920    pub start: FrameBound,
921    pub end: Option<FrameBound>,
922}
923
924#[derive(Debug, Clone, Copy, PartialEq, Eq)]
925pub enum FrameKind {
926    Rows,
927    Range,
928}
929
930#[derive(Debug, Clone, PartialEq, Eq)]
931pub enum FrameBound {
932    UnboundedPreceding,
933    OffsetPreceding(u64),
934    CurrentRow,
935    OffsetFollowing(u64),
936    UnboundedFollowing,
937}
938
939impl fmt::Display for FrameBound {
940    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941        match self {
942            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
943            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
944            Self::CurrentRow => f.write_str("CURRENT ROW"),
945            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
946            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
947        }
948    }
949}
950
951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952pub enum ExtractField {
953    Year,
954    Month,
955    Day,
956    Hour,
957    Minute,
958    Second,
959    Microsecond,
960}
961
962impl fmt::Display for ExtractField {
963    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
964        f.write_str(match self {
965            Self::Year => "YEAR",
966            Self::Month => "MONTH",
967            Self::Day => "DAY",
968            Self::Hour => "HOUR",
969            Self::Minute => "MINUTE",
970            Self::Second => "SECOND",
971            Self::Microsecond => "MICROSECOND",
972        })
973    }
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
977pub enum CastTarget {
978    Int,
979    BigInt,
980    Float,
981    Text,
982    Bool,
983    Vector,
984    Date,
985    Timestamp,
986    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
987    /// H3a. Engine reuses the existing runtime-interval / timestamp
988    /// paths (parse the text input, return the matching Value).
989    Interval,
990    Timestamptz,
991    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
992    /// types (v7.9.0); the cast just routes Text→Json with the
993    /// requested OID for the wire layer.
994    Json,
995    Jsonb,
996    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
997    /// compatibility; engine surfaces as Unsupported with a
998    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
999    RegType,
1000    RegClass,
1001    /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
1002    /// the PG external array form `{a,b,NULL}`.
1003    TextArray,
1004}
1005
1006impl fmt::Display for CastTarget {
1007    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1008        f.write_str(match self {
1009            Self::Int => "int",
1010            Self::BigInt => "bigint",
1011            Self::Float => "float",
1012            Self::Text => "text",
1013            Self::Bool => "bool",
1014            Self::Vector => "vector",
1015            Self::Interval => "interval",
1016            Self::Timestamptz => "timestamptz",
1017            Self::Json => "json",
1018            Self::Jsonb => "jsonb",
1019            Self::RegType => "regtype",
1020            Self::RegClass => "regclass",
1021            Self::Date => "date",
1022            Self::Timestamp => "timestamp",
1023            Self::TextArray => "TEXT[]",
1024        })
1025    }
1026}
1027
1028#[derive(Debug, Clone, PartialEq)]
1029pub enum Literal {
1030    Integer(i64),
1031    Float(f64),
1032    String(String),
1033    Bool(bool),
1034    Null,
1035    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
1036    Vector(Vec<f32>),
1037    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
1038    /// Split into a months part (because a month is not a fixed number of
1039    /// days) and a microseconds part (everything sub-month). `text` keeps
1040    /// the original spelling so Display round-trips byte-for-byte.
1041    Interval {
1042        months: i32,
1043        micros: i64,
1044        text: String,
1045    },
1046}
1047
1048#[derive(Debug, Clone, PartialEq, Eq)]
1049pub struct ColumnName {
1050    pub qualifier: Option<String>,
1051    pub name: String,
1052}
1053
1054#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1055pub enum BinOp {
1056    Or,
1057    And,
1058    Eq,
1059    NotEq,
1060    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
1061    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
1062    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
1063    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
1064    /// PG-style JOIN ON predicates and pg_dump output.
1065    IsDistinctFrom,
1066    IsNotDistinctFrom,
1067    Lt,
1068    LtEq,
1069    Gt,
1070    GtEq,
1071    Add,
1072    Sub,
1073    Mul,
1074    Div,
1075    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
1076    /// operands of equal dimension; engine returns `Value::Float(d)`.
1077    L2Distance,
1078    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
1079    /// more similar" remains true (matches pgvector's published convention).
1080    InnerProduct,
1081    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
1082    CosineDistance,
1083    /// SQL string concatenation `||`. NULL propagates.
1084    Concat,
1085    /// v4.14 `json -> key` — element access by string key (object)
1086    /// or integer index (array). Returns a JSON value.
1087    JsonGet,
1088    /// v4.14 `json ->> key` — same access, returns the result as
1089    /// TEXT (unwraps a top-level JSON string; renders other scalars
1090    /// as their canonical text).
1091    JsonGetText,
1092    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
1093    /// text array literal like `'{a,0,b}'`. Returns JSON.
1094    JsonGetPath,
1095    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
1096    JsonGetPathText,
1097    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
1098    /// when every key/value in `sub_json` is structurally present in
1099    /// the left side. Matches PG semantics (top-level + recursive).
1100    JsonContains,
1101}
1102
1103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1104pub enum UnOp {
1105    Not,
1106    Neg,
1107}
1108
1109// --- Display impls (round-trip-safe) --------------------------------------
1110
1111impl fmt::Display for Statement {
1112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1113        match self {
1114            Self::Select(s) => s.fmt(f),
1115            Self::CreateTable(s) => s.fmt(f),
1116            Self::CreateIndex(s) => s.fmt(f),
1117            Self::Insert(s) => s.fmt(f),
1118            Self::Update(s) => s.fmt(f),
1119            Self::Delete(s) => s.fmt(f),
1120            Self::Begin => f.write_str("BEGIN"),
1121            Self::Commit => f.write_str("COMMIT"),
1122            Self::Rollback => f.write_str("ROLLBACK"),
1123            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
1124            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
1125            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
1126            Self::ShowTables => f.write_str("SHOW TABLES"),
1127            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
1128            Self::CreateUser(s) => write!(
1129                f,
1130                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
1131                quote_ident(&s.name),
1132                s.role
1133            ),
1134            Self::DropUser(n) => write!(f, "DROP USER {}", quote_ident(n)),
1135            Self::ShowUsers => f.write_str("SHOW USERS"),
1136            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
1137            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
1138            Self::CreateSubscription(s) => {
1139                write!(
1140                    f,
1141                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
1142                    quote_ident(&s.name),
1143                    s.conn_str.replace('\'', "''")
1144                )?;
1145                for (i, p) in s.publications.iter().enumerate() {
1146                    if i > 0 {
1147                        f.write_str(", ")?;
1148                    }
1149                    write!(f, "{}", quote_ident(p))?;
1150                }
1151                Ok(())
1152            }
1153            Self::DropSubscription(name) => {
1154                write!(f, "DROP SUBSCRIPTION {}", quote_ident(name))
1155            }
1156            Self::WaitForWalPosition { pos, timeout_ms } => {
1157                write!(f, "WAIT FOR WAL POSITION {pos}")?;
1158                if let Some(ms) = timeout_ms {
1159                    write!(f, " WITH TIMEOUT {ms}")?;
1160                }
1161                Ok(())
1162            }
1163            Self::Analyze(None) => f.write_str("ANALYZE"),
1164            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
1165            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
1166            Self::Explain(e) => {
1167                if e.suggest {
1168                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
1169                } else if e.analyze {
1170                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
1171                } else {
1172                    write!(f, "EXPLAIN {}", e.inner)
1173                }
1174            }
1175            Self::AlterIndex(a) => {
1176                write!(f, "ALTER INDEX {} ", quote_ident(&a.name))?;
1177                match a.target {
1178                    AlterIndexTarget::Rebuild { encoding } => {
1179                        f.write_str("REBUILD")?;
1180                        if let Some(enc) = encoding {
1181                            write!(f, " WITH (encoding = {enc})")?;
1182                        }
1183                        Ok(())
1184                    }
1185                }
1186            }
1187            Self::AlterTable(a) => {
1188                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
1189                match &a.target {
1190                    AlterTableTarget::SetHotTierBytes(n) => {
1191                        write!(f, "SET hot_tier_bytes = {n}")
1192                    }
1193                    AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
1194                    AlterTableTarget::DropForeignKey(name) => {
1195                        write!(f, "DROP CONSTRAINT {}", quote_ident(name))
1196                    }
1197                }
1198            }
1199            Self::CreatePublication(p) => {
1200                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
1201                match &p.scope {
1202                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
1203                    PublicationScope::ForTables(ts) => {
1204                        f.write_str(" FOR TABLE ")?;
1205                        for (i, t) in ts.iter().enumerate() {
1206                            if i > 0 {
1207                                f.write_str(", ")?;
1208                            }
1209                            write!(f, "{}", quote_ident(t))?;
1210                        }
1211                        Ok(())
1212                    }
1213                    PublicationScope::AllTablesExcept(ts) => {
1214                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
1215                        for (i, t) in ts.iter().enumerate() {
1216                            if i > 0 {
1217                                f.write_str(", ")?;
1218                            }
1219                            write!(f, "{}", quote_ident(t))?;
1220                        }
1221                        Ok(())
1222                    }
1223                }
1224            }
1225            Self::CreateExtension(name) => {
1226                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
1227            }
1228            Self::DoBlock => f.write_str("DO $$ /* SPG no-op */ $$"),
1229            Self::DropPublication(name) => {
1230                write!(f, "DROP PUBLICATION {}", quote_ident(name))
1231            }
1232        }
1233    }
1234}
1235
1236impl fmt::Display for CreateIndexStatement {
1237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1238        if self.is_unique {
1239            f.write_str("CREATE UNIQUE INDEX ")?;
1240        } else {
1241            f.write_str("CREATE INDEX ")?;
1242        }
1243        if self.if_not_exists {
1244            f.write_str("IF NOT EXISTS ")?;
1245        }
1246        write!(
1247            f,
1248            "{} ON {} ",
1249            quote_ident(&self.name),
1250            quote_ident(&self.table)
1251        )?;
1252        match self.method {
1253            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
1254            IndexMethod::Brin => f.write_str("USING brin ")?,
1255            IndexMethod::BTree => {}
1256        }
1257        if let Some(expr) = &self.expression {
1258            write!(f, "({})", expr)?;
1259        } else if self.extra_columns.is_empty() {
1260            write!(f, "({})", quote_ident(&self.column))?;
1261        } else {
1262            // v7.9.14 — multi-column key. Emit each column quoted
1263            // so the round-tripped form re-parses to identical AST.
1264            f.write_str("(")?;
1265            write!(f, "{}", quote_ident(&self.column))?;
1266            for c in &self.extra_columns {
1267                write!(f, ", {}", quote_ident(c))?;
1268            }
1269            f.write_str(")")?;
1270        }
1271        if !self.included_columns.is_empty() {
1272            f.write_str(" INCLUDE (")?;
1273            for (i, c) in self.included_columns.iter().enumerate() {
1274                if i > 0 {
1275                    f.write_str(", ")?;
1276                }
1277                write!(f, "{}", quote_ident(c))?;
1278            }
1279            f.write_str(")")?;
1280        }
1281        if let Some(pred) = &self.partial_predicate {
1282            write!(f, " WHERE {}", pred)?;
1283        }
1284        Ok(())
1285    }
1286}
1287
1288impl fmt::Display for CreateTableStatement {
1289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1290        f.write_str("CREATE TABLE ")?;
1291        if self.if_not_exists {
1292            f.write_str("IF NOT EXISTS ")?;
1293        }
1294        write!(f, "{} (", quote_ident(&self.name))?;
1295        for (i, col) in self.columns.iter().enumerate() {
1296            if i > 0 {
1297                f.write_str(", ")?;
1298            }
1299            write!(f, "{col}")?;
1300        }
1301        // v7.6.0 — render FK constraints in table-level form, after
1302        // the column list. WAL replay round-trips through Display, so
1303        // every FK must serialise here for replay to reconstruct the
1304        // schema bit-for-bit.
1305        for fk in &self.foreign_keys {
1306            f.write_str(", ")?;
1307            write!(f, "{fk}")?;
1308        }
1309        f.write_str(")")
1310    }
1311}
1312
1313impl fmt::Display for ForeignKeyConstraint {
1314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1315        if let Some(name) = &self.name {
1316            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
1317        }
1318        f.write_str("FOREIGN KEY (")?;
1319        for (i, c) in self.columns.iter().enumerate() {
1320            if i > 0 {
1321                f.write_str(", ")?;
1322            }
1323            f.write_str(&quote_ident(c))?;
1324        }
1325        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
1326        if !self.parent_columns.is_empty() {
1327            f.write_str(" (")?;
1328            for (i, c) in self.parent_columns.iter().enumerate() {
1329                if i > 0 {
1330                    f.write_str(", ")?;
1331                }
1332                f.write_str(&quote_ident(c))?;
1333            }
1334            f.write_str(")")?;
1335        }
1336        // Only render non-default actions to keep Display output
1337        // close to user input. SPG's default is RESTRICT (matches
1338        // SQL spec).
1339        if self.on_delete != FkAction::Restrict {
1340            write!(f, " ON DELETE {}", self.on_delete)?;
1341        }
1342        if self.on_update != FkAction::Restrict {
1343            write!(f, " ON UPDATE {}", self.on_update)?;
1344        }
1345        Ok(())
1346    }
1347}
1348
1349impl fmt::Display for FkAction {
1350    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1351        match self {
1352            Self::Restrict => f.write_str("RESTRICT"),
1353            Self::Cascade => f.write_str("CASCADE"),
1354            Self::SetNull => f.write_str("SET NULL"),
1355            Self::SetDefault => f.write_str("SET DEFAULT"),
1356            Self::NoAction => f.write_str("NO ACTION"),
1357        }
1358    }
1359}
1360
1361impl fmt::Display for ColumnDef {
1362    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1363        write!(f, "{} {}", quote_ident(&self.name), self.ty)?;
1364        if let Some(d) = &self.default {
1365            write!(f, " DEFAULT {d}")?;
1366        }
1367        if self.auto_increment {
1368            f.write_str(" AUTO_INCREMENT")?;
1369        }
1370        if !self.nullable {
1371            f.write_str(" NOT NULL")?;
1372        }
1373        Ok(())
1374    }
1375}
1376
1377impl fmt::Display for InsertStatement {
1378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1379        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
1380        if let Some(cols) = &self.columns {
1381            f.write_str(" (")?;
1382            for (i, c) in cols.iter().enumerate() {
1383                if i > 0 {
1384                    f.write_str(", ")?;
1385                }
1386                f.write_str(&quote_ident(c))?;
1387            }
1388            f.write_str(")")?;
1389        }
1390        f.write_str(" VALUES ")?;
1391        for (ri, row) in self.rows.iter().enumerate() {
1392            if ri > 0 {
1393                f.write_str(", ")?;
1394            }
1395            f.write_str("(")?;
1396            for (i, v) in row.iter().enumerate() {
1397                if i > 0 {
1398                    f.write_str(", ")?;
1399                }
1400                write!(f, "{v}")?;
1401            }
1402            f.write_str(")")?;
1403        }
1404        Ok(())
1405    }
1406}
1407
1408impl fmt::Display for UpdateStatement {
1409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
1411        for (i, (col, expr)) in self.assignments.iter().enumerate() {
1412            if i > 0 {
1413                f.write_str(", ")?;
1414            }
1415            write!(f, "{} = {expr}", quote_ident(col))?;
1416        }
1417        if let Some(w) = &self.where_ {
1418            write!(f, " WHERE {w}")?;
1419        }
1420        Ok(())
1421    }
1422}
1423
1424impl fmt::Display for DeleteStatement {
1425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1426        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
1427        if let Some(w) = &self.where_ {
1428            write!(f, " WHERE {w}")?;
1429        }
1430        Ok(())
1431    }
1432}
1433
1434impl fmt::Display for SelectStatement {
1435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436        write_bare_select(self, f)?;
1437        for (kind, peer) in &self.unions {
1438            f.write_str(match kind {
1439                UnionKind::Distinct => " UNION ",
1440                UnionKind::All => " UNION ALL ",
1441            })?;
1442            write_bare_select(peer, f)?;
1443        }
1444        if !self.order_by.is_empty() {
1445            f.write_str(" ORDER BY ")?;
1446            for (i, o) in self.order_by.iter().enumerate() {
1447                if i > 0 {
1448                    f.write_str(", ")?;
1449                }
1450                write!(f, "{}", o.expr)?;
1451                if o.desc {
1452                    f.write_str(" DESC")?;
1453                }
1454            }
1455        }
1456        if let Some(n) = &self.limit {
1457            write!(f, " LIMIT {n}")?;
1458        }
1459        if let Some(o) = &self.offset {
1460            write!(f, " OFFSET {o}")?;
1461        }
1462        Ok(())
1463    }
1464}
1465
1466fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467    f.write_str("SELECT ")?;
1468    if s.distinct {
1469        f.write_str("DISTINCT ")?;
1470    }
1471    write_bare_select_body(s, f)
1472}
1473
1474fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475    for (i, item) in s.items.iter().enumerate() {
1476        if i > 0 {
1477            f.write_str(", ")?;
1478        }
1479        write!(f, "{item}")?;
1480    }
1481    if let Some(t) = &s.from {
1482        write!(f, " FROM {t}")?;
1483    }
1484    if let Some(e) = &s.where_ {
1485        write!(f, " WHERE {e}")?;
1486    }
1487    if let Some(gs) = &s.group_by {
1488        f.write_str(" GROUP BY ")?;
1489        for (i, g) in gs.iter().enumerate() {
1490            if i > 0 {
1491                f.write_str(", ")?;
1492            }
1493            write!(f, "{g}")?;
1494        }
1495    }
1496    if let Some(h) = &s.having {
1497        write!(f, " HAVING {h}")?;
1498    }
1499    Ok(())
1500}
1501
1502impl fmt::Display for SelectItem {
1503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504        match self {
1505            Self::Wildcard => f.write_str("*"),
1506            Self::Expr { expr, alias } => {
1507                write!(f, "{expr}")?;
1508                if let Some(a) = alias {
1509                    write!(f, " AS {}", quote_ident(a))?;
1510                }
1511                Ok(())
1512            }
1513        }
1514    }
1515}
1516
1517impl fmt::Display for FromClause {
1518    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1519        write!(f, "{}", self.primary)?;
1520        for j in &self.joins {
1521            match j.kind {
1522                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
1523                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
1524                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
1525            }
1526            if let Some(on) = &j.on {
1527                write!(f, " ON {on}")?;
1528            }
1529        }
1530        Ok(())
1531    }
1532}
1533
1534impl fmt::Display for TableRef {
1535    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1536        write!(f, "{}", quote_ident(&self.name))?;
1537        if let Some(a) = &self.alias {
1538            write!(f, " AS {}", quote_ident(a))?;
1539        }
1540        Ok(())
1541    }
1542}
1543
1544impl fmt::Display for ColumnName {
1545    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1546        if let Some(q) = &self.qualifier {
1547            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
1548        } else {
1549            write!(f, "{}", quote_ident(&self.name))
1550        }
1551    }
1552}
1553
1554impl fmt::Display for Expr {
1555    #[allow(clippy::too_many_lines)]
1556    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557        match self {
1558            Self::Literal(l) => write!(f, "{l}"),
1559            Self::Column(c) => write!(f, "{c}"),
1560            Self::Placeholder(n) => write!(f, "${n}"),
1561            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
1562            Self::Unary { op, expr } => match op {
1563                UnOp::Not => write!(f, "(NOT {expr})"),
1564                UnOp::Neg => write!(f, "(-{expr})"),
1565            },
1566            Self::Cast { expr, target } => write!(f, "({expr}::{target})"),
1567            Self::IsNull { expr, negated } => {
1568                if *negated {
1569                    write!(f, "({expr} IS NOT NULL)")
1570                } else {
1571                    write!(f, "({expr} IS NULL)")
1572                }
1573            }
1574            Self::FunctionCall { name, args } => {
1575                write!(f, "{name}(")?;
1576                for (i, a) in args.iter().enumerate() {
1577                    if i > 0 {
1578                        f.write_str(", ")?;
1579                    }
1580                    write!(f, "{a}")?;
1581                }
1582                f.write_str(")")
1583            }
1584            Self::Like {
1585                expr,
1586                pattern,
1587                negated,
1588            } => {
1589                if *negated {
1590                    write!(f, "({expr} NOT LIKE {pattern})")
1591                } else {
1592                    write!(f, "({expr} LIKE {pattern})")
1593                }
1594            }
1595            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
1596            Self::WindowFunction {
1597                name,
1598                args,
1599                partition_by,
1600                order_by,
1601                frame,
1602                null_treatment: _,
1603            } => {
1604                write!(f, "{name}(")?;
1605                for (i, a) in args.iter().enumerate() {
1606                    if i > 0 {
1607                        f.write_str(", ")?;
1608                    }
1609                    write!(f, "{a}")?;
1610                }
1611                f.write_str(") OVER (")?;
1612                if !partition_by.is_empty() {
1613                    f.write_str("PARTITION BY ")?;
1614                    for (i, p) in partition_by.iter().enumerate() {
1615                        if i > 0 {
1616                            f.write_str(", ")?;
1617                        }
1618                        write!(f, "{p}")?;
1619                    }
1620                }
1621                if !order_by.is_empty() {
1622                    if !partition_by.is_empty() {
1623                        f.write_str(" ")?;
1624                    }
1625                    f.write_str("ORDER BY ")?;
1626                    for (i, (e, desc)) in order_by.iter().enumerate() {
1627                        if i > 0 {
1628                            f.write_str(", ")?;
1629                        }
1630                        write!(f, "{e}")?;
1631                        if *desc {
1632                            f.write_str(" DESC")?;
1633                        }
1634                    }
1635                }
1636                if let Some(fr) = frame {
1637                    if !partition_by.is_empty() || !order_by.is_empty() {
1638                        f.write_str(" ")?;
1639                    }
1640                    let k = match fr.kind {
1641                        FrameKind::Rows => "ROWS",
1642                        FrameKind::Range => "RANGE",
1643                    };
1644                    if let Some(end) = &fr.end {
1645                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
1646                    } else {
1647                        write!(f, "{k} {}", fr.start)?;
1648                    }
1649                }
1650                f.write_str(")")
1651            }
1652            Self::ScalarSubquery(s) => write!(f, "({s})"),
1653            Self::Exists { subquery, negated } => {
1654                if *negated {
1655                    write!(f, "NOT EXISTS ({subquery})")
1656                } else {
1657                    write!(f, "EXISTS ({subquery})")
1658                }
1659            }
1660            Self::InSubquery {
1661                expr,
1662                subquery,
1663                negated,
1664            } => {
1665                if *negated {
1666                    write!(f, "({expr} NOT IN ({subquery}))")
1667                } else {
1668                    write!(f, "({expr} IN ({subquery}))")
1669                }
1670            }
1671            Self::Array(items) => {
1672                f.write_str("ARRAY[")?;
1673                for (i, e) in items.iter().enumerate() {
1674                    if i > 0 {
1675                        f.write_str(", ")?;
1676                    }
1677                    write!(f, "{e}")?;
1678                }
1679                f.write_str("]")
1680            }
1681            Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
1682            Self::AnyAll {
1683                expr,
1684                op,
1685                array,
1686                is_any,
1687            } => {
1688                let kw = if *is_any { "ANY" } else { "ALL" };
1689                write!(f, "({expr} {op} {kw}({array}))")
1690            }
1691        }
1692    }
1693}
1694
1695impl fmt::Display for Literal {
1696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1697        match self {
1698            Self::Integer(n) => write!(f, "{n}"),
1699            Self::Float(x) => {
1700                let s = format!("{x}");
1701                // Default Display for an integral f64 (e.g. 1.0) emits "1",
1702                // which would round-trip back to Integer. Force a dot.
1703                if s.contains('.') || s.contains('e') || s.contains('E') {
1704                    f.write_str(&s)
1705                } else {
1706                    write!(f, "{s}.0")
1707                }
1708            }
1709            Self::String(s) => {
1710                f.write_str("'")?;
1711                for c in s.chars() {
1712                    if c == '\'' {
1713                        f.write_str("''")?;
1714                    } else {
1715                        write!(f, "{c}")?;
1716                    }
1717                }
1718                f.write_str("'")
1719            }
1720            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
1721            Self::Null => f.write_str("NULL"),
1722            Self::Vector(v) => {
1723                f.write_str("[")?;
1724                for (i, x) in v.iter().enumerate() {
1725                    if i > 0 {
1726                        f.write_str(", ")?;
1727                    }
1728                    let s = format!("{x}");
1729                    // Mirror Float Display: force a dot so re-parse stays
1730                    // numerically literal.
1731                    if s.contains('.') || s.contains('e') || s.contains('E') {
1732                        f.write_str(&s)?;
1733                    } else {
1734                        write!(f, "{s}.0")?;
1735                    }
1736                }
1737                f.write_str("]")
1738            }
1739            Self::Interval { text, .. } => {
1740                f.write_str("INTERVAL '")?;
1741                for c in text.chars() {
1742                    if c == '\'' {
1743                        f.write_str("''")?;
1744                    } else {
1745                        write!(f, "{c}")?;
1746                    }
1747                }
1748                f.write_str("'")
1749            }
1750        }
1751    }
1752}
1753
1754impl fmt::Display for BinOp {
1755    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1756        f.write_str(match self {
1757            Self::Or => "OR",
1758            Self::And => "AND",
1759            Self::Eq => "=",
1760            Self::NotEq => "<>",
1761            Self::IsDistinctFrom => "IS DISTINCT FROM",
1762            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
1763            Self::Lt => "<",
1764            Self::LtEq => "<=",
1765            Self::Gt => ">",
1766            Self::GtEq => ">=",
1767            Self::Add => "+",
1768            Self::Sub => "-",
1769            Self::Mul => "*",
1770            Self::Div => "/",
1771            Self::L2Distance => "<->",
1772            Self::InnerProduct => "<#>",
1773            Self::CosineDistance => "<=>",
1774            Self::Concat => "||",
1775            Self::JsonGet => "->",
1776            Self::JsonGetText => "->>",
1777            Self::JsonGetPath => "#>",
1778            Self::JsonGetPathText => "#>>",
1779            Self::JsonContains => "@>",
1780        })
1781    }
1782}
1783
1784/// Quote `s` as a PG double-quoted identifier when required (keyword,
1785/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
1786/// Otherwise return it as-is. Returns an owned `String` to keep the call site
1787/// uniform.
1788fn quote_ident(s: &str) -> String {
1789    let needs_quote = match s.chars().next() {
1790        None => true,
1791        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
1792        _ => {
1793            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
1794                || s.chars().any(|c| c.is_ascii_uppercase())
1795                || is_keyword(s)
1796        }
1797    };
1798    if !needs_quote {
1799        return s.to_string();
1800    }
1801    let mut out = String::with_capacity(s.len() + 2);
1802    out.push('"');
1803    for c in s.chars() {
1804        if c == '"' {
1805            out.push_str("\"\"");
1806        } else {
1807            out.push(c);
1808        }
1809    }
1810    out.push('"');
1811    out
1812}
1813
1814fn is_keyword(s: &str) -> bool {
1815    matches!(
1816        &*s.to_ascii_lowercase(),
1817        "select"
1818            | "from"
1819            | "where"
1820            | "as"
1821            | "null"
1822            | "true"
1823            | "false"
1824            | "and"
1825            | "or"
1826            | "not"
1827            | "create"
1828            | "table"
1829            | "insert"
1830            | "into"
1831            | "values"
1832            | "index"
1833            | "on"
1834            | "begin"
1835            | "commit"
1836            | "rollback"
1837            | "is"
1838            | "between"
1839            | "in"
1840            | "like"
1841            | "group"
1842            | "distinct"
1843            | "union"
1844            | "all"
1845            | "join"
1846            | "inner"
1847            | "left"
1848            | "cross"
1849            | "outer"
1850            | "default"
1851            | "savepoint"
1852            | "release"
1853            | "to"
1854            | "having"
1855            | "show"
1856            | "extract"
1857            | "offset"
1858            | "asc"
1859            | "desc"
1860            | "interval"
1861    )
1862}
1863
1864#[cfg(test)]
1865mod tests {
1866    use super::*;
1867    use alloc::vec;
1868
1869    #[test]
1870    fn integer_literal_renders_without_dot() {
1871        assert_eq!(Literal::Integer(42).to_string(), "42");
1872    }
1873
1874    #[test]
1875    fn integral_float_keeps_dot() {
1876        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
1877        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
1878        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
1879    }
1880
1881    #[test]
1882    fn string_literal_doubles_quote() {
1883        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
1884    }
1885
1886    #[test]
1887    fn bool_and_null_render_uppercase() {
1888        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
1889        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
1890        assert_eq!(Literal::Null.to_string(), "NULL");
1891    }
1892
1893    #[test]
1894    fn binary_op_always_parenthesised() {
1895        let e = Expr::Binary {
1896            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
1897            op: BinOp::Add,
1898            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
1899        };
1900        assert_eq!(e.to_string(), "(1 + 2)");
1901    }
1902
1903    #[test]
1904    fn select_star_from_table() {
1905        let s = SelectStatement {
1906            items: vec![SelectItem::Wildcard],
1907            from: Some(FromClause {
1908                primary: TableRef {
1909                    name: "users".into(),
1910                    alias: None,
1911                    as_of_segment: None,
1912                },
1913                joins: vec![],
1914            }),
1915            where_: None,
1916            group_by: None,
1917            group_by_all: false,
1918            having: None,
1919            unions: vec![],
1920            order_by: Vec::new(),
1921            limit: None,
1922            offset: None,
1923            distinct: false,
1924            ctes: vec![],
1925        };
1926        assert_eq!(s.to_string(), "SELECT * FROM users");
1927    }
1928
1929    #[test]
1930    fn quote_ident_for_uppercase_and_keyword() {
1931        assert_eq!(quote_ident("foo"), "foo");
1932        assert_eq!(quote_ident("Foo"), "\"Foo\"");
1933        assert_eq!(quote_ident("select"), "\"select\"");
1934        assert_eq!(quote_ident(""), "\"\"");
1935        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
1936    }
1937}