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