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