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}
497
498impl fmt::Display for ColumnTypeName {
499    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500        match self {
501            Self::SmallInt => f.write_str("SMALLINT"),
502            Self::Int => f.write_str("INT"),
503            Self::BigInt => f.write_str("BIGINT"),
504            Self::Float => f.write_str("FLOAT"),
505            Self::Text => f.write_str("TEXT"),
506            Self::Varchar(n) => write!(f, "VARCHAR({n})"),
507            Self::Char(n) => write!(f, "CHAR({n})"),
508            Self::Bool => f.write_str("BOOL"),
509            Self::Vector { dim, encoding } => match encoding {
510                VecEncoding::F32 => write!(f, "VECTOR({dim})"),
511                VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
512                VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
513            },
514            Self::Json => f.write_str("JSON"),
515            Self::Jsonb => f.write_str("JSONB"),
516            Self::Numeric(p, s) => {
517                if *s == 0 {
518                    write!(f, "NUMERIC({p})")
519                } else {
520                    write!(f, "NUMERIC({p}, {s})")
521                }
522            }
523            Self::Date => f.write_str("DATE"),
524            Self::Timestamp => f.write_str("TIMESTAMP"),
525            Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
526        }
527    }
528}
529
530/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
531/// engine evaluates `expr` per matched row in the table's row order
532/// and rewrites cells in place. Indexed columns are dropped + re-
533/// inserted into the affected B-tree on each row change.
534#[derive(Debug, Clone, PartialEq)]
535pub struct UpdateStatement {
536    pub table: String,
537    pub assignments: Vec<(String, Expr)>,
538    pub where_: Option<Expr>,
539    /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
540    /// clause (legacy CommandComplete path). Some = engine
541    /// evaluates the projection over each mutated row and
542    /// streams the result as a Rows QueryResult.
543    pub returning: Option<Vec<SelectItem>>,
544}
545
546/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
547/// from the active catalog and prunes them from every index.
548#[derive(Debug, Clone, PartialEq)]
549pub struct DeleteStatement {
550    pub table: String,
551    pub where_: Option<Expr>,
552    /// v7.9.4 — `RETURNING <projection>`.
553    pub returning: Option<Vec<SelectItem>>,
554}
555
556#[derive(Debug, Clone, PartialEq)]
557pub struct InsertStatement {
558    pub table: String,
559    /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
560    /// `None`, every tuple is positional and must match the table arity.
561    /// When `Some`, the engine maps each tuple slot to the named column and
562    /// fills the rest with NULL (must be nullable).
563    pub columns: Option<Vec<String>>,
564    /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
565    /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`.
566    pub rows: Vec<Vec<Expr>>,
567    /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
568    /// upsert clause. None = legacy INSERT (conflict raises a
569    /// DuplicateKey error). mailrs migration blocker #2.
570    pub on_conflict: Option<OnConflictClause>,
571    /// v7.9.4 — `RETURNING <projection>`.
572    pub returning: Option<Vec<SelectItem>>,
573}
574
575/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
576#[derive(Debug, Clone, PartialEq)]
577pub struct OnConflictClause {
578    /// Local columns that identify the conflict (must match a
579    /// UNIQUE / PRIMARY KEY index on the target table). Empty
580    /// list means the user wrote `ON CONFLICT DO …` without a
581    /// target — engine picks the table's first BTree index by
582    /// convention.
583    pub target_columns: Vec<String>,
584    /// The action on conflict.
585    pub action: OnConflictAction,
586}
587
588/// v7.9.7 — action on conflict.
589#[derive(Debug, Clone, PartialEq)]
590pub enum OnConflictAction {
591    /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
592    /// silently skips conflicting ones.
593    Nothing,
594    /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
595    /// may reference `EXCLUDED.col` to read the incoming row's
596    /// value (engine wires `EXCLUDED` as a virtual table).
597    Update {
598        assignments: Vec<(String, Expr)>,
599        where_: Option<Expr>,
600    },
601}
602
603#[derive(Debug, Clone, PartialEq)]
604pub struct SelectStatement {
605    /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
606    /// expressions, materialised once at query start before the
607    /// body SELECT runs. Empty for a regular SELECT. Non-recursive
608    /// only — no `WITH RECURSIVE` for v4.x.
609    pub ctes: Vec<Cte>,
610    pub distinct: bool,
611    pub items: Vec<SelectItem>,
612    pub from: Option<FromClause>,
613    pub where_: Option<Expr>,
614    pub group_by: Option<Vec<Expr>>,
615    /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
616    /// expands `group_by` to every non-aggregate SELECT-list item
617    /// before the executor runs. Mutually exclusive with an
618    /// explicit `group_by` list (the parser sets exactly one).
619    pub group_by_all: bool,
620    /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
621    /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
622    /// aggregate executor resolves them through the same synthetic
623    /// schema used for the SELECT items.
624    pub having: Option<Expr>,
625    /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
626    /// itself a `SelectStatement` with `order_by = None` and `limit =
627    /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
628    /// top of the chain).
629    pub unions: Vec<(UnionKind, SelectStatement)>,
630    /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
631    /// Keys are matched left-to-right: first key decides, ties break
632    /// to the second, etc.
633    pub order_by: Vec<OrderBy>,
634    /// `LIMIT <n>` — bound on row output. `n` is an integer
635    /// literal **or** (v7.9.24) a placeholder `$N` resolved
636    /// against the prepared-statement Bind values. mailrs
637    /// migration follow-up H2.
638    pub limit: Option<LimitExpr>,
639    /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
640    /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
641    pub offset: Option<LimitExpr>,
642}
643
644/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
645/// time or a placeholder `$N` resolved during extended-query
646/// Bind. mailrs migration follow-up H2.
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub enum LimitExpr {
649    /// `LIMIT 10` — value known at parse time.
650    Literal(u32),
651    /// `LIMIT $N` — the 1-based parameter index, resolved against
652    /// the bind values when the prepared statement executes.
653    Placeholder(u16),
654}
655
656impl fmt::Display for LimitExpr {
657    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658        match self {
659            Self::Literal(n) => write!(f, "{n}"),
660            Self::Placeholder(n) => write!(f, "${n}"),
661        }
662    }
663}
664
665impl LimitExpr {
666    /// Convenience for the simple-query path where no placeholders
667    /// can possibly exist. Returns the literal value or `None` if
668    /// this is a placeholder (caller must surface as Unsupported).
669    pub fn as_literal(self) -> Option<u32> {
670        match self {
671            Self::Literal(n) => Some(n),
672            Self::Placeholder(_) => None,
673        }
674    }
675}
676
677/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
678/// the engine's `substitute_placeholders` pass these are
679/// always Literal; in the simple-query path a Placeholder
680/// shape returns None (executor surfaces as
681/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
682impl SelectStatement {
683    #[must_use]
684    pub fn limit_literal(&self) -> Option<u32> {
685        self.limit.and_then(LimitExpr::as_literal)
686    }
687    #[must_use]
688    pub fn offset_literal(&self) -> Option<u32> {
689        self.offset.and_then(LimitExpr::as_literal)
690    }
691}
692
693#[derive(Debug, Clone, PartialEq)]
694pub struct Cte {
695    pub name: String,
696    pub body: SelectStatement,
697    /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
698    /// RECURSIVE keyword. Applies to every CTE in the clause per
699    /// PG semantics. A non-recursive body in a RECURSIVE WITH is
700    /// allowed; the engine just runs it once.
701    pub recursive: bool,
702    /// v4.22: optional `WITH name(a, b, c)` column-name list. When
703    /// non-empty, these override the body's output column names
704    /// position-by-position; the engine errors out if the count
705    /// doesn't match the body's projection width.
706    pub column_overrides: Vec<String>,
707}
708
709#[derive(Debug, Clone, PartialEq)]
710pub struct OrderBy {
711    pub expr: Expr,
712    /// `false` = ASC (default), `true` = DESC.
713    pub desc: bool,
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
717pub enum UnionKind {
718    /// `UNION` — dedupes the combined set.
719    Distinct,
720    /// `UNION ALL` — concatenates without dedup.
721    All,
722}
723
724#[derive(Debug, Clone, PartialEq)]
725pub enum SelectItem {
726    Wildcard,
727    Expr { expr: Expr, alias: Option<String> },
728}
729
730#[derive(Debug, Clone, PartialEq)]
731pub struct TableRef {
732    pub name: String,
733    pub alias: Option<String>,
734    /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
735    /// When `Some(id)`, the scan restricts to rows that live in
736    /// segment `<id>` only — useful for forensic inspection of a
737    /// specific freezer-emitted segment without exposing the hot
738    /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
739    /// is STABILITY carve-out for v6.10 — needs the freezer to
740    /// stamp each segment with a wall-clock at creation time.
741    pub as_of_segment: Option<u32>,
742}
743
744/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
745/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
746/// joins evaluate left-associatively in nested-loop order.
747#[derive(Debug, Clone, PartialEq)]
748pub struct FromClause {
749    pub primary: TableRef,
750    pub joins: Vec<FromJoin>,
751}
752
753#[derive(Debug, Clone, PartialEq)]
754pub struct FromJoin {
755    pub kind: JoinKind,
756    pub table: TableRef,
757    /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
758    pub on: Option<Expr>,
759}
760
761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
762pub enum JoinKind {
763    Inner,
764    Left,
765    Cross,
766}
767
768#[derive(Debug, Clone, PartialEq)]
769pub enum Expr {
770    Literal(Literal),
771    Column(ColumnName),
772    /// v6.1.1 — `$N` parameter placeholder for the extended query
773    /// protocol. The number is 1-based per PostgreSQL convention.
774    /// Evaluation looks up `params[N-1]` from the prepared-statement
775    /// bind buffer; out-of-range indices raise a runtime error
776    /// (same shape as a column-not-found miss).
777    Placeholder(u16),
778    Binary {
779        lhs: Box<Expr>,
780        op: BinOp,
781        rhs: Box<Expr>,
782    },
783    Unary {
784        op: UnOp,
785        expr: Box<Expr>,
786    },
787    /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
788    /// TEXT, BOOL targets; engine coerces at evaluation time.
789    Cast {
790        expr: Box<Expr>,
791        target: CastTarget,
792    },
793    /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
794    IsNull {
795        expr: Box<Expr>,
796        negated: bool,
797    },
798    /// Function call `name(args...)`. v1.4 supports a small built-in set
799    /// (length, upper, lower, abs, coalesce); unknown names error at eval
800    /// time so the parser stays open for v1.5 aggregates.
801    FunctionCall {
802        name: String,
803        args: Vec<Expr>,
804    },
805    /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
806    /// wildcards are `%` (any run) and `_` (one char), backslash escapes
807    /// the next char (so `\%` matches a literal `%`).
808    Like {
809        expr: Box<Expr>,
810        pattern: Box<Expr>,
811        negated: bool,
812    },
813    /// v4.12 window function call: `name(args) OVER (PARTITION BY
814    /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
815    /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
816    /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
817    /// unordered windows and "from start of partition through
818    /// current row" for ordered windows — no explicit ROWS /
819    /// RANGE clause in v4.12 MVP.
820    WindowFunction {
821        name: String,
822        args: Vec<Expr>,
823        partition_by: Vec<Expr>,
824        order_by: Vec<(Expr, bool /* desc */)>,
825        /// v4.20 explicit frame. `None` means "use the default":
826        /// whole-partition when unordered, running aggregate from
827        /// partition start through current row when ordered.
828        frame: Option<WindowFrame>,
829        /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
830        /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
831        /// `Respect` (PG / ANSI default — NULLs participate). Other
832        /// window functions ignore this flag.
833        null_treatment: NullTreatment,
834    },
835    /// v4.10 scalar subquery — `(SELECT ...)` used in expression
836    /// position. Must return exactly one row × one column at eval
837    /// time; the engine errors out otherwise. Uncorrelated only —
838    /// the inner SELECT cannot reference outer columns.
839    ScalarSubquery(Box<SelectStatement>),
840    /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
841    /// projection is ignored; only row-count matters.
842    Exists {
843        subquery: Box<SelectStatement>,
844        negated: bool,
845    },
846    /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
847    /// project exactly one column; membership is tested by Eq
848    /// against each row's value (NULL handling follows ANSI:
849    /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
850    InSubquery {
851        expr: Box<Expr>,
852        subquery: Box<SelectStatement>,
853        negated: bool,
854    },
855    /// `EXTRACT(<field> FROM <source>)` — pull an integer component
856    /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
857    /// because the `FROM` keyword is what separates the two halves,
858    /// not a comma.
859    Extract {
860        field: ExtractField,
861        source: Box<Expr>,
862    },
863}
864
865/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
866/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
867/// in the offset walk. `Ignore` causes the function to skip NULL
868/// values in the argument expression, returning the next non-NULL.
869#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
870pub enum NullTreatment {
871    #[default]
872    Respect,
873    Ignore,
874}
875
876/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
877/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
878/// where end implicitly = CURRENT ROW.
879#[derive(Debug, Clone, PartialEq, Eq)]
880pub struct WindowFrame {
881    pub kind: FrameKind,
882    pub start: FrameBound,
883    pub end: Option<FrameBound>,
884}
885
886#[derive(Debug, Clone, Copy, PartialEq, Eq)]
887pub enum FrameKind {
888    Rows,
889    Range,
890}
891
892#[derive(Debug, Clone, PartialEq, Eq)]
893pub enum FrameBound {
894    UnboundedPreceding,
895    OffsetPreceding(u64),
896    CurrentRow,
897    OffsetFollowing(u64),
898    UnboundedFollowing,
899}
900
901impl fmt::Display for FrameBound {
902    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903        match self {
904            Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
905            Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
906            Self::CurrentRow => f.write_str("CURRENT ROW"),
907            Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
908            Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
909        }
910    }
911}
912
913#[derive(Debug, Clone, Copy, PartialEq, Eq)]
914pub enum ExtractField {
915    Year,
916    Month,
917    Day,
918    Hour,
919    Minute,
920    Second,
921    Microsecond,
922}
923
924impl fmt::Display for ExtractField {
925    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926        f.write_str(match self {
927            Self::Year => "YEAR",
928            Self::Month => "MONTH",
929            Self::Day => "DAY",
930            Self::Hour => "HOUR",
931            Self::Minute => "MINUTE",
932            Self::Second => "SECOND",
933            Self::Microsecond => "MICROSECOND",
934        })
935    }
936}
937
938#[derive(Debug, Clone, Copy, PartialEq, Eq)]
939pub enum CastTarget {
940    Int,
941    BigInt,
942    Float,
943    Text,
944    Bool,
945    Vector,
946    Date,
947    Timestamp,
948    /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
949    /// H3a. Engine reuses the existing runtime-interval / timestamp
950    /// paths (parse the text input, return the matching Value).
951    Interval,
952    Timestamptz,
953    /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
954    /// types (v7.9.0); the cast just routes Text→Json with the
955    /// requested OID for the wire layer.
956    Json,
957    Jsonb,
958    /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
959    /// compatibility; engine surfaces as Unsupported with a
960    /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
961    RegType,
962    RegClass,
963}
964
965impl fmt::Display for CastTarget {
966    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
967        f.write_str(match self {
968            Self::Int => "int",
969            Self::BigInt => "bigint",
970            Self::Float => "float",
971            Self::Text => "text",
972            Self::Bool => "bool",
973            Self::Vector => "vector",
974            Self::Interval => "interval",
975            Self::Timestamptz => "timestamptz",
976            Self::Json => "json",
977            Self::Jsonb => "jsonb",
978            Self::RegType => "regtype",
979            Self::RegClass => "regclass",
980            Self::Date => "date",
981            Self::Timestamp => "timestamp",
982        })
983    }
984}
985
986#[derive(Debug, Clone, PartialEq)]
987pub enum Literal {
988    Integer(i64),
989    Float(f64),
990    String(String),
991    Bool(bool),
992    Null,
993    /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
994    Vector(Vec<f32>),
995    /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
996    /// Split into a months part (because a month is not a fixed number of
997    /// days) and a microseconds part (everything sub-month). `text` keeps
998    /// the original spelling so Display round-trips byte-for-byte.
999    Interval {
1000        months: i32,
1001        micros: i64,
1002        text: String,
1003    },
1004}
1005
1006#[derive(Debug, Clone, PartialEq, Eq)]
1007pub struct ColumnName {
1008    pub qualifier: Option<String>,
1009    pub name: String,
1010}
1011
1012#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1013pub enum BinOp {
1014    Or,
1015    And,
1016    Eq,
1017    NotEq,
1018    /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
1019    /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
1020    /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
1021    /// non-NULL behaviour matches `<>` / `=` exactly. Common in
1022    /// PG-style JOIN ON predicates and pg_dump output.
1023    IsDistinctFrom,
1024    IsNotDistinctFrom,
1025    Lt,
1026    LtEq,
1027    Gt,
1028    GtEq,
1029    Add,
1030    Sub,
1031    Mul,
1032    Div,
1033    /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
1034    /// operands of equal dimension; engine returns `Value::Float(d)`.
1035    L2Distance,
1036    /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
1037    /// more similar" remains true (matches pgvector's published convention).
1038    InnerProduct,
1039    /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
1040    CosineDistance,
1041    /// SQL string concatenation `||`. NULL propagates.
1042    Concat,
1043    /// v4.14 `json -> key` — element access by string key (object)
1044    /// or integer index (array). Returns a JSON value.
1045    JsonGet,
1046    /// v4.14 `json ->> key` — same access, returns the result as
1047    /// TEXT (unwraps a top-level JSON string; renders other scalars
1048    /// as their canonical text).
1049    JsonGetText,
1050    /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
1051    /// text array literal like `'{a,0,b}'`. Returns JSON.
1052    JsonGetPath,
1053    /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
1054    JsonGetPathText,
1055    /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
1056    /// when every key/value in `sub_json` is structurally present in
1057    /// the left side. Matches PG semantics (top-level + recursive).
1058    JsonContains,
1059}
1060
1061#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1062pub enum UnOp {
1063    Not,
1064    Neg,
1065}
1066
1067// --- Display impls (round-trip-safe) --------------------------------------
1068
1069impl fmt::Display for Statement {
1070    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1071        match self {
1072            Self::Select(s) => s.fmt(f),
1073            Self::CreateTable(s) => s.fmt(f),
1074            Self::CreateIndex(s) => s.fmt(f),
1075            Self::Insert(s) => s.fmt(f),
1076            Self::Update(s) => s.fmt(f),
1077            Self::Delete(s) => s.fmt(f),
1078            Self::Begin => f.write_str("BEGIN"),
1079            Self::Commit => f.write_str("COMMIT"),
1080            Self::Rollback => f.write_str("ROLLBACK"),
1081            Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
1082            Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
1083            Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
1084            Self::ShowTables => f.write_str("SHOW TABLES"),
1085            Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
1086            Self::CreateUser(s) => write!(
1087                f,
1088                "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
1089                quote_ident(&s.name),
1090                s.role
1091            ),
1092            Self::DropUser(n) => write!(f, "DROP USER {}", quote_ident(n)),
1093            Self::ShowUsers => f.write_str("SHOW USERS"),
1094            Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
1095            Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
1096            Self::CreateSubscription(s) => {
1097                write!(
1098                    f,
1099                    "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
1100                    quote_ident(&s.name),
1101                    s.conn_str.replace('\'', "''")
1102                )?;
1103                for (i, p) in s.publications.iter().enumerate() {
1104                    if i > 0 {
1105                        f.write_str(", ")?;
1106                    }
1107                    write!(f, "{}", quote_ident(p))?;
1108                }
1109                Ok(())
1110            }
1111            Self::DropSubscription(name) => {
1112                write!(f, "DROP SUBSCRIPTION {}", quote_ident(name))
1113            }
1114            Self::WaitForWalPosition { pos, timeout_ms } => {
1115                write!(f, "WAIT FOR WAL POSITION {pos}")?;
1116                if let Some(ms) = timeout_ms {
1117                    write!(f, " WITH TIMEOUT {ms}")?;
1118                }
1119                Ok(())
1120            }
1121            Self::Analyze(None) => f.write_str("ANALYZE"),
1122            Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
1123            Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
1124            Self::Explain(e) => {
1125                if e.suggest {
1126                    write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
1127                } else if e.analyze {
1128                    write!(f, "EXPLAIN ANALYZE {}", e.inner)
1129                } else {
1130                    write!(f, "EXPLAIN {}", e.inner)
1131                }
1132            }
1133            Self::AlterIndex(a) => {
1134                write!(f, "ALTER INDEX {} ", quote_ident(&a.name))?;
1135                match a.target {
1136                    AlterIndexTarget::Rebuild { encoding } => {
1137                        f.write_str("REBUILD")?;
1138                        if let Some(enc) = encoding {
1139                            write!(f, " WITH (encoding = {enc})")?;
1140                        }
1141                        Ok(())
1142                    }
1143                }
1144            }
1145            Self::AlterTable(a) => {
1146                write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
1147                match &a.target {
1148                    AlterTableTarget::SetHotTierBytes(n) => {
1149                        write!(f, "SET hot_tier_bytes = {n}")
1150                    }
1151                    AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
1152                    AlterTableTarget::DropForeignKey(name) => {
1153                        write!(f, "DROP CONSTRAINT {}", quote_ident(name))
1154                    }
1155                }
1156            }
1157            Self::CreatePublication(p) => {
1158                write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
1159                match &p.scope {
1160                    PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
1161                    PublicationScope::ForTables(ts) => {
1162                        f.write_str(" FOR TABLE ")?;
1163                        for (i, t) in ts.iter().enumerate() {
1164                            if i > 0 {
1165                                f.write_str(", ")?;
1166                            }
1167                            write!(f, "{}", quote_ident(t))?;
1168                        }
1169                        Ok(())
1170                    }
1171                    PublicationScope::AllTablesExcept(ts) => {
1172                        f.write_str(" FOR ALL TABLES EXCEPT ")?;
1173                        for (i, t) in ts.iter().enumerate() {
1174                            if i > 0 {
1175                                f.write_str(", ")?;
1176                            }
1177                            write!(f, "{}", quote_ident(t))?;
1178                        }
1179                        Ok(())
1180                    }
1181                }
1182            }
1183            Self::CreateExtension(name) => {
1184                write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
1185            }
1186            Self::DoBlock => f.write_str("DO $$ /* SPG no-op */ $$"),
1187            Self::DropPublication(name) => {
1188                write!(f, "DROP PUBLICATION {}", quote_ident(name))
1189            }
1190        }
1191    }
1192}
1193
1194impl fmt::Display for CreateIndexStatement {
1195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1196        if self.is_unique {
1197            f.write_str("CREATE UNIQUE INDEX ")?;
1198        } else {
1199            f.write_str("CREATE INDEX ")?;
1200        }
1201        if self.if_not_exists {
1202            f.write_str("IF NOT EXISTS ")?;
1203        }
1204        write!(
1205            f,
1206            "{} ON {} ",
1207            quote_ident(&self.name),
1208            quote_ident(&self.table)
1209        )?;
1210        match self.method {
1211            IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
1212            IndexMethod::Brin => f.write_str("USING brin ")?,
1213            IndexMethod::BTree => {}
1214        }
1215        if let Some(expr) = &self.expression {
1216            write!(f, "({})", expr)?;
1217        } else if self.extra_columns.is_empty() {
1218            write!(f, "({})", quote_ident(&self.column))?;
1219        } else {
1220            // v7.9.14 — multi-column key. Emit each column quoted
1221            // so the round-tripped form re-parses to identical AST.
1222            f.write_str("(")?;
1223            write!(f, "{}", quote_ident(&self.column))?;
1224            for c in &self.extra_columns {
1225                write!(f, ", {}", quote_ident(c))?;
1226            }
1227            f.write_str(")")?;
1228        }
1229        if !self.included_columns.is_empty() {
1230            f.write_str(" INCLUDE (")?;
1231            for (i, c) in self.included_columns.iter().enumerate() {
1232                if i > 0 {
1233                    f.write_str(", ")?;
1234                }
1235                write!(f, "{}", quote_ident(c))?;
1236            }
1237            f.write_str(")")?;
1238        }
1239        if let Some(pred) = &self.partial_predicate {
1240            write!(f, " WHERE {}", pred)?;
1241        }
1242        Ok(())
1243    }
1244}
1245
1246impl fmt::Display for CreateTableStatement {
1247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248        f.write_str("CREATE TABLE ")?;
1249        if self.if_not_exists {
1250            f.write_str("IF NOT EXISTS ")?;
1251        }
1252        write!(f, "{} (", quote_ident(&self.name))?;
1253        for (i, col) in self.columns.iter().enumerate() {
1254            if i > 0 {
1255                f.write_str(", ")?;
1256            }
1257            write!(f, "{col}")?;
1258        }
1259        // v7.6.0 — render FK constraints in table-level form, after
1260        // the column list. WAL replay round-trips through Display, so
1261        // every FK must serialise here for replay to reconstruct the
1262        // schema bit-for-bit.
1263        for fk in &self.foreign_keys {
1264            f.write_str(", ")?;
1265            write!(f, "{fk}")?;
1266        }
1267        f.write_str(")")
1268    }
1269}
1270
1271impl fmt::Display for ForeignKeyConstraint {
1272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1273        if let Some(name) = &self.name {
1274            write!(f, "CONSTRAINT {} ", quote_ident(name))?;
1275        }
1276        f.write_str("FOREIGN KEY (")?;
1277        for (i, c) in self.columns.iter().enumerate() {
1278            if i > 0 {
1279                f.write_str(", ")?;
1280            }
1281            f.write_str(&quote_ident(c))?;
1282        }
1283        write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
1284        if !self.parent_columns.is_empty() {
1285            f.write_str(" (")?;
1286            for (i, c) in self.parent_columns.iter().enumerate() {
1287                if i > 0 {
1288                    f.write_str(", ")?;
1289                }
1290                f.write_str(&quote_ident(c))?;
1291            }
1292            f.write_str(")")?;
1293        }
1294        // Only render non-default actions to keep Display output
1295        // close to user input. SPG's default is RESTRICT (matches
1296        // SQL spec).
1297        if self.on_delete != FkAction::Restrict {
1298            write!(f, " ON DELETE {}", self.on_delete)?;
1299        }
1300        if self.on_update != FkAction::Restrict {
1301            write!(f, " ON UPDATE {}", self.on_update)?;
1302        }
1303        Ok(())
1304    }
1305}
1306
1307impl fmt::Display for FkAction {
1308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1309        match self {
1310            Self::Restrict => f.write_str("RESTRICT"),
1311            Self::Cascade => f.write_str("CASCADE"),
1312            Self::SetNull => f.write_str("SET NULL"),
1313            Self::SetDefault => f.write_str("SET DEFAULT"),
1314            Self::NoAction => f.write_str("NO ACTION"),
1315        }
1316    }
1317}
1318
1319impl fmt::Display for ColumnDef {
1320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1321        write!(f, "{} {}", quote_ident(&self.name), self.ty)?;
1322        if let Some(d) = &self.default {
1323            write!(f, " DEFAULT {d}")?;
1324        }
1325        if self.auto_increment {
1326            f.write_str(" AUTO_INCREMENT")?;
1327        }
1328        if !self.nullable {
1329            f.write_str(" NOT NULL")?;
1330        }
1331        Ok(())
1332    }
1333}
1334
1335impl fmt::Display for InsertStatement {
1336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1337        write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
1338        if let Some(cols) = &self.columns {
1339            f.write_str(" (")?;
1340            for (i, c) in cols.iter().enumerate() {
1341                if i > 0 {
1342                    f.write_str(", ")?;
1343                }
1344                f.write_str(&quote_ident(c))?;
1345            }
1346            f.write_str(")")?;
1347        }
1348        f.write_str(" VALUES ")?;
1349        for (ri, row) in self.rows.iter().enumerate() {
1350            if ri > 0 {
1351                f.write_str(", ")?;
1352            }
1353            f.write_str("(")?;
1354            for (i, v) in row.iter().enumerate() {
1355                if i > 0 {
1356                    f.write_str(", ")?;
1357                }
1358                write!(f, "{v}")?;
1359            }
1360            f.write_str(")")?;
1361        }
1362        Ok(())
1363    }
1364}
1365
1366impl fmt::Display for UpdateStatement {
1367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1368        write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
1369        for (i, (col, expr)) in self.assignments.iter().enumerate() {
1370            if i > 0 {
1371                f.write_str(", ")?;
1372            }
1373            write!(f, "{} = {expr}", quote_ident(col))?;
1374        }
1375        if let Some(w) = &self.where_ {
1376            write!(f, " WHERE {w}")?;
1377        }
1378        Ok(())
1379    }
1380}
1381
1382impl fmt::Display for DeleteStatement {
1383    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1384        write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
1385        if let Some(w) = &self.where_ {
1386            write!(f, " WHERE {w}")?;
1387        }
1388        Ok(())
1389    }
1390}
1391
1392impl fmt::Display for SelectStatement {
1393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1394        write_bare_select(self, f)?;
1395        for (kind, peer) in &self.unions {
1396            f.write_str(match kind {
1397                UnionKind::Distinct => " UNION ",
1398                UnionKind::All => " UNION ALL ",
1399            })?;
1400            write_bare_select(peer, f)?;
1401        }
1402        if !self.order_by.is_empty() {
1403            f.write_str(" ORDER BY ")?;
1404            for (i, o) in self.order_by.iter().enumerate() {
1405                if i > 0 {
1406                    f.write_str(", ")?;
1407                }
1408                write!(f, "{}", o.expr)?;
1409                if o.desc {
1410                    f.write_str(" DESC")?;
1411                }
1412            }
1413        }
1414        if let Some(n) = &self.limit {
1415            write!(f, " LIMIT {n}")?;
1416        }
1417        if let Some(o) = &self.offset {
1418            write!(f, " OFFSET {o}")?;
1419        }
1420        Ok(())
1421    }
1422}
1423
1424fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1425    f.write_str("SELECT ")?;
1426    if s.distinct {
1427        f.write_str("DISTINCT ")?;
1428    }
1429    write_bare_select_body(s, f)
1430}
1431
1432fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1433    for (i, item) in s.items.iter().enumerate() {
1434        if i > 0 {
1435            f.write_str(", ")?;
1436        }
1437        write!(f, "{item}")?;
1438    }
1439    if let Some(t) = &s.from {
1440        write!(f, " FROM {t}")?;
1441    }
1442    if let Some(e) = &s.where_ {
1443        write!(f, " WHERE {e}")?;
1444    }
1445    if let Some(gs) = &s.group_by {
1446        f.write_str(" GROUP BY ")?;
1447        for (i, g) in gs.iter().enumerate() {
1448            if i > 0 {
1449                f.write_str(", ")?;
1450            }
1451            write!(f, "{g}")?;
1452        }
1453    }
1454    if let Some(h) = &s.having {
1455        write!(f, " HAVING {h}")?;
1456    }
1457    Ok(())
1458}
1459
1460impl fmt::Display for SelectItem {
1461    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1462        match self {
1463            Self::Wildcard => f.write_str("*"),
1464            Self::Expr { expr, alias } => {
1465                write!(f, "{expr}")?;
1466                if let Some(a) = alias {
1467                    write!(f, " AS {}", quote_ident(a))?;
1468                }
1469                Ok(())
1470            }
1471        }
1472    }
1473}
1474
1475impl fmt::Display for FromClause {
1476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477        write!(f, "{}", self.primary)?;
1478        for j in &self.joins {
1479            match j.kind {
1480                JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
1481                JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
1482                JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
1483            }
1484            if let Some(on) = &j.on {
1485                write!(f, " ON {on}")?;
1486            }
1487        }
1488        Ok(())
1489    }
1490}
1491
1492impl fmt::Display for TableRef {
1493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1494        write!(f, "{}", quote_ident(&self.name))?;
1495        if let Some(a) = &self.alias {
1496            write!(f, " AS {}", quote_ident(a))?;
1497        }
1498        Ok(())
1499    }
1500}
1501
1502impl fmt::Display for ColumnName {
1503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504        if let Some(q) = &self.qualifier {
1505            write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
1506        } else {
1507            write!(f, "{}", quote_ident(&self.name))
1508        }
1509    }
1510}
1511
1512impl fmt::Display for Expr {
1513    #[allow(clippy::too_many_lines)]
1514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1515        match self {
1516            Self::Literal(l) => write!(f, "{l}"),
1517            Self::Column(c) => write!(f, "{c}"),
1518            Self::Placeholder(n) => write!(f, "${n}"),
1519            Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
1520            Self::Unary { op, expr } => match op {
1521                UnOp::Not => write!(f, "(NOT {expr})"),
1522                UnOp::Neg => write!(f, "(-{expr})"),
1523            },
1524            Self::Cast { expr, target } => write!(f, "({expr}::{target})"),
1525            Self::IsNull { expr, negated } => {
1526                if *negated {
1527                    write!(f, "({expr} IS NOT NULL)")
1528                } else {
1529                    write!(f, "({expr} IS NULL)")
1530                }
1531            }
1532            Self::FunctionCall { name, args } => {
1533                write!(f, "{name}(")?;
1534                for (i, a) in args.iter().enumerate() {
1535                    if i > 0 {
1536                        f.write_str(", ")?;
1537                    }
1538                    write!(f, "{a}")?;
1539                }
1540                f.write_str(")")
1541            }
1542            Self::Like {
1543                expr,
1544                pattern,
1545                negated,
1546            } => {
1547                if *negated {
1548                    write!(f, "({expr} NOT LIKE {pattern})")
1549                } else {
1550                    write!(f, "({expr} LIKE {pattern})")
1551                }
1552            }
1553            Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
1554            Self::WindowFunction {
1555                name,
1556                args,
1557                partition_by,
1558                order_by,
1559                frame,
1560                null_treatment: _,
1561            } => {
1562                write!(f, "{name}(")?;
1563                for (i, a) in args.iter().enumerate() {
1564                    if i > 0 {
1565                        f.write_str(", ")?;
1566                    }
1567                    write!(f, "{a}")?;
1568                }
1569                f.write_str(") OVER (")?;
1570                if !partition_by.is_empty() {
1571                    f.write_str("PARTITION BY ")?;
1572                    for (i, p) in partition_by.iter().enumerate() {
1573                        if i > 0 {
1574                            f.write_str(", ")?;
1575                        }
1576                        write!(f, "{p}")?;
1577                    }
1578                }
1579                if !order_by.is_empty() {
1580                    if !partition_by.is_empty() {
1581                        f.write_str(" ")?;
1582                    }
1583                    f.write_str("ORDER BY ")?;
1584                    for (i, (e, desc)) in order_by.iter().enumerate() {
1585                        if i > 0 {
1586                            f.write_str(", ")?;
1587                        }
1588                        write!(f, "{e}")?;
1589                        if *desc {
1590                            f.write_str(" DESC")?;
1591                        }
1592                    }
1593                }
1594                if let Some(fr) = frame {
1595                    if !partition_by.is_empty() || !order_by.is_empty() {
1596                        f.write_str(" ")?;
1597                    }
1598                    let k = match fr.kind {
1599                        FrameKind::Rows => "ROWS",
1600                        FrameKind::Range => "RANGE",
1601                    };
1602                    if let Some(end) = &fr.end {
1603                        write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
1604                    } else {
1605                        write!(f, "{k} {}", fr.start)?;
1606                    }
1607                }
1608                f.write_str(")")
1609            }
1610            Self::ScalarSubquery(s) => write!(f, "({s})"),
1611            Self::Exists { subquery, negated } => {
1612                if *negated {
1613                    write!(f, "NOT EXISTS ({subquery})")
1614                } else {
1615                    write!(f, "EXISTS ({subquery})")
1616                }
1617            }
1618            Self::InSubquery {
1619                expr,
1620                subquery,
1621                negated,
1622            } => {
1623                if *negated {
1624                    write!(f, "({expr} NOT IN ({subquery}))")
1625                } else {
1626                    write!(f, "({expr} IN ({subquery}))")
1627                }
1628            }
1629        }
1630    }
1631}
1632
1633impl fmt::Display for Literal {
1634    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1635        match self {
1636            Self::Integer(n) => write!(f, "{n}"),
1637            Self::Float(x) => {
1638                let s = format!("{x}");
1639                // Default Display for an integral f64 (e.g. 1.0) emits "1",
1640                // which would round-trip back to Integer. Force a dot.
1641                if s.contains('.') || s.contains('e') || s.contains('E') {
1642                    f.write_str(&s)
1643                } else {
1644                    write!(f, "{s}.0")
1645                }
1646            }
1647            Self::String(s) => {
1648                f.write_str("'")?;
1649                for c in s.chars() {
1650                    if c == '\'' {
1651                        f.write_str("''")?;
1652                    } else {
1653                        write!(f, "{c}")?;
1654                    }
1655                }
1656                f.write_str("'")
1657            }
1658            Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
1659            Self::Null => f.write_str("NULL"),
1660            Self::Vector(v) => {
1661                f.write_str("[")?;
1662                for (i, x) in v.iter().enumerate() {
1663                    if i > 0 {
1664                        f.write_str(", ")?;
1665                    }
1666                    let s = format!("{x}");
1667                    // Mirror Float Display: force a dot so re-parse stays
1668                    // numerically literal.
1669                    if s.contains('.') || s.contains('e') || s.contains('E') {
1670                        f.write_str(&s)?;
1671                    } else {
1672                        write!(f, "{s}.0")?;
1673                    }
1674                }
1675                f.write_str("]")
1676            }
1677            Self::Interval { text, .. } => {
1678                f.write_str("INTERVAL '")?;
1679                for c in text.chars() {
1680                    if c == '\'' {
1681                        f.write_str("''")?;
1682                    } else {
1683                        write!(f, "{c}")?;
1684                    }
1685                }
1686                f.write_str("'")
1687            }
1688        }
1689    }
1690}
1691
1692impl fmt::Display for BinOp {
1693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1694        f.write_str(match self {
1695            Self::Or => "OR",
1696            Self::And => "AND",
1697            Self::Eq => "=",
1698            Self::NotEq => "<>",
1699            Self::IsDistinctFrom => "IS DISTINCT FROM",
1700            Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
1701            Self::Lt => "<",
1702            Self::LtEq => "<=",
1703            Self::Gt => ">",
1704            Self::GtEq => ">=",
1705            Self::Add => "+",
1706            Self::Sub => "-",
1707            Self::Mul => "*",
1708            Self::Div => "/",
1709            Self::L2Distance => "<->",
1710            Self::InnerProduct => "<#>",
1711            Self::CosineDistance => "<=>",
1712            Self::Concat => "||",
1713            Self::JsonGet => "->",
1714            Self::JsonGetText => "->>",
1715            Self::JsonGetPath => "#>",
1716            Self::JsonGetPathText => "#>>",
1717            Self::JsonContains => "@>",
1718        })
1719    }
1720}
1721
1722/// Quote `s` as a PG double-quoted identifier when required (keyword,
1723/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
1724/// Otherwise return it as-is. Returns an owned `String` to keep the call site
1725/// uniform.
1726fn quote_ident(s: &str) -> String {
1727    let needs_quote = match s.chars().next() {
1728        None => true,
1729        Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
1730        _ => {
1731            s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
1732                || s.chars().any(|c| c.is_ascii_uppercase())
1733                || is_keyword(s)
1734        }
1735    };
1736    if !needs_quote {
1737        return s.to_string();
1738    }
1739    let mut out = String::with_capacity(s.len() + 2);
1740    out.push('"');
1741    for c in s.chars() {
1742        if c == '"' {
1743            out.push_str("\"\"");
1744        } else {
1745            out.push(c);
1746        }
1747    }
1748    out.push('"');
1749    out
1750}
1751
1752fn is_keyword(s: &str) -> bool {
1753    matches!(
1754        &*s.to_ascii_lowercase(),
1755        "select"
1756            | "from"
1757            | "where"
1758            | "as"
1759            | "null"
1760            | "true"
1761            | "false"
1762            | "and"
1763            | "or"
1764            | "not"
1765            | "create"
1766            | "table"
1767            | "insert"
1768            | "into"
1769            | "values"
1770            | "index"
1771            | "on"
1772            | "begin"
1773            | "commit"
1774            | "rollback"
1775            | "is"
1776            | "between"
1777            | "in"
1778            | "like"
1779            | "group"
1780            | "distinct"
1781            | "union"
1782            | "all"
1783            | "join"
1784            | "inner"
1785            | "left"
1786            | "cross"
1787            | "outer"
1788            | "default"
1789            | "savepoint"
1790            | "release"
1791            | "to"
1792            | "having"
1793            | "show"
1794            | "extract"
1795            | "offset"
1796            | "asc"
1797            | "desc"
1798            | "interval"
1799    )
1800}
1801
1802#[cfg(test)]
1803mod tests {
1804    use super::*;
1805    use alloc::vec;
1806
1807    #[test]
1808    fn integer_literal_renders_without_dot() {
1809        assert_eq!(Literal::Integer(42).to_string(), "42");
1810    }
1811
1812    #[test]
1813    fn integral_float_keeps_dot() {
1814        assert_eq!(Literal::Float(1.0).to_string(), "1.0");
1815        assert_eq!(Literal::Float(1.5).to_string(), "1.5");
1816        assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
1817    }
1818
1819    #[test]
1820    fn string_literal_doubles_quote() {
1821        assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
1822    }
1823
1824    #[test]
1825    fn bool_and_null_render_uppercase() {
1826        assert_eq!(Literal::Bool(true).to_string(), "TRUE");
1827        assert_eq!(Literal::Bool(false).to_string(), "FALSE");
1828        assert_eq!(Literal::Null.to_string(), "NULL");
1829    }
1830
1831    #[test]
1832    fn binary_op_always_parenthesised() {
1833        let e = Expr::Binary {
1834            lhs: Box::new(Expr::Literal(Literal::Integer(1))),
1835            op: BinOp::Add,
1836            rhs: Box::new(Expr::Literal(Literal::Integer(2))),
1837        };
1838        assert_eq!(e.to_string(), "(1 + 2)");
1839    }
1840
1841    #[test]
1842    fn select_star_from_table() {
1843        let s = SelectStatement {
1844            items: vec![SelectItem::Wildcard],
1845            from: Some(FromClause {
1846                primary: TableRef {
1847                    name: "users".into(),
1848                    alias: None,
1849                    as_of_segment: None,
1850                },
1851                joins: vec![],
1852            }),
1853            where_: None,
1854            group_by: None,
1855            group_by_all: false,
1856            having: None,
1857            unions: vec![],
1858            order_by: Vec::new(),
1859            limit: None,
1860            offset: None,
1861            distinct: false,
1862            ctes: vec![],
1863        };
1864        assert_eq!(s.to_string(), "SELECT * FROM users");
1865    }
1866
1867    #[test]
1868    fn quote_ident_for_uppercase_and_keyword() {
1869        assert_eq!(quote_ident("foo"), "foo");
1870        assert_eq!(quote_ident("Foo"), "\"Foo\"");
1871        assert_eq!(quote_ident("select"), "\"select\"");
1872        assert_eq!(quote_ident(""), "\"\"");
1873        assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
1874    }
1875}