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/// `COPY … TO STDOUT` output format. `text` is PG's default
15/// (tab-separated, `\N` nulls, backslash escapes); `csv` follows
16/// RFC-4180-style quoting.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum CopyFormat {
19 #[default]
20 Text,
21 Csv,
22}
23
24/// Options for `COPY … TO STDOUT [WITH] (…)`. Defaults reproduce the
25/// bare `COPY … TO STDOUT` text-format behaviour, so an empty option
26/// list is a no-op. `delimiter` / `null_str` / `quote` fall back to the
27/// per-format defaults (text: `\t` / `\N`; csv: `,` / `` / `"`) when
28/// unset.
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct CopyOptions {
31 pub format: CopyFormat,
32 pub header: bool,
33 pub delimiter: Option<char>,
34 pub null_str: Option<String>,
35 pub quote: Option<char>,
36 /// v7.39 (round 247) — CSV `ESCAPE`: the character that precedes a
37 /// quote (or itself) inside a quoted cell. Defaults to the quote
38 /// character (PG's doubling behavior).
39 pub escape: Option<char>,
40 /// v7.39 (round 247) — CSV `FORCE_QUOTE (col, …)` / `FORCE_QUOTE *`:
41 /// columns whose non-NULL cells always quote. `Some(vec![])` is the
42 /// `*` spelling (every column).
43 pub force_quote: Option<Vec<String>>,
44 /// v7.39 (round 265) — CSV `FORCE_NOT_NULL (col, …)`: for these
45 /// columns an UNQUOTED empty field reads as the empty string rather
46 /// than NULL (probed). COPY FROM only.
47 pub force_not_null: Option<Vec<String>>,
48 /// v7.39 (round 265) — CSV `FORCE_NULL (col, …)`: for these columns
49 /// a QUOTED empty field (`""`) also reads as NULL (probed). COPY
50 /// FROM only.
51 pub force_null: Option<Vec<String>>,
52}
53
54/// v7.39 (round 218) — FETCH / MOVE cursor direction. PG grammar: single-row
55/// forms (NEXT / PRIOR / FIRST / LAST / ABSOLUTE n / RELATIVE n) return at
56/// most one row; multi-row forms (bare n / ALL / FORWARD [n|ALL] /
57/// BACKWARD [n|ALL]) stream a run. A negative bare/FORWARD count means
58/// BACKWARD (normalized at execution).
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum CursorDirection {
61 Next,
62 Prior,
63 First,
64 Last,
65 Absolute(i64),
66 Relative(i64),
67 /// Bare `FETCH n` / `FORWARD n` (negative = backward n).
68 Count(i64),
69 /// `ALL` / `FORWARD ALL`.
70 All,
71 Backward(i64),
72 BackwardAll,
73}
74
75impl fmt::Display for CursorDirection {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 match self {
78 Self::Next => f.write_str("NEXT"),
79 Self::Prior => f.write_str("PRIOR"),
80 Self::First => f.write_str("FIRST"),
81 Self::Last => f.write_str("LAST"),
82 Self::Absolute(n) => write!(f, "ABSOLUTE {n}"),
83 Self::Relative(n) => write!(f, "RELATIVE {n}"),
84 Self::Count(n) => write!(f, "FORWARD {n}"),
85 Self::All => f.write_str("ALL"),
86 Self::Backward(n) => write!(f, "BACKWARD {n}"),
87 Self::BackwardAll => f.write_str("BACKWARD ALL"),
88 }
89 }
90}
91
92/// v7.39 (round 320, V53) — what a `DISCARD` throws away.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum DiscardTarget {
95 All,
96 Plans,
97 Sequences,
98 Temp,
99}
100
101impl fmt::Display for DiscardTarget {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(match self {
104 Self::All => "ALL",
105 Self::Plans => "PLANS",
106 Self::Sequences => "SEQUENCES",
107 Self::Temp => "TEMP",
108 })
109 }
110}
111
112/// v7.39 (round 535) — which maintenance statement, and therefore what
113/// its target names. Measured on PG18: INDEX / TABLE / CLUSTER name a
114/// relation, SCHEMA names a schema, and SYSTEM / DATABASE name neither
115/// in a way SPG can refuse.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum MaintainKind {
118 ReindexRelation,
119 ReindexSchema,
120 /// `REINDEX SYSTEM` / `REINDEX DATABASE`, and a bare `CLUSTER`.
121 Whole,
122 ClusterRelation,
123}
124
125/// v7.39 (round 547) — see [`Statement::SetDbRoleSetting`]. Boxed in the
126/// enum so the variant costs one pointer.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct SetDbRoleSettingStatement {
129 pub database: Option<String>,
130 pub role: Option<String>,
131 pub param: Option<String>,
132 pub value: Option<String>,
133}
134
135/// v7.39 (round 696) — which operand a [`Statement::ValidateOnly`] names,
136/// and therefore which catalog answers whether it exists.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum ValidateOnlyKind {
139 /// `LOCK TABLE <t> [, …]` — the relation must exist.
140 LockTable,
141 /// Every role named must exist: `DROP OWNED BY <r> [, …]`,
142 /// `REASSIGN OWNED BY <r> [, …] TO <r>`, and (round 697)
143 /// `SET SESSION AUTHORIZATION <r>`.
144 RoleName,
145 /// `SECURITY LABEL …` — PG refuses unconditionally, because no label
146 /// provider is loaded. SPG has none either.
147 SecurityLabel,
148 /// v7.39 (round 697) — `CREATE EXTENSION <e>`: the extension must be
149 /// AVAILABLE (PG: `extension "x" is not available`).
150 ExtensionAvailable,
151 /// v7.39 (round 708) — `ALTER TYPE <t> <any no-op form>`: the TYPE must
152 /// exist (PG: `type "x" does not exist`); the action itself stays a
153 /// no-op (PG genuinely renames; that residual is recorded).
154 TypeName,
155 /// v7.39 (round 708) — `ALTER AGGREGATE name(args) …`: names[0] is the
156 /// aggregate, the rest its argument type names (`*` = the `(*)` form).
157 /// Existence only; the action no-ops (PG really renames built-ins —
158 /// measured — and SPG does not model that).
159 AggregateName,
160 /// v7.39 (round 708) — `DROP CONVERSION <c>`: SPG ships no conversions,
161 /// so every name answers PG's `conversion "x" does not exist`.
162 ConversionName,
163 /// v7.39 (round 708) — `DROP LANGUAGE <l>`: an unknown language does
164 /// not exist; a shipped one is required (PG's two wordings, measured).
165 LanguageName,
166 /// v7.39 (round 709) — a collation name: performable or PG's
167 /// `collation "x" for encoding "UTF8" does not exist`.
168 CollationName,
169 /// v7.39 (round 709) — a text search configuration name.
170 TsConfigName,
171 /// v7.39 (round 709) — an event trigger name. SPG has none, so the
172 /// not-found answer is total.
173 EventTriggerName,
174 /// v7.39 (round 709) — a tablespace name. SPG has none beyond PG's two
175 /// built-ins, whose drop PG refuses with `permission denied` (measured).
176 TablespaceName,
177 /// v7.39 (round 709) — a large-object oid (names[0], decimal). The
178 /// registry is real (round 287), so the check is a lookup.
179 LargeObjectOid,
180 /// v7.39 (round 706) — `CREATE SERVER` / `CREATE FOREIGN TABLE` /
181 /// `CREATE FOREIGN DATA WRAPPER`. SPG has no foreign-data
182 /// infrastructure at all, so PG's refusals (`foreign-data wrapper "x"
183 /// does not exist`, `server "x" does not exist`) cannot be copied —
184 /// PG can refuse because the missing piece is installable there.
185 /// Accepted with a WARNING, the extension resolution (round 697):
186 /// refusing turns a dump that restores today into one that needs
187 /// editing, and silent acceptance was the actual defect.
188 ForeignInfra,
189 /// v7.39 (round 697) — `DROP EXTENSION <e>`: it must be installed
190 /// (PG: `extension "x" does not exist`).
191 ExtensionInstalled,
192}
193
194#[derive(Debug, Clone, PartialEq)]
195#[allow(clippy::large_enum_variant)] // Statement::Select dominates; Boxing would touch every match site
196pub enum Statement {
197 /// v7.39 (round 695) — `ALTER SYSTEM SET <name> = …` / `RESET <name>`.
198 ///
199 /// It used to be swallowed with the rest of the ALTER no-ops, which meant
200 /// `ALTER SYSTEM SET nosuch_guc = 1` was ACCEPTED where PG18 answers
201 /// `unrecognized configuration parameter`. SPG still applies nothing —
202 /// there is no postgresql.auto.conf to write — but a name it does not
203 /// know is now refused rather than swallowed.
204 ///
205 /// `None` is `RESET ALL`, which names no parameter.
206 AlterSystem {
207 parameter: Option<String>,
208 },
209 /// `DROP DATABASE [IF EXISTS] <name>`. SPG is single-database, so
210 /// this never succeeds; the name and the flag are carried so the
211 /// engine can answer with PG's wording for the two cases PG itself
212 /// has — an unknown name, or the database you are connected to.
213 DropDatabase {
214 name: String,
215 if_exists: bool,
216 },
217 /// A statement SPG accepts as a no-op but PG refuses inside a
218 /// transaction block — today `CREATE DATABASE` / `DROP DATABASE`,
219 /// which are no-ops here because SPG is single-database.
220 ///
221 /// The no-op path they used to share (`Statement::Empty`) also
222 /// carries CREATE ROLE, CREATE CAST and a dozen others that PG is
223 /// happy to run inside a transaction, so the object has to be named
224 /// to refuse the right ones.
225 NoOpPreventedInTransaction {
226 what: String,
227 },
228 /// v7.39 (round 696) — statements SPG performs nothing for, but whose
229 /// OPERAND PG validates before performing nothing either.
230 ///
231 /// All four used to be consumed whole by `is_dump_noise_statement`,
232 /// which meant `LOCK TABLE nosuch` and `DROP OWNED BY nosuchrole` were
233 /// ACCEPTED where PG18 errors. Accepting a statement that names
234 /// something that does not exist is the F29 shape: the caller is told
235 /// their intent was understood when the object it referred to is not
236 /// there.
237 ///
238 /// They share one variant because they share one rule — resolve the
239 /// name, refuse if absent, otherwise no-op — and four variants would be
240 /// four places for that rule to drift.
241 /// v7.39 (round 707) — `DROP AGGREGATE [IF EXISTS] name(argtypes)[, …]`.
242 /// Consumed whole by the dump-noise list before, so `DROP AGGREGATE
243 /// nosuch(int)` reported success. PG validates every named aggregate's
244 /// EXISTENCE first (measured: a list with one unknown fails on the
245 /// unknown even when an earlier entry exists), renders the signature
246 /// with canonical type names (`int` → `integer`), and refuses to drop a
247 /// built-in (`cannot drop function sum(integer) because it is required
248 /// by the database system`). Every SPG aggregate is a built-in, so the
249 /// outcome is one of those two errors — or the IF EXISTS no-op.
250 ///
251 /// `args` holds the argument type names as written; `None` is the
252 /// `(*)` spelling.
253 DropAggregate {
254 if_exists: bool,
255 items: Vec<(String, Option<Vec<String>>)>,
256 },
257 /// v7.39 (round 750) — `ALTER ROLE|USER <name> … PASSWORD 'x' |
258 /// PASSWORD NULL`. The one attribute of the no-op family with a
259 /// SECURITY consequence: it was silently dropped (ledgered r710),
260 /// so a rotated credential never rotated. `None` = PASSWORD NULL
261 /// (the role keeps existing but can no longer password-auth).
262 AlterRolePassword {
263 name: String,
264 password: Option<String>,
265 },
266 ValidateOnly {
267 kind: ValidateOnlyKind,
268 /// The names the statement referred to. Empty means the form names
269 /// nothing (`SECURITY LABEL`, whose refusal is unconditional).
270 names: Vec<String>,
271 },
272
273 /// v7.39 (round 547) — `ALTER ROLE … SET/RESET` and
274 /// `ALTER DATABASE … SET/RESET`: the GUC defaults a session picks up
275 /// when it starts. Both used to land in the pg_dump no-op tail, so
276 /// the statement reported success and changed nothing.
277 ///
278 /// `database` / `role` are `None` for PG's oid 0 — `ALTER ROLE ALL`
279 /// sets both to None. `param` is `None` for RESET ALL. `value` is
280 /// `None` for RESET of one parameter.
281 SetDbRoleSetting(Box<SetDbRoleSettingStatement>),
282 /// v7.39 (round 288) — `SET CONSTRAINTS { ALL | <name>… }
283 /// { DEFERRED | IMMEDIATE }`. `deferred` carries the timing; the
284 /// name list is not yet honoured (ALL is what pg_dump emits and
285 /// what a circular-FK restore needs), so a named form applies to
286 /// all deferrable constraints too rather than silently doing
287 /// nothing.
288 /// v7.39 (round 308) — `SET CONSTRAINTS { ALL | name [, …] }
289 /// { DEFERRED | IMMEDIATE }`. An empty `names` is the ALL form;
290 /// otherwise the timing applies only to the constraints listed.
291 SetConstraints {
292 names: Vec<String>,
293 deferred: bool,
294 },
295
296 /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
297 /// [CASCADE | RESTRICT]`. Engine removes the matching tables
298 /// (each one) from the catalog; IF EXISTS makes the drop
299 /// idempotent. CASCADE / RESTRICT trailers parsed silently
300 /// (SPG always cascades index drops on table drop).
301 DropTable {
302 names: Vec<String>,
303 if_exists: bool,
304 },
305 /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
306 /// matching index across whichever table holds it.
307 DropIndex {
308 name: String,
309 if_exists: bool,
310 },
311 /// v7.14.0 — empty / comment-only statement. The lexer strips
312 /// `--` line comments and `/* … */` block comments (including
313 /// the MySQL conditional `/*!NNNNN … */` form) before the
314 /// parser ever sees them; a SQL chunk that contains nothing
315 /// else lands here. Engine returns CommandOk no-op so
316 /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
317 /// wrapped in conditional comments, etc.) load cleanly.
318 /// v7.39 (round 277) — SQL-level `PREPARE <name> [(type, …)] AS
319 /// <stmt>`. Session-scoped; the body keeps its `$N` placeholders
320 /// and is substituted at EXECUTE time.
321 Prepare {
322 name: String,
323 /// Declared parameter type names, in order. Empty when the
324 /// `(type, …)` list was omitted (PG infers them).
325 param_types: Vec<String>,
326 body: alloc::boxed::Box<Statement>,
327 /// The statement's own source text, which
328 /// `pg_prepared_statements.statement` reports verbatim.
329 source: String,
330 },
331 /// v7.39 (round 277) — `EXECUTE <name> [(arg, …)]`.
332 Execute {
333 name: String,
334 args: Vec<Expr>,
335 },
336 /// v7.39 (round 277) — `DEALLOCATE {<name> | ALL}`. `None` = ALL.
337 Deallocate(Option<String>),
338 /// v7.39 (round 280) — `CREATE STATISTICS [IF NOT EXISTS] <name>
339 /// [(kind, …)] ON <col>, … FROM <table>`. SPG records the object so
340 /// dumps restore and reflection is honest; the planner does not
341 /// consult it yet.
342 CreateStatistics {
343 name: String,
344 if_not_exists: bool,
345 /// Requested kinds as PG's single letters (`d` ndistinct,
346 /// `f` dependencies, `m` mcv). Empty = PG's default set.
347 kinds: Vec<String>,
348 columns: Vec<String>,
349 table: String,
350 },
351 /// v7.39 (round 280) — `DROP STATISTICS [IF EXISTS] <name>`.
352 DropStatistics {
353 name: String,
354 if_exists: bool,
355 },
356 /// v7.39 (round 278) — `CALL <proc>(…)`. Parses; the engine
357 /// reports that the procedure does not exist, because SPG has no
358 /// procedure catalog. Carried as a statement rather than raised at
359 /// parse time so the failure is a missing OBJECT (42883), not a
360 /// syntax error.
361 Call(String),
362 /// v7.39 (round 278) — `PREPARE TRANSACTION '<gid>'`. Same shape:
363 /// 2PC is unavailable, which PG itself reports when
364 /// `max_prepared_transactions` is 0.
365 PrepareTransaction(String),
366 Empty,
367 /// v7.39 (round 218) — `DECLARE <name> [BINARY] [INSENSITIVE]
368 /// [[NO] SCROLL] CURSOR [{WITH|WITHOUT} HOLD] FOR <select>`. The
369 /// canonical driver path for streaming large result sets (psycopg2
370 /// named cursors, JDBC setFetchSize).
371 DeclareCursor {
372 name: String,
373 /// `None` = neither keyword (PG default: backward allowed when the
374 /// plan supports it — always, for SPG's materialized cursors);
375 /// `Some(true)` = SCROLL; `Some(false)` = NO SCROLL (backward
376 /// fetch errors 55000).
377 scroll: Option<bool>,
378 /// `WITH HOLD` — survives the creating transaction's COMMIT.
379 hold: bool,
380 query: Box<Statement>,
381 },
382 /// v7.39 (round 218) — `FETCH [<direction>] [FROM|IN] <name>`.
383 FetchCursor {
384 name: String,
385 direction: CursorDirection,
386 },
387 /// v7.39 (round 218) — `MOVE [<direction>] [FROM|IN] <name>`: FETCH
388 /// without returning rows; the command tag carries the move count.
389 MoveCursor {
390 name: String,
391 direction: CursorDirection,
392 },
393 /// v7.39 (round 218) — `CLOSE <name>` / `CLOSE ALL` (`None` = ALL).
394 CloseCursor {
395 name: Option<String>,
396 },
397 /// v7.39 (round 222) — `LISTEN <channel>`: subscribe this session to
398 /// async notifications on the channel.
399 Listen(String),
400 /// v7.39 (round 222) — `NOTIFY <channel> [, '<payload>']`. Delivered at
401 /// COMMIT (PG semantics: transactional, deduplicated within the tx);
402 /// immediately under autocommit.
403 Notify {
404 channel: String,
405 payload: Option<String>,
406 },
407 /// v7.39 (round 222) — `UNLISTEN <channel>` / `UNLISTEN *` (`None` = *).
408 Unlisten(Option<String>),
409 /// `COPY table [(cols)] TO STDOUT` — the engine renders the
410 /// visible rows in COPY text format (tab-separated, `\N`
411 /// nulls, backslash escapes) as a single-text-column result
412 /// set; the wire layer streams CopyData from it.
413 CopyTo {
414 table: String,
415 columns: Option<Vec<String>>,
416 /// v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT`: an
417 /// arbitrary SELECT/VALUES/CTE (a whole [`Statement`], so set-ops and
418 /// VALUES ride through unchanged) whose result set is streamed in COPY
419 /// format. `Some` overrides `table`/`columns` (which are empty then);
420 /// `None` is the classic `COPY <table> …` shape.
421 query: Option<Box<Statement>>,
422 /// v7.37.x — `WITH (FORMAT csv, HEADER, DELIMITER, NULL, QUOTE)`
423 /// and the legacy `WITH CSV HEADER …` spelling. Default =
424 /// text format, no header (bare `COPY … TO STDOUT`).
425 options: CopyOptions,
426 },
427 /// v7.39 (round 249) — `COPY table [(cols)] FROM '<path>' [(opts)]`.
428 /// The engine is no_std and cannot read the file itself: the host
429 /// (embedded / server / tooling) reads the path and hands the bytes to
430 /// `Engine::copy_from_buffer`. Dispatching this statement straight to
431 /// the engine reports that contract.
432 CopyFromFile {
433 table: String,
434 columns: Option<Vec<String>>,
435 path: String,
436 options: CopyOptions,
437 },
438 /// v7.39 (round 249/252) — `COPY <table> [(cols)] TO '<file>'` (and
439 /// the `COPY (<query>) TO '<file>'` form). The engine is no_std and
440 /// cannot write the file itself: the host renders the payload via
441 /// `Engine::copy_to_buffer` and writes the path.
442 CopyToFile {
443 table: String,
444 columns: Option<Vec<String>>,
445 query: Option<Box<Statement>>,
446 path: String,
447 options: CopyOptions,
448 },
449 Select(SelectStatement),
450 CreateTable(CreateTableStatement),
451 /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
452 /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
453 /// no-op so PG dumps that include extension declarations
454 /// (notably `pgvector`) load against SPG without splitting
455 /// init scripts. mailrs migration follow-up F3.
456 CreateExtension(String),
457 /// v7.9.27 → v7.16.2 — PG `DO $$ … $$ [LANGUAGE plpgsql];`
458 /// block. The body is now CAPTURED as a [`PlPgSqlBlock`] and
459 /// the engine executes it at top level (mailrs round-10
460 /// A.2). Pre-v7.16.2 the parser discarded the body and the
461 /// engine returned CommandOk — a SEV-1 silent no-op that
462 /// turned mailrs's `DO BEGIN IF EXISTS … THEN ALTER … END
463 /// $$` idempotent migrations into invisible no-ops.
464 DoBlock(PlPgSqlBlock),
465 CreateIndex(CreateIndexStatement),
466 Insert(InsertStatement),
467 /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
468 Update(UpdateStatement),
469 /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
470 Delete(DeleteStatement),
471 /// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ `MERGE` statement.
472 /// `MERGE INTO target [alias] USING source [alias] ON cond
473 /// WHEN MATCHED [AND cond] THEN { UPDATE SET … | DELETE | DO NOTHING }
474 /// WHEN NOT MATCHED [AND cond] THEN { INSERT (cols) VALUES (vals) | DO NOTHING }
475 /// [WHEN …]`. SPG v7.17 supports table-based source (subquery
476 /// source is a follow-up); BY SOURCE / BY TARGET and RETURNING
477 /// are also follow-ups.
478 Merge(MergeStatement),
479 /// v7.39 (round 169) — `VACUUM [(opts)] [FULL|FREEZE|VERBOSE|ANALYZE]
480 /// [<table>]`. Was a parse-time no-op from the pre-MVCC era; with the
481 /// in-place MVCC gate ON, tombstoned versions are REAL bloat and a
482 /// customer's manual VACUUM must actually reclaim. `analyze` mirrors
483 /// the `VACUUM ANALYZE` spelling.
484 Vacuum {
485 table: Option<String>,
486 analyze: bool,
487 },
488 /// `BEGIN` / `START TRANSACTION` — with an optional explicit
489 /// `ISOLATION LEVEL …` mode (`None` = use the session default). PG
490 /// applies the level for the duration of this transaction only.
491 Begin(Option<IsolationLevel>),
492 Commit,
493 Rollback,
494 /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
495 /// stack so a later `ROLLBACK TO <name>` can undo just the work
496 /// since this point.
497 Savepoint(String),
498 /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
499 /// named savepoint and discard later savepoints. Does not end the
500 /// transaction.
501 RollbackToSavepoint(String),
502 /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
503 /// rolling back. Keeps the work done since then.
504 ReleaseSavepoint(String),
505 /// `SHOW TABLES` — return the list of tables in the catalog.
506 ShowTables,
507 /// v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES` /
508 /// `SHOW SCHEMAS`. SPG is single-database; the executor
509 /// returns the canonical MySQL set so the mysql / MariaDB
510 /// client populates its database selector.
511 ShowDatabases,
512 /// v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE TABLE <t>`
513 /// returns a 2-column row `(Table, "Create Table")` carrying
514 /// the synthesized DDL. mysqldump emits this for every
515 /// table at scrape time.
516 ShowCreateTable(String),
517 /// v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES FROM <t>`
518 /// (also `SHOW INDEX`, `SHOW KEYS`).
519 ShowIndexes(String),
520 /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS`.
521 ShowStatus,
522 /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW VARIABLES`.
523 ShowVariables,
524 /// v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
525 ShowProcesslist,
526 /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
527 /// pgbouncer sends `DISCARD ALL` between pooled client sessions to make
528 /// the connection look brand new to the next client; it used to be
529 /// swallowed as dump noise, so nothing was discarded.
530 Discard(DiscardTarget),
531 /// v7.39 (round 318, V51) — MySQL `KILL [CONNECTION | QUERY] <expr>`.
532 /// The id is an expression because MariaDB accepts one
533 /// (`KILL connection_id()` is the documented way to drop your own
534 /// connection). `query_only` is the `QUERY` form: stop the target's
535 /// running statement but leave it connected.
536 Kill {
537 query_only: bool,
538 id: Box<Expr>,
539 },
540 /// `SHOW COLUMNS FROM <table>` — return one row per column with
541 /// its declared name / type / nullability.
542 ShowColumns(String),
543 /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
544 /// Role is optional; defaults to `readonly` when omitted.
545 CreateUser(CreateUserStatement),
546 /// `DROP USER 'name'` (v4.1). v7.39 (read01 round 58) — `IF EXISTS` is
547 /// carried through: PG skips with a NOTICE rather than erroring.
548 DropUser {
549 name: String,
550 if_exists: bool,
551 },
552 /// v7.39 (RLS) — `SET ROLE { name | NONE | DEFAULT }` / `RESET ROLE`.
553 /// `Some(name)` switches the session's effective role (drives
554 /// `current_user` and RLS enforcement); `None` resets to the login
555 /// identity (the Admin superuser).
556 SetRole(Option<String>),
557 /// v7.39 (read01 round 57) — `GRANT <privs> ON <object> TO <roles>`.
558 Grant(GrantStatement),
559 /// v7.39 (read01 round 57) — `REVOKE [GRANT OPTION FOR] <privs> ON
560 /// <object> FROM <roles>`.
561 Revoke(GrantStatement),
562 /// v7.39 (RLS) — `CREATE POLICY name ON table …`.
563 CreatePolicy(CreatePolicyStatement),
564 /// v7.39 (RLS) — `ALTER POLICY name ON table …`.
565 AlterPolicy(AlterPolicyStatement),
566 /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
567 DropPolicy(DropPolicyStatement),
568 /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
569 ShowUsers,
570 /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
571 /// single-column text table describing the rewritten plan tree
572 /// for `inner`. `analyze` triggers an actual exec to attach
573 /// observed row counts and elapsed micros to each node.
574 Explain(ExplainStatement),
575 /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
576 /// Synchronous rebuild of an NSW index. With the optional
577 /// encoding clause, every stored cell at the indexed column is
578 /// also re-encoded through `coerce_value` before the new graph
579 /// builds.
580 AlterIndex(AlterIndexStatement),
581 /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
582 /// The only setting in v6.7.2 is `hot_tier_bytes`, which
583 /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
584 /// for the named table.
585 AlterTable(AlterTableStatement),
586 /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
587 /// The catalog row lives in `spg_publications`. Publisher-side
588 /// WAL filtering arrives in v6.1.5.
589 CreatePublication(CreatePublicationStatement),
590 /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
591 /// no-op when the publication does not exist.
592 DropPublication {
593 name: String,
594 /// v7.39 (round 754, F31-B4) — `IF EXISTS` quietly skips a
595 /// missing publication; the bare form refuses with PG's
596 /// sentence (PG18-measured — the old "silent no-op" note on
597 /// the executor was wrong).
598 if_exists: bool,
599 },
600 /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
601 /// publication ordered by name with `(name, scope_summary,
602 /// table_count)` columns. The scope summary is the human-
603 /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
604 /// TABLES EXCEPT …`; `table_count` is `NULL` for the
605 /// `AllTables` scope and the table-list length otherwise.
606 ShowPublications,
607 /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
608 /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
609 /// in `spg_subscriptions`; when the subscription is
610 /// `enabled = true` (default) the server spawns a
611 /// background worker that connects to `conn` and drains the
612 /// requested publication(s) into the local engine.
613 CreateSubscription(CreateSubscriptionStatement),
614 /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
615 /// PUBLICATION, silent no-op when absent. Stops the
616 /// associated worker thread before removing the row.
617 DropSubscription {
618 name: String,
619 /// v7.39 (round 754, F31-B4) — same contract as
620 /// [`Statement::DropPublication`].
621 if_exists: bool,
622 },
623 /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
624 /// subscription ordered by name with `(name, conn_str,
625 /// publications, enabled, last_received_pos)`.
626 ShowSubscriptions,
627 /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
628 /// Blocks until the local server's apply position reaches
629 /// `<pos>` or `<ms>` elapses. Server-layer command: the
630 /// engine refuses it (`EngineError::Unsupported`) since
631 /// `lag_state` lives in `spg-server`'s `ServerState`.
632 WaitForWalPosition {
633 pos: u64,
634 /// `None` → wait forever; `Some(ms)` → return after `ms`
635 /// milliseconds even if the target isn't reached.
636 timeout_ms: Option<u64>,
637 },
638 /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
639 /// table; `ANALYZE <name>` re-stats just one. Populates
640 /// `spg_statistic` with per-column null_frac + n_distinct +
641 /// 100-bucket equi-depth histogram.
642 Analyze(Option<String>),
643 /// v7.39 (round 535) — `REINDEX { INDEX | TABLE | SCHEMA | DATABASE
644 /// | SYSTEM } [CONCURRENTLY] <name>` and `CLUSTER [VERBOSE]
645 /// [<table> [USING <index>]]`.
646 ///
647 /// SPG has neither index bloat nor a clustering order to rebuild, so
648 /// the work is a no-op — but PG VALIDATES the target, and both were
649 /// swallowed at parse time, so `REINDEX TABLE typo` reported success.
650 /// The name is carried now so the engine can say what PG says.
651 Maintain {
652 kind: MaintainKind,
653 /// `REINDEX … CONCURRENTLY`. Carried for the same reason as
654 /// [`CreateIndexStatement::concurrently`]: PG bars the
655 /// CONCURRENTLY form inside a transaction block and allows the
656 /// plain one.
657 concurrently: bool,
658 /// `None` for the whole-database forms, which name nothing.
659 target: Option<String>,
660 },
661 /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] [ONLY] <name>
662 /// [, ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE |
663 /// RESTRICT]`. Clears every row from each named table. SPG's
664 /// SEQUENCE identity is per-table; RESTART IDENTITY reinitializes
665 /// the associated sequence to its starting value. CASCADE
666 /// currently walks direct FK-referring tables and truncates
667 /// them too (PG's semantics). The ONLY modifier (skip partitions)
668 /// and RESTRICT (default) are accepted with no effect since
669 /// SPG's declarative partitions are always truncated together.
670 Truncate {
671 tables: Vec<String>,
672 restart_identity: bool,
673 cascade: bool,
674 /// v7.39 (round 647) — `TRUNCATE ONLY t`. Absorbed as a no-op
675 /// since v7.14 on the reasoning that SPG's children are separate
676 /// relations a truncate does not descend into. Same reasoning
677 /// round 621 applied to `FROM ONLY`, and it stopped being true
678 /// for the same reason: measured, `TRUNCATE <inheritance parent>`
679 /// leaves the children's rows where PG empties them, and
680 /// `TRUNCATE ONLY <partitioned parent>` is silently accepted
681 /// where PG refuses it outright.
682 only: bool,
683 },
684 /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
685 /// BTree-cold indices and merges small cold-tier segments
686 /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
687 /// 4 MiB) into a single larger segment per (table, index).
688 /// `WHERE` predicate filtering on which tables to compact is
689 /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
690 /// v6.7.3 only supports the bare form.
691 CompactColdSegments,
692 /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
693 /// parameter on the engine; v7.12.1 honours
694 /// `default_text_search_config` (consumed by `to_tsvector` /
695 /// `plainto_tsquery` family when called without an explicit
696 /// config arg). All other names are accepted as a no-op so PG
697 /// dumps with `SET client_encoding`, `SET search_path` etc.
698 /// load cleanly.
699 SetParameter {
700 name: String,
701 value: SetValue,
702 /// v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to the
703 /// current transaction; the engine saves the prior value and
704 /// restores it at COMMIT / ROLLBACK. Plain `SET` (and `SET
705 /// SESSION`) leave this false and persist for the session.
706 local: bool,
707 },
708 /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
709 /// multi-assignment (mysqldump preamble uses
710 /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
711 /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
712 /// source order. Pairs whose LHS is a MySQL session/user
713 /// variable (`@VAR` / `@@VAR`) are recorded with the raw
714 /// name so the engine can ignore them; pairs whose LHS is
715 /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
716 /// go through the regular `set_session_param` path.
717 SetParameterList(Vec<(String, SetValue)>),
718 /// v7.39 (round 430) — MySQL's USER-defined variables:
719 /// `SET @x = 5, @s := CONCAT('a','b')`. Distinct from
720 /// [`Self::SetParameter`] (a `@@`-style engine/session setting) in
721 /// every way that matters: the value is an arbitrary EXPRESSION, the
722 /// name lives in its own per-session namespace, and reading an unset
723 /// one answers NULL rather than raising. `:=` and `=` are the same
724 /// assignment here.
725 ///
726 /// Before this the parser stripped every `@`, so `@x` and `@@x` were
727 /// the same node: `SET @x = 5` silently landed in the session-parameter
728 /// store where nothing could read it back, and `SELECT @x` failed with
729 /// "Unknown system variable".
730 /// v7.39 (round 554) — `SET @a = …, SETTING = …`.
731 ///
732 /// `settings` is the trailing half a mysqldump preamble writes:
733 /// `SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'`
734 /// saves a value and changes it in one statement. The parser used
735 /// to refuse the mixture outright, so no mysqldump could be
736 /// restored past its preamble.
737 SetUserVars(Vec<(String, Expr)>, Vec<(String, Expr)>),
738 /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
739 /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
740 /// silently accepted). PG-standard surface for picking an
741 /// isolation level. Engine tracks the value on
742 /// `Engine::current_isolation_level()`; actual MVCC / SSI
743 /// semantics implementation lands separately. PG itself maps
744 /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
745 /// effectively every level reads as READ COMMITTED in v7.37.8.
746 SetTransaction {
747 isolation: IsolationLevel,
748 },
749 /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
750 /// with the parameter's current value as TEXT. Today the only
751 /// recognised param is `transaction_isolation`; further
752 /// surfaces (`search_path`, `application_name`, …) land as the
753 /// session-parameter inventory grows.
754 ShowParameter(String),
755 /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
756 /// to its default. No-op for parameters SPG does not track.
757 ResetParameter(Option<String>),
758 /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
759 /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
760 /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
761 /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
762 /// languages parse but error at exec time with a clear
763 /// unsupported message.
764 CreateFunction(CreateFunctionStatement),
765 /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
766 /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
767 /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
768 /// triggers and column-list / WHEN clauses are out of scope
769 /// for v7.12.4.
770 CreateTrigger(CreateTriggerStatement),
771 /// v7.39 (round 139) — `CREATE RULE name AS ON event TO table [WHERE cond]
772 /// DO [ALSO|INSTEAD] { NOTHING | command }` query-rewrite rule.
773 CreateRule(CreateRuleStatement),
774 /// v7.39 (round 139) — `DROP RULE [IF EXISTS] name ON table`.
775 DropRule {
776 name: String,
777 table: String,
778 if_exists: bool,
779 },
780 /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
781 /// no-op when missing if `IF EXISTS` is set.
782 DropTrigger {
783 name: String,
784 table: String,
785 if_exists: bool,
786 },
787 /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
788 /// DROP TRIGGER but global (no table scope).
789 DropFunction {
790 name: String,
791 /// v7.39 (read01 round 62) — the argument TYPES, when the statement gave
792 /// them: `DROP FUNCTION f(int)` drops that overload only. `None` = no
793 /// argument list, which PG accepts only when the name is unambiguous.
794 args: Option<Vec<String>>,
795 if_exists: bool,
796 },
797 /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
798 /// [AS data_type]
799 /// [INCREMENT [BY] n]
800 /// [MINVALUE n | NO MINVALUE]
801 /// [MAXVALUE n | NO MAXVALUE]
802 /// [START [WITH] n]
803 /// [CACHE n]
804 /// [[NO] CYCLE]
805 /// [OWNED BY {table.col | NONE}]`.
806 /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
807 /// emits + nextval/currval/setval downstream all work.
808 CreateSequence(CreateSequenceStatement),
809 /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
810 /// the same option grammar as CREATE SEQUENCE, plus
811 /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
812 AlterSequence(AlterSequenceStatement),
813 /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
814 /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
815 /// silently (no FK on sequences).
816 DropSequence {
817 names: Vec<String>,
818 if_exists: bool,
819 },
820 /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
821 /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
822 /// silent-no-op VIEW story from the v7.17 customer-readiness
823 /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
824 /// so any downstream `SELECT FROM v` errored with table-not-
825 /// found. The view body is stored verbatim; SELECT FROM <v>
826 /// rewrites at exec-time by prepending the view body as a
827 /// synthetic CTE.
828 CreateView(CreateViewStatement),
829 /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
830 /// [CASCADE | RESTRICT]`. Removes the matching view from the
831 /// catalog; CASCADE/RESTRICT parsed silently.
832 DropView {
833 names: Vec<String>,
834 if_exists: bool,
835 },
836 /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
837 /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
838 /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
839 /// model: the materialised result lives as a regular table
840 /// with the matching name + a parallel
841 /// `materialized_views` registry mapping name → body source
842 /// (used by REFRESH).
843 CreateMaterializedView(CreateMaterializedViewStatement),
844 /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
845 /// [NO] DATA]`. Re-runs the stored body and replaces the
846 /// cached rows. `WITH NO DATA` truncates without re-running.
847 RefreshMaterializedView {
848 name: String,
849 with_data: bool,
850 },
851 /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
852 /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
853 /// backing table and the source registry entry.
854 DropMaterializedView {
855 names: Vec<String>,
856 if_exists: bool,
857 },
858 /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
859 /// …)`. Closes the silent-no-op CREATE TYPE story so PG
860 /// dumps that declare enum types load with real constraints
861 /// instead of becoming free-form TEXT. Future kinds
862 /// (composite / range / domain) extend the inner `kind`
863 /// enum.
864 CreateType(CreateTypeStatement),
865 /// v7.37 D.55 — `ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
866 /// [{BEFORE | AFTER} 'existing']`. Extends an enum's label list so
867 /// enum evolution stops being a silent no-op. `position` is
868 /// `Some((is_before, anchor))`.
869 /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
870 /// Used to be swallowed by the ALTER TYPE no-op tail, so the rename was
871 /// accepted and silently ignored.
872 /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
873 /// Used to be swallowed as dump noise, so a comment was accepted and lost
874 /// (and obj_description / col_description always returned NULL).
875 /// `kind` is lowercase ("table" / "column" / "index" / …); for a column
876 /// `name` is the dotted `table.column`. `comment: None` = `IS NULL` = remove.
877 CommentOn {
878 kind: String,
879 name: String,
880 comment: Option<String>,
881 },
882 AlterTypeRenameValue {
883 type_name: String,
884 old: String,
885 new: String,
886 },
887 AlterTypeAddValue {
888 type_name: String,
889 label: String,
890 if_not_exists: bool,
891 position: Option<(bool, String)>,
892 },
893 /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
894 /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
895 /// from the catalog.
896 DropType {
897 names: Vec<String>,
898 if_exists: bool,
899 },
900 /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
901 /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
902 /// A DOMAIN is a named CHECK-constrained alias over a built-
903 /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
904 /// every column declared with the domain. Closes the
905 /// silent-no-op CREATE DOMAIN story so PG dumps that ship
906 /// validated identifier types (email, positive_int, …) keep
907 /// their guarantees.
908 CreateDomain(CreateDomainStatement),
909 /// v7.39 (round 260) — `ALTER DOMAIN name <action>`. Every form was
910 /// previously swallowed by the catch-all DDL arm: the statement
911 /// reported success and did nothing, so a migration that dropped a
912 /// constraint kept rejecting the data it had just been told to
913 /// accept.
914 AlterDomain {
915 name: String,
916 action: AlterDomainAction,
917 },
918 /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
919 /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
920 /// domain from the catalog.
921 DropDomain {
922 names: Vec<String>,
923 if_exists: bool,
924 },
925 /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
926 /// name [AUTHORIZATION user]`. SPG is single-database;
927 /// schemas are tracked as a namespace registry so pg_dump
928 /// multi-schema declarations land cleanly and `SELECT *
929 /// FROM information_schema.schemata` returns real entries.
930 /// Schema-qualified `schema.table` references still strip
931 /// the prefix at lookup time per PG (schemas are not
932 /// isolation boundaries in v7.17 — see project-next-docket
933 /// for the v7.18+ isolation tracking).
934 CreateSchema {
935 name: String,
936 if_not_exists: bool,
937 },
938 /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
939 /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
940 /// from the registry; built-in `public` / `pg_catalog` /
941 /// `information_schema` cannot be dropped.
942 DropSchema {
943 names: Vec<String>,
944 if_exists: bool,
945 },
946}
947
948/// v7.39 (round 260) — the `ALTER DOMAIN` actions SPG implements.
949#[derive(Debug, Clone, PartialEq)]
950pub enum AlterDomainAction {
951 AddConstraint { name: Option<String>, check: Expr },
952 DropConstraint { name: String, if_exists: bool },
953 SetDefault(Expr),
954 DropDefault,
955 SetNotNull,
956 DropNotNull,
957 RenameTo(String),
958}
959
960/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
961#[derive(Debug, Clone, PartialEq)]
962pub struct CreateDomainStatement {
963 pub name: String,
964 /// Base type for the domain (one of the built-in
965 /// `ColumnTypeName` variants).
966 pub base_type: ColumnTypeName,
967 /// v7.39 (round 259) — `CREATE DOMAIN child AS parent …` where
968 /// `parent` is itself a DOMAIN. The parser already captured the
969 /// unknown type name; it just was not carried here, so the parent's
970 /// CHECK constraints were invisible and a value violating them was
971 /// silently accepted. `base_type` still holds the ultimate scalar
972 /// type, which is what the storage tier stores.
973 pub base_domain: Option<String>,
974 /// Optional `DEFAULT <expr>`. Resolved at engine-side
975 /// CREATE TABLE time when a column is bound to this domain.
976 pub default: Option<Expr>,
977 /// `NOT NULL` from the domain definition. Engine ORs this
978 /// with the column-level nullability so the strictest of the
979 /// two wins (i.e. the column is non-nullable if either side
980 /// says so).
981 pub not_null: bool,
982 /// Zero-or-more `CHECK (expr)` predicates. Each one is
983 /// enforced as part of the column's CHECK list at INSERT /
984 /// UPDATE time, with `VALUE` substituted for the column's
985 /// current cell value.
986 pub checks: Vec<Expr>,
987}
988
989/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
990#[derive(Debug, Clone, PartialEq, Eq)]
991pub struct CreateTypeStatement {
992 pub name: String,
993 pub kind: TypeKind,
994}
995
996/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
997/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
998/// and later (COMPOSITE, RANGE) can land without an AST shape
999/// migration.
1000///
1001/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
1002/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
1003/// stores the field list in the catalog so PG dumps that emit
1004/// `CREATE TYPE … AS (…)` don't error out; using a composite type
1005/// as a column type lands in Phase 2 (Value::Composite encoding +
1006/// ROW() literal + field-access syntax).
1007#[derive(Debug, Clone, PartialEq, Eq)]
1008pub enum TypeKind {
1009 /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
1010 /// labels are ordered).
1011 Enum { labels: Vec<String> },
1012 /// `AS (field_name field_type, …)`. Order matters; PG
1013 /// composite literals are positional.
1014 Composite {
1015 fields: Vec<(String, ColumnTypeName)>,
1016 /// v7.39 (round 264) — parallel to `fields`: the raw type NAME
1017 /// when a field's type is not a builtin (i.e. another composite).
1018 /// The parser already captures it; without carrying it here a
1019 /// nested composite field resolved to the Text placeholder and
1020 /// the inner record never became a record.
1021 field_user_types: Vec<Option<String>>,
1022 },
1023}
1024
1025/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
1026/// a string literal, an identifier (often a config name), an
1027/// integer/float, or the bare `DEFAULT` keyword.
1028#[derive(Debug, Clone, PartialEq)]
1029pub enum SetValue {
1030 String(String),
1031 Ident(String),
1032 Number(String),
1033 Default,
1034}
1035
1036/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
1037/// at parse time and tracks the selected value on the engine. The
1038/// actual semantic differentiation (REPEATABLE READ snapshot,
1039/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
1040/// today every level reads as effective READ COMMITTED (which is
1041/// also how PG treats READ UNCOMMITTED — it silently upgrades to
1042/// READ COMMITTED). Default = `ReadCommitted`.
1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1044pub enum IsolationLevel {
1045 ReadUncommitted,
1046 #[default]
1047 ReadCommitted,
1048 RepeatableRead,
1049 Serializable,
1050}
1051
1052impl IsolationLevel {
1053 /// Canonical PG-style display name, as `SHOW transaction_isolation`
1054 /// would return it. v7.39 (round 770, F31 tranche 6 #154) — PG
1055 /// KEEPS the "read uncommitted" label (measured: `BEGIN ISOLATION
1056 /// LEVEL READ UNCOMMITTED; SHOW transaction_isolation` answers
1057 /// `read uncommitted`) and only BEHAVES as read committed; the old
1058 /// fold renamed the label too.
1059 pub fn as_pg_str(self) -> &'static str {
1060 match self {
1061 Self::ReadUncommitted => "read uncommitted",
1062 Self::ReadCommitted => "read committed",
1063 Self::RepeatableRead => "repeatable read",
1064 Self::Serializable => "serializable",
1065 }
1066 }
1067}
1068
1069impl core::fmt::Display for IsolationLevel {
1070 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1071 f.write_str(self.as_pg_str())
1072 }
1073}
1074
1075/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
1076/// single fixed-shape DDL; the WITH-clause options PG supports
1077/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
1078/// scope for v6.1.4 — `enabled` defaults to true and there are
1079/// no other knobs to set in v6.1.x.
1080#[derive(Debug, Clone, PartialEq, Eq)]
1081pub struct CreateSubscriptionStatement {
1082 pub name: String,
1083 /// Connection string in PG keyword=value form (e.g.
1084 /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
1085 /// `host` and `port` fields; the rest is reserved for
1086 /// future v6.1.x options.
1087 pub conn_str: String,
1088 /// One or more publications on the remote side. Order is
1089 /// preserved verbatim from the DDL; the worker requests them
1090 /// in this order. v6.1.4 records the list; v6.1.5
1091 /// publisher-side filtering enforces it.
1092 pub publications: Vec<String>,
1093}
1094
1095/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
1096#[derive(Debug, Clone, PartialEq, Eq)]
1097pub struct CreateSequenceStatement {
1098 pub name: String,
1099 pub if_not_exists: bool,
1100 pub temporary: bool,
1101 /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
1102 pub data_type: Option<SequenceDataType>,
1103 pub options: SequenceOptions,
1104}
1105
1106/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
1107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1108pub enum SequenceDataType {
1109 SmallInt,
1110 Int,
1111 BigInt,
1112}
1113
1114/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
1115/// All fields are optional. `min_value`/`max_value` carry
1116/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
1117#[derive(Debug, Clone, Default, PartialEq, Eq)]
1118pub struct SequenceOptions {
1119 pub increment: Option<i64>,
1120 pub min_value: Option<SeqBound>,
1121 pub max_value: Option<SeqBound>,
1122 pub start: Option<i64>,
1123 /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
1124 /// RESTART, `Some(Some(n))` = RESTART WITH n.
1125 pub restart: Option<Option<i64>>,
1126 pub cache: Option<i64>,
1127 pub cycle: Option<bool>,
1128 pub owned_by: Option<SequenceOwnedBy>,
1129}
1130
1131/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
1132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1133pub enum SeqBound {
1134 Value(i64),
1135 NoBound,
1136}
1137
1138/// v7.17.0 — `OWNED BY {table.col | NONE}`.
1139#[derive(Debug, Clone, PartialEq, Eq)]
1140pub enum SequenceOwnedBy {
1141 None,
1142 Column { table: String, column: String },
1143}
1144
1145/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
1146#[derive(Debug, Clone, PartialEq)]
1147pub struct CreateMaterializedViewStatement {
1148 pub name: String,
1149 pub if_not_exists: bool,
1150 /// Optional `(col, col, …)` rename list. Applies to the
1151 /// backing table at CREATE / REFRESH time.
1152 pub columns: Vec<String>,
1153 /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
1154 /// the cached rows.
1155 pub body: SelectStatement,
1156 /// `WITH DATA` (default) = materialise the rows at CREATE
1157 /// time. `WITH NO DATA` = create an empty backing table;
1158 /// callers must REFRESH before SELECT returns rows.
1159 pub with_data: bool,
1160 /// v7.38 (read01 P6.49) — when true this node came from
1161 /// `CREATE TABLE … AS <select>` (CTAS) / `SELECT … INTO`, so the
1162 /// executor creates a plain table and does NOT register it in the
1163 /// materialized-view registry (no REFRESH semantics).
1164 pub as_plain_table: bool,
1165 /// v7.39 (round 436) — `CREATE TEMPORARY TABLE … AS <select>`. Only
1166 /// meaningful together with `as_plain_table`; the executor puts the
1167 /// resulting table in the creating session's namespace.
1168 pub temporary: bool,
1169}
1170
1171/// v7.39 (read01 round 132) — `WITH [LOCAL | CASCADED] CHECK OPTION` on an
1172/// auto-updatable view. `Cascaded` is PG's default when the bare
1173/// `WITH CHECK OPTION` is written.
1174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1175pub enum ViewCheckOption {
1176 Local,
1177 Cascaded,
1178}
1179
1180/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
1181#[derive(Debug, Clone, PartialEq)]
1182pub struct CreateViewStatement {
1183 pub name: String,
1184 pub or_replace: bool,
1185 pub if_not_exists: bool,
1186 pub temporary: bool,
1187 /// Optional `(col, col, …)` rename list. When non-empty,
1188 /// these override the body's projected column names per-
1189 /// position at SELECT-from-view time.
1190 pub columns: Vec<String>,
1191 /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
1192 /// time to materialise the view as a synthetic CTE.
1193 pub body: SelectStatement,
1194 /// v7.39 (round 132) — `WITH CHECK OPTION`. When set, a write through this
1195 /// view whose resulting row fails the view's WHERE is rejected (SQLSTATE
1196 /// 44000). `None` = no check option.
1197 pub check_option: Option<ViewCheckOption>,
1198}
1199
1200/// v7.17.0 — `ALTER SEQUENCE` AST node.
1201#[derive(Debug, Clone, PartialEq, Eq)]
1202pub struct AlterSequenceStatement {
1203 pub name: String,
1204 pub if_exists: bool,
1205 pub options: SequenceOptions,
1206 /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`. Set
1207 /// instead of `options`; the two forms are mutually exclusive in PG.
1208 pub rename_to: Option<String>,
1209}
1210
1211/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
1212/// the [`PublicationScope`] shape. v6.1.2 only accepted
1213/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
1214/// variants by flipping the parser gate (no AST migration).
1215#[derive(Debug, Clone, PartialEq, Eq)]
1216pub struct CreatePublicationStatement {
1217 pub name: String,
1218 pub scope: PublicationScope,
1219}
1220
1221/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
1222/// flips the parser gate for the `ForTables` / `AllTablesExcept`
1223/// variants — the on-disk shape, snapshot serialisation, and the
1224/// AST round-trip Display path were already in place in v6.1.2
1225/// so this is a parser-only widening.
1226#[derive(Debug, Clone, PartialEq, Eq)]
1227pub enum PublicationScope {
1228 AllTables,
1229 ForTables(Vec<String>),
1230 AllTablesExcept(Vec<String>),
1231 /// v7.39 (round 754, F31-B5) — `FOR TABLES IN SCHEMA <name>`
1232 /// (PG 15+). AST-only: the executor folds `public` to
1233 /// [`PublicationScope::AllTables`] (SPG's single-schema world)
1234 /// and refuses any other schema with PG's sentence, so the
1235 /// catalog / serializer / replication filter never see it.
1236 TablesInSchema(String),
1237}
1238
1239#[derive(Debug, Clone, PartialEq, Eq)]
1240pub struct AlterIndexStatement {
1241 pub name: String,
1242 pub target: AlterIndexTarget,
1243}
1244
1245#[derive(Debug, Clone, PartialEq, Eq)]
1246pub enum AlterIndexTarget {
1247 /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
1248 /// rebuilds the existing graph in place without touching the
1249 /// column encoding; `Some(enc)` re-encodes every cell first.
1250 Rebuild { encoding: Option<VecEncoding> },
1251 /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
1252 /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
1253 /// uses it to make the migration idempotent (re-running on a
1254 /// DB where the rename already happened is a no-op rather
1255 /// than an error).
1256 Rename { new: String, if_exists: bool },
1257 /// v7.39 (round 710) — `SET ( option = value, … )` / `RESET ( … )`.
1258 /// Was a SYNTAX ERROR; PG resolves the INDEX first (`relation "x"
1259 /// does not exist`), so the index is validated and the storage
1260 /// parameters no-op (SPG engine-manages them, as ALTER TABLE's
1261 /// SET/RESET arms already record).
1262 StorageParams,
1263}
1264
1265/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
1266/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
1267/// can add more SET subjects without changing the dispatch shape.
1268#[derive(Debug, Clone, PartialEq)]
1269pub struct AlterTableStatement {
1270 pub name: String,
1271 /// v7.13.2 — mailrs round-6 S1. One or more subactions
1272 /// separated by commas in the source SQL. PG-semantic apply
1273 /// is sequential; engine bails on first error (no
1274 /// transactional rollback of completed subactions in v7.13).
1275 /// Single-subaction shape stays a 1-element vec.
1276 pub targets: Vec<AlterTableTarget>,
1277}
1278
1279#[derive(Debug, Clone, PartialEq)]
1280#[allow(clippy::large_enum_variant)]
1281pub enum AlterTableTarget {
1282 /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
1283 ///
1284 /// Both were accepted-and-ignored since v7.37.18, on the reasoning
1285 /// that SPG has no PG-style inheritance. Round 645 gave it one, and
1286 /// the reasoning went stale: `NO INHERIT` reported success while the
1287 /// child stayed attached, which is the worst kind of answer — the
1288 /// statement says it worked and the catalog disagrees.
1289 Inherit { parent: String, detach: bool },
1290 /// Per-table hot-tier byte budget override. The freezer
1291 /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
1292 SetHotTierBytes(u64),
1293 /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
1294 /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
1295 /// Engine validates existing rows against the new constraint
1296 /// before installing it.
1297 AddForeignKey(ForeignKeyConstraint),
1298 /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
1299 /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
1300 /// no-op when no FK with that name exists; otherwise raises.
1301 DropForeignKey { name: String, if_exists: bool },
1302 /// v7.39 (round 431) — MySQL's `ALTER TABLE t DROP {INDEX|KEY} name`,
1303 /// the counterpart of `ADD INDEX`. Lowers to the same catalog action
1304 /// as the standalone `DROP INDEX` statement.
1305 DropIndex { name: String, if_exists: bool },
1306 /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
1307 /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
1308 /// (20 migrate-*.sql hits). Engine appends the column to the
1309 /// schema and back-fills every existing row with the DEFAULT
1310 /// (or NULL when no DEFAULT and the column is nullable).
1311 AddColumn {
1312 column: ColumnDef,
1313 if_not_exists: bool,
1314 },
1315 /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
1316 /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
1317 /// existing row's column value by evaluating the optional
1318 /// USING expression (default `col::<ty>`) and re-coercing
1319 /// against the new column type.
1320 AlterColumnType {
1321 column: String,
1322 new_type: ColumnTypeName,
1323 using: Option<Expr>,
1324 /// v7.39 (round 713) — `COLLATE <name>` between the type and
1325 /// USING. PG re-collates the column, and an ABSENT clause RESETS
1326 /// the collation to the type default (measured round 713) — so
1327 /// `None` is not "leave it alone". The type parser consumed the
1328 /// clause all along and this surface dropped it on the floor:
1329 /// the statement succeeded and the ordering did not change, the
1330 /// silent-divergence shape. Folded variant + the name as written.
1331 collation: Option<(Collation, String)>,
1332 },
1333 /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
1334 /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
1335 /// every row's value at that position is removed; any index
1336 /// on the column is dropped. `if_exists` makes the drop a
1337 /// no-op when the column is missing. `cascade` removes
1338 /// dependents (FKs referencing the column, partial indexes
1339 /// whose predicate names the column); without it, the engine
1340 /// rejects when dependents exist.
1341 DropColumn {
1342 column: String,
1343 if_exists: bool,
1344 cascade: bool,
1345 },
1346 /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
1347 /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
1348 /// CONSTRAINT name CHECK (expr)` — table-level constraints
1349 /// installed post-CREATE-TABLE. pg_dump emits PKs as a
1350 /// separate ALTER TABLE statement, so this surface lets the
1351 /// dump load straight through.
1352 AddTableConstraint(TableConstraint),
1353 /// v7.39 (round 652) — `OWNER TO <role>`. SPG is single-owner, so
1354 /// there is nothing to record; what PG does that SPG did not is
1355 /// REFUSE a role that does not exist. The name has to reach the
1356 /// engine for that, because only the engine knows the roles.
1357 OwnerTo { role: String },
1358 /// v7.39 (round 652) — `CLUSTER ON <index>` and `SET WITHOUT
1359 /// CLUSTER` (the latter as `None`). SPG has no clustered storage, so
1360 /// the hint is still a no-op; naming an index that does not exist is
1361 /// not.
1362 ClusterOn { index: Option<String> },
1363 /// v7.39 (round 652) — `VALIDATE CONSTRAINT <name>`: scan the rows
1364 /// already in the table against a constraint added `NOT VALID` and,
1365 /// if they all pass, mark it validated. It used to be swallowed as a
1366 /// no-op on the theory that SPG validated at ADD time; SPG did not.
1367 ValidateConstraint { name: String },
1368 /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
1369 /// Renames the column in the schema and propagates the rename
1370 /// to every stored source string that references it as a
1371 /// (potentially-qualified) column identifier: CHECK predicates,
1372 /// partial-index predicates, runtime DEFAULT expressions, and
1373 /// triggers' `UPDATE OF` column lists. Function bodies and
1374 /// trigger bodies are NOT auto-rewritten — they're loose
1375 /// source text and may contain references SPG can't statically
1376 /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
1377 /// the column even if dependents exist; users renaming a
1378 /// column referenced by a function body update the function
1379 /// body separately.
1380 RenameColumn { old: String, new: String },
1381 /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
1382 /// Reachable now that the schema stores user-supplied constraint names.
1383 RenameConstraint { old: String, new: String },
1384 /// v7.22 (round-13 T2) — mark a column auto-incrementing.
1385 /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
1386 /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
1387 /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
1388 /// (identity); both lower to this. SPG's auto-increment is
1389 /// max+1-scan based, so the dump's `setval(…)` calls stay
1390 /// no-ops without losing the sequence position.
1391 SetColumnAutoIncrement {
1392 column: String,
1393 /// The implicit sequence pg_dump names for an identity
1394 /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
1395 /// nextval target for a serial default. The engine creates
1396 /// it if absent so the dump's later `setval(s, …)` lands.
1397 seq_name: Option<String>,
1398 },
1399 /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
1400 /// table itself (mailrs round-10 A.5 carve-out — mailrs's
1401 /// migrate-042 uses it). The engine moves the table entry
1402 /// in the catalog under the new name; child catalog state
1403 /// (FKs pointing at this table, triggers watching this
1404 /// table) tracks the rename through the storage layer.
1405 RenameTable { new: String },
1406 /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
1407 /// { ALL | <name> }`. Toggles whether row-level triggers
1408 /// fire on subsequent INSERT/UPDATE/DELETE on the table.
1409 /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
1410 /// ENABLE epilogue around every table's data block so the
1411 /// rows already-computed in prod don't get re-rewritten
1412 /// (and so trigger-driven side effects like
1413 /// audit/queueing don't re-fire during a bulk reload).
1414 /// `which == TriggerSelector::All` toggles every trigger
1415 /// on the table; `Named(name)` toggles one trigger. The
1416 /// engine persists the disabled state on `TriggerDef.enabled`
1417 /// (catalog FILE_VERSION 25+) and the row-write paths skip
1418 /// the trigger when `!enabled`.
1419 SetTriggerEnabled {
1420 which: TriggerSelector,
1421 enabled: bool,
1422 },
1423 /// v7.39 (RLS) — `ALTER TABLE t { ENABLE | DISABLE | FORCE | NO FORCE }
1424 /// ROW LEVEL SECURITY`. `enabled` = Some for ENABLE/DISABLE (sets
1425 /// `relrowsecurity`); `force` = Some for FORCE/NO FORCE (sets
1426 /// `relforcerowsecurity`). Exactly one is `Some` per statement.
1427 SetRowSecurity {
1428 enabled: Option<bool>,
1429 force: Option<bool>,
1430 },
1431 /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child
1432 /// <bounds>`. Promotes an existing table `child` to a partition
1433 /// of `parent` using PG-style `FOR VALUES …` / `DEFAULT` bounds.
1434 /// Engine validates that `child`'s columns are layout-compatible
1435 /// with `parent` and that every row in `child` satisfies the
1436 /// bound before installing the role.
1437 AttachPartition {
1438 child: String,
1439 bounds: PartitionOfBoundsAst,
1440 },
1441 /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
1442 /// child [CONCURRENTLY] [FINALIZE]`. Demotes a partition back
1443 /// to a standalone table (clears `partition_role`) and removes
1444 /// it from the parent's child set. v7.37.16.5: `CONCURRENTLY`
1445 /// is parser-accepted; engine performs the same atomic detach
1446 /// (single-engine, no replication lag — the PG semantics that
1447 /// require the two-phase split don't apply).
1448 DetachPartition {
1449 child: String,
1450 concurrently: bool,
1451 finalize: bool,
1452 },
1453 /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col SET DEFAULT
1454 /// <expr>`. Engine re-parses + freezes the literal at this point,
1455 /// matching CREATE TABLE-side default semantics. Volatile shapes
1456 /// (`now()` / `nextval`) take the runtime-default path.
1457 AlterColumnSetDefault { column: String, default_expr: Expr },
1458 /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col DROP DEFAULT`.
1459 AlterColumnDropDefault { column: String },
1460 /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col SET NOT NULL`.
1461 /// Engine validates that no existing row has NULL in that column
1462 /// before flipping the flag (PG semantics — partial NOT NULL
1463 /// would surface inconsistently).
1464 AlterColumnSetNotNull { column: String },
1465 /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col DROP NOT NULL`.
1466 AlterColumnDropNotNull { column: String },
1467 /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN col RESTART
1468 /// [WITH n]` on an identity column (`None` = bare RESTART, from the
1469 /// column's start value = 1). Engine records a next-value floor over
1470 /// SPG's max+1 identity allocation.
1471 AlterColumnRestart { column: String, with: Option<i64> },
1472 /// v7.38 (read01 U10) — `ALTER TABLE … ALTER COLUMN col DROP
1473 /// EXPRESSION` turns a stored generated column into a plain column
1474 /// (its generation expression is removed; existing values are kept).
1475 AlterColumnDropExpression { column: String, if_exists: bool },
1476 /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
1477 /// de-generate an identity column into a plain column.
1478 AlterColumnDropIdentity { column: String, if_exists: bool },
1479 /// v7.38 (read01 U12) — `ALTER TABLE … ALTER COLUMN col SET
1480 /// EXPRESSION AS (expr)` (PG 17) changes a stored generated column's
1481 /// expression and recomputes every existing row.
1482 AlterColumnSetExpression { column: String, expr: Expr },
1483 /// v7.39 (round 710) — `OF <type>` / the type half of the typed-table
1484 /// binding. The BINDING stays a no-op (recorded); the TYPE must exist
1485 /// (PG: `type "x" does not exist`).
1486 OfType { type_name: String },
1487 /// v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`. The
1488 /// identity setting no-ops (SPG has no logical replication consumer);
1489 /// the INDEX must exist on this table (PG: `index "i" for table "t"
1490 /// does not exist`).
1491 ReplicaIdentityUsingIndex { index: String },
1492}
1493
1494/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
1495/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
1496/// modifiers; v7.16.1 ships the two shapes pg_dump actually
1497/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
1498/// shouldn't surface from a dump.
1499#[derive(Debug, Clone, PartialEq, Eq)]
1500pub enum TriggerSelector {
1501 /// Every trigger on the table.
1502 All,
1503 /// A specific trigger by name.
1504 Named(String),
1505}
1506
1507/// Each bool mirrors one independent PG `EXPLAIN (…)` option (ANALYZE,
1508/// SUGGEST, COSTS OFF, BUFFERS, TIMING OFF, …); they compose freely, so a
1509/// bitflags word or a nested options struct would only relocate the lint
1510/// while making the option each caller sets harder to read.
1511#[allow(clippy::struct_excessive_bools)]
1512#[derive(Debug, Clone, PartialEq)]
1513pub struct ExplainStatement {
1514 pub analyze: bool,
1515 /// v7.39 (round 225) — widened from SelectStatement so EXPLAIN
1516 /// INSERT/UPDATE/DELETE parses (PG explains DML); the engine renders
1517 /// `Insert on / Update on / Delete on` trees for them.
1518 pub inner: Box<Statement>,
1519 /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
1520 /// advisor pass: after the regular plan tree, the engine
1521 /// emits one suggestion line per column referenced in the
1522 /// query's WHERE / JOIN that has no covering index on the
1523 /// owning table.
1524 pub suggest: bool,
1525 /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
1526 /// `elapsed=…us` annotations from the Total line (and any
1527 /// future cost-bearing lines). PG-standard option used by
1528 /// regression suites and diff-friendly EXPLAIN output. When
1529 /// `true`, takes precedence over the per-session
1530 /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
1531 pub costs_off: bool,
1532 /// v7.37.22 (22.7) — `EXPLAIN (BUFFERS) <SELECT>`. PG-standard
1533 /// option that surfaces hot/cold/shared block counters. SPG's
1534 /// hot-tier scan path counts examined rows; the BUFFERS option
1535 /// makes that an explicit per-operator annotation.
1536 pub buffers: bool,
1537 /// v7.37.22 (22.7) — `EXPLAIN (TIMING [ON|OFF]) <SELECT>`. PG
1538 /// uses this to disable per-operator timing while still
1539 /// emitting actual-row counts (cheaper than ANALYZE). Default
1540 /// when EXPLAIN ANALYZE is set: TIMING ON. `false` strips the
1541 /// timing portion of the Total line. Decoupled from `costs_off`:
1542 /// PG's COSTS OFF strips estimated cost; TIMING OFF strips
1543 /// measured wall-clock.
1544 pub timing_off: bool,
1545 /// v7.37.22 (22.7) — `EXPLAIN (SETTINGS) <SELECT>`. PG appends
1546 /// modified GUC values to the plan output. SPG emits the
1547 /// session params that diverge from default after the main
1548 /// plan body.
1549 pub settings: bool,
1550 /// v7.37.22 (22.7) — `EXPLAIN (WAL) <SELECT>`. PG counts WAL
1551 /// bytes / records / FPI emitted by the query. SPG's
1552 /// write-side queries (INSERT/UPDATE/DELETE wrapped in EXPLAIN
1553 /// ANALYZE) report against the engine WAL counter delta.
1554 pub wal: bool,
1555 /// v7.39 (round 227) — `EXPLAIN (SUMMARY OFF)` suppresses the trailing
1556 /// `Planning Time:` / `Execution Time:` lines. PG defaults SUMMARY on
1557 /// for ANALYZE and off otherwise; SPG emits them for ANALYZE unless
1558 /// this is set.
1559 pub summary_off: bool,
1560 /// v7.37.23 (23.5) — `EXPLAIN (FORMAT text|json|xml|yaml)`.
1561 /// PG's standard format selector. Default is text. JSON / XML
1562 /// / YAML emit a single-row TEXT result whose body wraps the
1563 /// existing line-per-operator text in the chosen container —
1564 /// PG-compatible just enough for dashboards that parse those
1565 /// container shapes (pgAdmin's JSON path picker, etc.).
1566 pub format: ExplainFormat,
1567}
1568
1569#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1570pub enum ExplainFormat {
1571 #[default]
1572 Text,
1573 Json,
1574 Xml,
1575 Yaml,
1576}
1577
1578/// v7.39 (RLS) — the command a `CREATE POLICY` scopes to. `All` is the default.
1579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1580pub enum PolicyCmd {
1581 All,
1582 Select,
1583 Insert,
1584 Update,
1585 Delete,
1586}
1587
1588/// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
1589/// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`.
1590#[derive(Debug, Clone, PartialEq)]
1591pub struct CreatePolicyStatement {
1592 pub name: String,
1593 pub table: String,
1594 /// `true` = PERMISSIVE (default), `false` = RESTRICTIVE.
1595 pub permissive: bool,
1596 pub cmd: PolicyCmd,
1597 /// Empty = PUBLIC.
1598 pub roles: Vec<String>,
1599 pub using: Option<Expr>,
1600 pub with_check: Option<Expr>,
1601}
1602
1603/// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
1604/// [USING (expr)] [WITH CHECK (expr)] }`. Cannot change PERMISSIVE/RESTRICTIVE
1605/// or the command (matches PG).
1606#[derive(Debug, Clone, PartialEq)]
1607pub struct AlterPolicyStatement {
1608 pub name: String,
1609 pub table: String,
1610 pub rename_to: Option<String>,
1611 pub roles: Option<Vec<String>>,
1612 pub using: Option<Expr>,
1613 pub with_check: Option<Expr>,
1614}
1615
1616/// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
1617#[derive(Debug, Clone, PartialEq, Eq)]
1618pub struct DropPolicyStatement {
1619 pub name: String,
1620 pub table: String,
1621 pub if_exists: bool,
1622}
1623
1624#[derive(Debug, Clone, PartialEq, Eq)]
1625pub struct CreateUserStatement {
1626 pub name: String,
1627 /// Empty when the statement carried no PASSWORD — legal for a bare
1628 /// `CREATE ROLE`, which cannot log in anyway.
1629 pub password: String,
1630 /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
1631 /// the parser; the engine validates against `Role::parse` so a
1632 /// typo lands as a runtime error with a clear message rather than
1633 /// a parse failure.
1634 pub role: String,
1635 /// v7.39 (read01 round 58) — the PG role attributes. `None` = the
1636 /// statement did not say, so the default for its spelling applies:
1637 /// `CREATE USER` is `CREATE ROLE … LOGIN`, `CREATE ROLE` is NOLOGIN;
1638 /// both default to INHERIT and NOSUPERUSER.
1639 pub login: Option<bool>,
1640 pub inherit: Option<bool>,
1641 pub superuser: Option<bool>,
1642 /// `true` when spelled `CREATE USER` (LOGIN by default).
1643 pub is_user: bool,
1644}
1645
1646/// v7.39 (round 322, V46) — PG's function volatility class. Declarative:
1647/// it tells the planner how far a call may be moved or folded. SPG records
1648/// it faithfully (`pg_proc.provolatile`, `pg_get_functiondef`) and does not
1649/// yet exploit it for constant folding.
1650#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1651pub enum FunctionVolatility {
1652 Immutable,
1653 Stable,
1654 #[default]
1655 Volatile,
1656}
1657
1658impl FunctionVolatility {
1659 /// PG's one-character `pg_proc.provolatile` code.
1660 #[must_use]
1661 pub const fn as_pg_char(self) -> &'static str {
1662 match self {
1663 Self::Immutable => "i",
1664 Self::Stable => "s",
1665 Self::Volatile => "v",
1666 }
1667 }
1668
1669 #[must_use]
1670 pub const fn as_sql(self) -> &'static str {
1671 match self {
1672 Self::Immutable => "IMMUTABLE",
1673 Self::Stable => "STABLE",
1674 Self::Volatile => "VOLATILE",
1675 }
1676 }
1677}
1678
1679/// v7.39 (round 322, V46) — PG's parallel-safety class.
1680#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1681pub enum FunctionParallel {
1682 #[default]
1683 Unsafe,
1684 Restricted,
1685 Safe,
1686}
1687
1688impl FunctionParallel {
1689 /// PG's one-character `pg_proc.proparallel` code.
1690 #[must_use]
1691 pub const fn as_pg_char(self) -> &'static str {
1692 match self {
1693 Self::Unsafe => "u",
1694 Self::Restricted => "r",
1695 Self::Safe => "s",
1696 }
1697 }
1698
1699 #[must_use]
1700 pub const fn as_sql(self) -> &'static str {
1701 match self {
1702 Self::Unsafe => "PARALLEL UNSAFE",
1703 Self::Restricted => "PARALLEL RESTRICTED",
1704 Self::Safe => "PARALLEL SAFE",
1705 }
1706 }
1707}
1708
1709/// v7.39 (round 322, V46) — the attribute clauses `CREATE FUNCTION` accepts
1710/// on either side of its body. Defaults are PG's: VOLATILE, called on null
1711/// input, SECURITY INVOKER, not leakproof, PARALLEL UNSAFE, and the
1712/// language's default cost / rows.
1713#[derive(Debug, Clone, Copy, PartialEq, Default)]
1714pub struct FunctionAttrs {
1715 pub volatility: FunctionVolatility,
1716 /// `STRICT` / `RETURNS NULL ON NULL INPUT`: a call with any NULL
1717 /// argument returns NULL without running the body.
1718 pub strict: bool,
1719 pub security_definer: bool,
1720 pub leakproof: bool,
1721 pub parallel: FunctionParallel,
1722 /// `COST n` — `None` leaves PG's per-language default.
1723 pub cost: Option<f64>,
1724 /// `ROWS n` — set-returning functions only; `None` = default.
1725 pub rows: Option<f64>,
1726}
1727
1728impl FunctionAttrs {
1729 /// The attribute words `pg_get_functiondef` puts on their own line,
1730 /// in PG's order (measured on 18.4: volatility, PARALLEL, STRICT,
1731 /// SECURITY DEFINER, LEAKPROOF, COST, ROWS). Empty when everything is
1732 /// at its default — PG then emits no such line at all.
1733 #[must_use]
1734 pub fn render_words(&self) -> alloc::vec::Vec<alloc::string::String> {
1735 let mut out = alloc::vec::Vec::new();
1736 if self.volatility != FunctionVolatility::Volatile {
1737 out.push(alloc::string::String::from(self.volatility.as_sql()));
1738 }
1739 if self.parallel != FunctionParallel::Unsafe {
1740 out.push(alloc::string::String::from(self.parallel.as_sql()));
1741 }
1742 if self.strict {
1743 out.push(alloc::string::String::from("STRICT"));
1744 }
1745 if self.security_definer {
1746 out.push(alloc::string::String::from("SECURITY DEFINER"));
1747 }
1748 if self.leakproof {
1749 out.push(alloc::string::String::from("LEAKPROOF"));
1750 }
1751 if let Some(c) = self.cost {
1752 out.push(alloc::format!("COST {}", render_attr_number(c)));
1753 }
1754 if let Some(r) = self.rows {
1755 out.push(alloc::format!("ROWS {}", render_attr_number(r)));
1756 }
1757 out
1758 }
1759}
1760
1761/// PG prints a whole-numbered cost / rows without a decimal point.
1762fn render_attr_number(v: f64) -> alloc::string::String {
1763 // no_std: `f64::fract` lives in std, so compare against the truncation.
1764 let whole = v as i64;
1765 if v.abs() < 1e15 && (whole as f64) == v {
1766 alloc::format!("{whole}")
1767 } else {
1768 alloc::format!("{v}")
1769 }
1770}
1771
1772/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
1773/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
1774/// (the row-level trigger body the CREATE TRIGGER below references).
1775/// Non-trigger user-defined functions parse but error at execution
1776/// time with a clear unsupported message; that surface lands in
1777/// v7.12.5+.
1778#[derive(Debug, Clone, PartialEq)]
1779pub struct CreateFunctionStatement {
1780 pub name: String,
1781 /// `OR REPLACE` was present; an existing function with the
1782 /// same name is overwritten instead of erroring.
1783 pub or_replace: bool,
1784 /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
1785 /// list `()` (sufficient for trigger functions). Other shapes
1786 /// parse and store the args but the executor refuses to call
1787 /// them.
1788 pub args: Vec<FunctionArg>,
1789 /// `RETURNS <type>` — `trigger` is the supported shape for
1790 /// v7.12.4; arbitrary return types parse to
1791 /// [`FunctionReturn::Other`].
1792 pub returns: FunctionReturn,
1793 /// `LANGUAGE <lang>` clause. PG accepts the clause on either
1794 /// side of `AS $$...$$`; the parser canonicalises to one slot.
1795 /// `plpgsql` and `sql` are the two interesting values.
1796 pub language: String,
1797 /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
1798 /// a structured AST; non-trigger / non-plpgsql bodies stay as
1799 /// the raw source text so the v7.12.5+ executor can pick them
1800 /// up without a parser rev.
1801 pub body: FunctionBody,
1802 /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
1803 /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. PG accepts them
1804 /// on either side of the body; before this they were a parse error, so
1805 /// PG's own `pg_dump` output would not restore.
1806 pub attrs: FunctionAttrs,
1807}
1808
1809/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
1810#[derive(Debug, Clone, PartialEq)]
1811pub struct FunctionArg {
1812 /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
1813 /// (the default); `OUT` / `INOUT` parse but the executor
1814 /// refuses them.
1815 pub mode: FunctionArgMode,
1816 /// Optional arg name. Trigger functions traditionally don't
1817 /// name their args (they read NEW/OLD instead), so `None` is
1818 /// the common case.
1819 pub name: Option<String>,
1820 /// Declared type, normalised to the SPG `DataType` mapping
1821 /// where one exists. Unknown / extension types parse as a
1822 /// raw string under [`FunctionArgType::Raw`].
1823 pub ty: FunctionArgType,
1824}
1825
1826#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1827pub enum FunctionArgMode {
1828 In,
1829 Out,
1830 InOut,
1831}
1832
1833#[derive(Debug, Clone, PartialEq)]
1834pub enum FunctionArgType {
1835 Typed(ColumnTypeName),
1836 /// Unknown / extension types — kept as the parser-side raw
1837 /// identifier so error messages can name them precisely.
1838 Raw(String),
1839}
1840
1841#[derive(Debug, Clone, PartialEq)]
1842pub enum FunctionReturn {
1843 /// `RETURNS TRIGGER` — the row-level trigger function shape.
1844 /// v7.12.4 ships exactly this for execution.
1845 Trigger,
1846 /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
1847 /// the function is unused (since v7.12.4 doesn't ship scalar
1848 /// function invocation).
1849 Void,
1850 /// `RETURNS <type>` for any concrete data type. Reserved for
1851 /// v7.12.5+'s scalar UDF surface.
1852 Type(ColumnTypeName),
1853 /// `RETURNS <ident>` for types SPG doesn't know — extension
1854 /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
1855 Other(String),
1856}
1857
1858#[derive(Debug, Clone, PartialEq)]
1859pub enum FunctionBody {
1860 /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
1861 /// trigger-function executor walks this directly without
1862 /// re-parsing.
1863 PlPgSql(PlPgSqlBlock),
1864 /// Raw source text — parser couldn't (or didn't try to)
1865 /// structure-parse the body. Used for `LANGUAGE sql`
1866 /// functions and any PL/pgSQL body that contains v7.12.5+
1867 /// features the v7.12.4 parser doesn't yet recognise. The
1868 /// executor returns an unsupported error when invoked.
1869 Raw(String),
1870}
1871
1872/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
1873/// from assignment + return to a real-PL/pgSQL surface:
1874/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
1875/// control flow, `RAISE` diagnostics, and embedded SQL
1876/// statements that execute through the regular engine path.
1877/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
1878/// which mailrs's trigger doesn't need but other PG customers
1879/// may; deferred to a future minor release.
1880#[derive(Debug, Clone, PartialEq)]
1881pub struct PlPgSqlBlock {
1882 /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
1883 /// preceding `BEGIN`. Empty when the body opens directly with
1884 /// `BEGIN`. Declarations execute in order; each may reference
1885 /// earlier-declared locals in its init expression.
1886 pub declarations: Vec<PlPgSqlDeclare>,
1887 pub statements: Vec<PlPgSqlStmt>,
1888 /// v7.37.20 (20.10) — `EXCEPTION WHEN <cond> [OR <cond>...] THEN
1889 /// <body>` handlers appended to the block. Empty when no
1890 /// EXCEPTION clause is present. When a body statement raises
1891 /// (via RAISE EXCEPTION, ASSERT falsy, or a runtime error),
1892 /// handlers are tried in order; the first matching condition
1893 /// runs its body and the block terminates cleanly. `OTHERS`
1894 /// matches any exception. Unhandled exceptions propagate.
1895 pub exception_handlers: Vec<ExceptionHandler>,
1896}
1897
1898/// v7.37.20 (20.10) — one `WHEN <cond> [OR <cond>...] THEN <body>`
1899/// arm inside an EXCEPTION block.
1900#[derive(Debug, Clone, PartialEq)]
1901pub struct ExceptionHandler {
1902 /// Condition names (`OTHERS`, `unique_violation`, etc.). Multiple
1903 /// conditions joined by `OR` share one handler body.
1904 pub conditions: Vec<String>,
1905 /// Statements to run when a matching exception is caught.
1906 pub body: Vec<PlPgSqlStmt>,
1907}
1908
1909/// v7.12.6 — single `DECLARE` entry: variable name + declared
1910/// type + optional initialiser. Variables default to SQL NULL
1911/// when no init is given (matches PG).
1912#[derive(Debug, Clone, PartialEq)]
1913pub struct PlPgSqlDeclare {
1914 pub name: String,
1915 /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
1916 /// knows it; raw text otherwise).
1917 pub ty: FunctionArgType,
1918 pub default: Option<Expr>,
1919}
1920
1921#[derive(Debug, Clone, PartialEq)]
1922pub enum PlPgSqlStmt {
1923 /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
1924 /// for clarity in error reporting (PG also forbids it) — the
1925 /// executor errors with a clear "OLD is read-only" message.
1926 Assign { target: AssignTarget, value: Expr },
1927 /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
1928 /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
1929 /// the SELECT statement with the INTO clause stripped; the
1930 /// engine runs it via `Engine::execute`, takes the first
1931 /// row's first column, and assigns to the local variable
1932 /// in the DECLARE scope. Single-column / single-row
1933 /// queries only at v7.16.2; multi-target (`INTO a, b`) is
1934 /// a v7.16.x follow-up.
1935 SelectInto {
1936 var: String,
1937 body: Box<SelectStatement>,
1938 },
1939 /// `RETURN <target>;` — trigger functions canonically return
1940 /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
1941 /// expression for forward compatibility with scalar UDFs.
1942 Return(ReturnTarget),
1943 /// v7.39 (read01 round 66) — `RETURN NEXT <expr>;`: append one row to the
1944 /// set a SETOF function is building, and KEEP GOING. Not a return.
1945 ReturnNext(Expr),
1946 /// v7.39 (read01 round 66) — `RETURN QUERY <select>;`: append every row the
1947 /// query yields, and keep going. It used to desugar to a side-effect
1948 /// statement whose result was DISCARDED — in a SETOF function that is the
1949 /// whole answer thrown away.
1950 ReturnQuery(Box<SelectStatement>),
1951 /// v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the dynamic
1952 /// twin. Its rows go to the set too; it used to run and discard them.
1953 ReturnQueryExecute { sql: Expr },
1954 /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
1955 /// [ELSE body] END IF;`. Branches are tried in order; first
1956 /// truthy condition wins; the optional ELSE runs when no
1957 /// condition matched.
1958 If {
1959 branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
1960 else_branch: Vec<PlPgSqlStmt>,
1961 },
1962 /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
1963 /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
1964 /// (logging — observable side effect only) or `EXCEPTION`
1965 /// (aborts the trigger and propagates as an error). v7.12.6
1966 /// supports the basic format-string substitution PG uses
1967 /// (`%` placeholders consumed positionally).
1968 Raise {
1969 level: RaiseLevel,
1970 message: String,
1971 args: Vec<Expr>,
1972 },
1973 /// v7.12.6 — embedded SQL statement inside the trigger body
1974 /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
1975 /// NEW.col / OLD.col references inside the embedded
1976 /// statement's expression tree are substituted with the
1977 /// current trigger context before the engine re-executes the
1978 /// statement. Recursion depth into nested triggers is
1979 /// bounded by the engine's existing trigger-fire guard.
1980 EmbeddedSql(Box<Statement>),
1981 /// v7.37.20 (20.14) — `ASSERT <condition> [, <message>];`. If
1982 /// the condition evaluates falsy the trigger / DO block aborts
1983 /// with the message (defaulting to a generic shape when none
1984 /// is provided). Same propagation shape as `RAISE EXCEPTION`
1985 /// — the error reaches the caller's query path. PG's behaviour
1986 /// is identical except for a `plpgsql.check_asserts` GUC that
1987 /// can disable the check globally; SPG always evaluates.
1988 Assert {
1989 condition: Expr,
1990 message: Option<Expr>,
1991 },
1992 /// v7.37.20 (20.3) — `WHILE <condition> LOOP <body> END LOOP;`.
1993 /// Iterate the body while condition evaluates truthy. Iteration
1994 /// count is bounded by `WHILE_LOOP_BUDGET` to prevent runaway
1995 /// loops; the executor errors out when reached. EXIT / CONTINUE
1996 /// inside the body queue with 20.2.
1997 While {
1998 condition: Expr,
1999 body: Vec<PlPgSqlStmt>,
2000 },
2001 /// v7.37.20 (20.4) — `FOR <var> IN [REVERSE] <start>..<end> LOOP
2002 /// <body> END LOOP;`. Integer iteration; `var` is BigInt-valued;
2003 /// bounds inclusive on both sides. REVERSE walks backward.
2004 /// Iteration budget guards runaway.
2005 ForRange {
2006 var: String,
2007 start: Expr,
2008 end: Expr,
2009 reverse: bool,
2010 body: Vec<PlPgSqlStmt>,
2011 },
2012 /// v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`. Runs the body
2013 /// repeatedly; only `EXIT [WHEN <cond>]` breaks out. Iteration
2014 /// budget guards runaway.
2015 Loop { body: Vec<PlPgSqlStmt> },
2016 /// v7.37.20 (20.2) — `EXIT [WHEN <condition>];` inside a loop.
2017 /// Unconditional (no WHEN) or conditional (only breaks when
2018 /// condition is truthy). Bubbles up as BodyOutcome::Break which
2019 /// the enclosing loop catches. Outside a loop it's a no-op.
2020 Exit { when: Option<Expr> },
2021 /// v7.37.20 (20.2) — `CONTINUE [WHEN <condition>];` inside a
2022 /// loop. Same shape as EXIT but bubbles up as BodyOutcome::Continue
2023 /// which the enclosing loop catches, skipping the remainder of
2024 /// the body and jumping to the next iteration.
2025 Continue { when: Option<Expr> },
2026 /// v7.37.20 (20.13) — `EXECUTE <string_expr>;` runs a runtime-
2027 /// computed SQL statement. The expression is evaluated to a
2028 /// text value, the resulting string is parsed and dispatched
2029 /// through the engine like an EmbeddedSql. USING <param_list>
2030 /// for placeholder binding queues with v7.40 PL/pgSQL epic.
2031 ExecuteDynamic { sql: Expr },
2032 /// v7.37.20 (20.5) — `FOR <var> IN <select_body> LOOP <body>
2033 /// END LOOP;`. Runs the SELECT once, iterates the resulting
2034 /// rows, binds the first column of each row to `var` as a
2035 /// scalar Value, then runs the body per iteration. EXIT /
2036 /// CONTINUE / ASSERT / RAISE etc. propagate through the
2037 /// enclosing loop's BodyOutcome discipline the same way
2038 /// FOR range and WHILE do. Full record-binding (var as
2039 /// composite carrying all columns) queues with v7.40 record
2040 /// type infrastructure.
2041 ForQuery {
2042 var: String,
2043 query: Box<SelectStatement>,
2044 body: Vec<PlPgSqlStmt>,
2045 },
2046 /// v7.37.20 (20.6) — `FOR <var> IN EXECUTE <string_expr> LOOP
2047 /// <body> END LOOP;`. Same shape as ForQuery but the SELECT is
2048 /// computed at runtime from a text expression, parsed on the
2049 /// fly, then iterated. Enables dynamic queries where the
2050 /// projection / FROM / WHERE clauses depend on runtime values.
2051 ForExecute {
2052 var: String,
2053 sql_expr: Expr,
2054 body: Vec<PlPgSqlStmt>,
2055 },
2056}
2057
2058#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2059pub enum RaiseLevel {
2060 /// `RAISE NOTICE` — diagnostic message, observable in the
2061 /// server log. Does not affect the trigger's outcome.
2062 Notice,
2063 /// `RAISE WARNING` — like NOTICE, slightly louder severity.
2064 Warning,
2065 /// `RAISE INFO` — like NOTICE, slightly quieter.
2066 Info,
2067 /// `RAISE LOG` — like NOTICE, lower priority.
2068 Log,
2069 /// `RAISE DEBUG` — like NOTICE, lowest priority.
2070 Debug,
2071 /// `RAISE EXCEPTION` — aborts the trigger function with the
2072 /// given message, propagating up to the caller as a query-
2073 /// level error.
2074 Exception,
2075}
2076
2077#[derive(Debug, Clone, PartialEq)]
2078pub enum AssignTarget {
2079 NewColumn(String),
2080 OldColumn(String),
2081 /// Reserved for v7.12.5 DECLARE'd local variables.
2082 Local(String),
2083}
2084
2085#[derive(Debug, Clone, PartialEq)]
2086pub enum ReturnTarget {
2087 /// `RETURN NEW;` — for BEFORE triggers, this is the row that
2088 /// actually gets written (possibly with NEW.col mutations
2089 /// applied). For AFTER triggers, the return value is ignored.
2090 New,
2091 /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
2092 /// the delete proceed; for BEFORE UPDATE / INSERT it's
2093 /// equivalent to dropping the write.
2094 Old,
2095 /// `RETURN NULL;` — for BEFORE triggers, skips the write
2096 /// entirely. For AFTER, the return value is ignored.
2097 Null,
2098 /// `RETURN <expr>;` — non-row return shape; reserved for the
2099 /// scalar UDF surface in v7.12.5+. Executor errors when used
2100 /// inside a trigger function.
2101 Expr(Expr),
2102}
2103
2104/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
2105/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
2106/// but the executor refuses them. `WHEN (cond)` clauses are out
2107/// of scope; the trigger function can short-circuit on a leading
2108/// IF inside its body once v7.12.5 lands IF.
2109#[derive(Debug, Clone, PartialEq)]
2110pub struct CreateTriggerStatement {
2111 pub name: String,
2112 pub or_replace: bool,
2113 pub timing: TriggerTiming,
2114 /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
2115 /// three entries in order.
2116 pub events: Vec<TriggerEvent>,
2117 pub table: String,
2118 /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
2119 /// only `Row`; `Statement` parses but the executor refuses.
2120 pub for_each: TriggerForEach,
2121 /// Name of the function to invoke. The function must exist at
2122 /// CREATE TRIGGER time — PG18-measured (round 753): PG refuses a
2123 /// forward reference (`function no_such_fn() does not exist`), so
2124 /// requiring it IS the PG behaviour (the old note claimed the
2125 /// opposite).
2126 pub function: String,
2127 /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
2128 /// (mailrs round-5 G7). Non-empty only when the events list
2129 /// contains UPDATE and the user wrote the column-list filter.
2130 /// PG fires the trigger only when at least one of these
2131 /// columns appears in the SET clause; SPG conservatively
2132 /// fires on any UPDATE matching the listed columns or
2133 /// rewriting them at the row level. Empty vec = no filter
2134 /// (fire on every UPDATE).
2135 pub update_columns: Vec<String>,
2136 /// v7.39 (round 138) — `WHEN ( condition )` row-level filter: the row
2137 /// trigger fires only when the condition (over NEW / OLD) is true. `None`
2138 /// = no WHEN (fire unconditionally). Not allowed on INSTEAD OF triggers.
2139 pub when_condition: Option<Expr>,
2140}
2141
2142/// v7.39 (round 139) — `CREATE RULE` query-rewrite rule AST node.
2143#[derive(Debug, Clone, PartialEq)]
2144pub struct CreateRuleStatement {
2145 pub name: String,
2146 pub or_replace: bool,
2147 /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
2148 pub event: String,
2149 pub table: String,
2150 /// `true` = `DO INSTEAD` (replace the operation), `false` = `DO ALSO`
2151 /// (run alongside; PG's default when neither keyword is written).
2152 pub instead: bool,
2153 /// Optional `WHERE ( condition )` — the rule applies only when it holds.
2154 pub when_condition: Option<Expr>,
2155 /// The `DO` commands (over NEW / OLD). Empty = `NOTHING`.
2156 pub commands: Vec<Statement>,
2157}
2158
2159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2160pub enum TriggerTiming {
2161 /// Fires before the row is written; the trigger function's
2162 /// return value (NEW or NULL) decides the row content and
2163 /// whether the write proceeds at all.
2164 Before,
2165 /// Fires after the row is written; the return value is
2166 /// ignored.
2167 After,
2168 /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
2169 /// v7.12.4 (SPG has no updatable-view surface).
2170 InsteadOf,
2171}
2172
2173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2174pub enum TriggerEvent {
2175 Insert,
2176 Update,
2177 Delete,
2178 /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
2179 /// so the trigger never fires.
2180 Truncate,
2181}
2182
2183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2184pub enum TriggerForEach {
2185 Row,
2186 Statement,
2187}
2188
2189/// v7.39 (round 537) — a `CREATE INDEX` key column's ordering clause.
2190///
2191/// SPG's index does not scan in a direction, but `indexdef` reproduces
2192/// the DDL and dropping this made `(a DESC NULLS LAST)` read back as
2193/// `(a)`. `nulls_first` is `None` when the statement did not say, in
2194/// which case PG's default applies — LAST for ascending, FIRST for
2195/// descending, and neither is rendered.
2196#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2197pub struct IndexColumnOrder {
2198 pub descending: bool,
2199 pub nulls_first: Option<bool>,
2200}
2201
2202#[derive(Debug, Clone, PartialEq)]
2203pub struct CreateIndexStatement {
2204 pub name: String,
2205 /// `CREATE INDEX CONCURRENTLY`. SPG builds indexes synchronously
2206 /// either way, so this changes nothing about how the index is made
2207 /// — it is carried because PG refuses the CONCURRENTLY form inside
2208 /// a transaction block and accepts the plain one, and the engine
2209 /// cannot tell them apart without it.
2210 pub concurrently: bool,
2211 /// v7.39 (round 537) — the leading key column's ordering clause,
2212 /// which is the column SPG indexes.
2213 pub key_order: IndexColumnOrder,
2214 /// v7.39 (round 538) — an explicit `COLLATE` on that key, as
2215 /// written. SPG orders text by bytes, so honouring it changes
2216 /// nothing; PG prints it, because an explicitly named collation and
2217 /// the one a column inherits are different objects.
2218 pub key_collation: Option<String>,
2219 pub table: String,
2220 pub column: String,
2221 /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2222 /// (PG 15+). Default (`false`) is the SQL-standard NULLS DISTINCT, where
2223 /// any NULL in the key exempts the row from the uniqueness check.
2224 pub nulls_not_distinct: bool,
2225 /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
2226 /// graph for vector kNN); unspecified is the default B-tree index.
2227 pub method: IndexMethod,
2228 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2229 /// index name already exists, instead of raising `DuplicateIndex`.
2230 pub if_not_exists: bool,
2231 /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
2232 /// non-key columns the planner should treat as "covered" by
2233 /// this index when checking whether a query can run as an
2234 /// index-only scan. Empty when no `INCLUDE` clause was given.
2235 pub included_columns: Vec<String>,
2236 /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
2237 /// for which `<expr>` evaluates truthy enter the index;
2238 /// queries whose `WHERE` clause's canonical Display form
2239 /// matches this expression's Display form can be served by the
2240 /// partial index. Stored as a parsed `Expr` so the engine
2241 /// re-uses the existing evaluation path; storage persists the
2242 /// Display form on the catalog snapshot.
2243 pub partial_predicate: Option<Expr>,
2244 /// v6.8.2 — expression-based index. When `Some(expr)`, the
2245 /// index key is the result of `expr` evaluated on each row
2246 /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
2247 /// field still names the *primary* column the expression
2248 /// touches so existing planner shortcuts that resolve a
2249 /// column position stay valid. `None` = plain
2250 /// column-reference index (the legacy shape).
2251 pub expression: Option<Expr>,
2252 /// v7.9.14 — extra column names after the leading column in a
2253 /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
2254 /// planner today still only uses the leading column for index
2255 /// seeks; the extras are tracked verbatim so the same DDL
2256 /// round-trips through WAL replay + catalog snapshot, and so
2257 /// the engine can emit a clear warning at INDEX CREATE time
2258 /// that only the leading column is currently honoured.
2259 /// Composite BTree index keys land in v7.10.
2260 pub extra_columns: Vec<String>,
2261 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2262 /// enforces uniqueness on the indexed key (combined with the
2263 /// `partial_predicate` filter — only rows where the predicate
2264 /// evaluates truthy enter the uniqueness check). Standard SQL
2265 /// and PG's canonical way to express conditional uniqueness.
2266 /// mailrs K1.
2267 pub is_unique: bool,
2268 /// v7.15.0 — operator class on the leading column, when the
2269 /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2270 /// Lower-cased. Most opclasses are still informational; the
2271 /// engine routes on `gin_trgm_ops` specifically to build a
2272 /// trigram-shingle GIN over a TEXT column, and otherwise
2273 /// keeps the current "accepted and discarded" behaviour for
2274 /// pg_dump compatibility.
2275 pub opclass: Option<String>,
2276 /// r1038 — the access method as WRITTEN, lower-cased; `None` when
2277 /// there was no `USING` clause.
2278 ///
2279 /// `method` cannot answer this: `gist` / `spgist` / `hash` all become
2280 /// `IndexMethod::BTree` so PG schemas naming an AM SPG has no
2281 /// implementation for still load. That degradation is deliberate, but
2282 /// it loses the name — and the operator-class check needs it, both to
2283 /// look the class up under the AM the user actually named and to say
2284 /// which AM it was missing from, the way PG's message does.
2285 pub method_name: Option<String>,
2286}
2287
2288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2289pub enum IndexMethod {
2290 /// Default — B-tree over `IndexKey`. Used for equality / range
2291 /// lookups on scalar columns.
2292 BTree,
2293 /// `USING hnsw` — NSW graph for kNN over a vector column.
2294 Hnsw,
2295 /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2296 /// metadata that records (min_key, max_key) for each page in a
2297 /// cold-tier segment, on the indexed column. The optimizer
2298 /// can use these summaries to skip pages whose range does NOT
2299 /// overlap a query's WHERE predicate. BRIN indexes carry no
2300 /// in-memory data — the summaries live in the segment v2
2301 /// envelope's sidecar. Created via the standard
2302 /// `CREATE INDEX … USING brin (col)` syntax.
2303 Brin,
2304 /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2305 /// column. Posting lists map `lexeme word` → row locators; the
2306 /// planner uses them to narrow `WHERE col @@ tsquery` to the
2307 /// candidate rows whose vectors contain a matching term, then
2308 /// re-evaluates the full `@@` semantics on each candidate.
2309 /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2310 /// silently degraded to a full scan at query time.
2311 Gin,
2312}
2313
2314/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2315/// inside a CREATE TABLE column list.
2316///
2317/// The source table's shape can only be read from the catalog, so the
2318/// parser records the clause and the engine expands it. `at` is how many
2319/// explicit columns preceded it: PG keeps the written order, so
2320/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2321#[derive(Debug, Clone, PartialEq)]
2322pub struct LikeSpec {
2323 pub source: String,
2324 pub at: usize,
2325 pub options: LikeOptions,
2326}
2327
2328/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2329/// types and NOT NULL and nothing else — measured on PG18, where a
2330/// copied generated column becomes a plain one and a copied identity
2331/// column loses its identity.
2332#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2333pub struct LikeOptions {
2334 pub defaults: bool,
2335 pub constraints: bool,
2336 pub identity: bool,
2337 pub generated: bool,
2338 pub indexes: bool,
2339 pub comments: bool,
2340}
2341
2342#[derive(Debug, Clone, PartialEq)]
2343pub struct CreateTableStatement {
2344 /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2345 /// creating session's own namespace: it shadows a permanent table of the
2346 /// same name, other sessions never see it, and it is dropped when the
2347 /// session ends. A `bool` here lands in the struct's existing padding.
2348 pub temporary: bool,
2349 pub name: String,
2350 pub columns: Vec<ColumnDef>,
2351 /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2352 /// the order written. Empty for a table that has none.
2353 pub like_specs: Vec<LikeSpec>,
2354 /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2355 /// Empty for a table that inherits from nothing. Order matters:
2356 /// the child takes each parent's columns in this order before its
2357 /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2358 pub inherits: Vec<String>,
2359 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2360 /// table name already exists, instead of raising `DuplicateTable`.
2361 pub if_not_exists: bool,
2362 /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2363 /// constraints. Column-level `REFERENCES` (single-column inline
2364 /// form) is normalised into this vec at parse time so the engine
2365 /// sees one uniform list.
2366 pub foreign_keys: Vec<ForeignKeyConstraint>,
2367 /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2368 /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2369 /// Engine resolves each into a BTree index named after the
2370 /// constraint's leading column at CREATE TABLE time; INSERT
2371 /// path enforces composite uniqueness via row scan on the
2372 /// leading column index.
2373 pub table_constraints: Vec<TableConstraint>,
2374 /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2375 /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2376 /// the engine creates a parent table whose own rows stay
2377 /// empty and routes INSERT/SELECT through children. Mutually
2378 /// exclusive with `partition_of` (parser enforces).
2379 pub partition_by: Option<PartitionBySpec>,
2380 /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2381 /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2382 /// the table inherits its column list from `parent` (the
2383 /// parser rejects an explicit column list when this is set);
2384 /// engine routes child rows back to the parent at INSERT.
2385 pub partition_of: Option<PartitionOfSpec>,
2386}
2387
2388/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2389/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2390/// future LIST / HASH without breaking the public AST shape.
2391#[derive(Debug, Clone, PartialEq)]
2392pub struct PartitionBySpec {
2393 pub kind: PartitionKindAst,
2394 /// One or more ident references into the parent's column list.
2395 /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2396 /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2397 /// shape PG-compatible.
2398 pub key_columns: Vec<String>,
2399}
2400
2401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2402pub enum PartitionKindAst {
2403 Range,
2404 /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2405 /// `FOR VALUES IN (lit, lit, …)`.
2406 List,
2407 /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2408 /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2409 Hash,
2410}
2411
2412/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2413/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2414/// or the catch-all `DEFAULT` partition.
2415#[derive(Debug, Clone, PartialEq)]
2416pub struct PartitionOfSpec {
2417 pub parent_name: String,
2418 pub bounds: PartitionOfBoundsAst,
2419}
2420
2421#[derive(Debug, Clone, PartialEq)]
2422pub enum PartitionOfBoundsAst {
2423 /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2424 /// (lits include vector bodies), so we box both bounds to keep
2425 /// the variant size in line with `Default` for clippy and to
2426 /// minimise per-statement footprint when the partition shape
2427 /// isn't in use.
2428 Range {
2429 lower: Box<Expr>,
2430 upper: Box<Expr>,
2431 },
2432 /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2433 /// expr resolves to a typed literal at child-create time.
2434 List {
2435 values: Vec<Expr>,
2436 },
2437 /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2438 /// PG enforces `0 ≤ r < m`; m must be positive.
2439 Hash {
2440 modulus: u32,
2441 remainder: u32,
2442 },
2443 Default,
2444}
2445
2446/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2447/// column list. Either a composite PRIMARY KEY or a UNIQUE
2448/// (single- or multi-column).
2449#[derive(Debug, Clone, PartialEq)]
2450pub enum TableConstraint {
2451 /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2452 /// referenced column. Engine builds a BTree index named
2453 /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2454 PrimaryKey {
2455 name: Option<String>,
2456 columns: Vec<String>,
2457 /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2458 /// Round 621 consumed the clauses; these carry them.
2459 deferrable: bool,
2460 initially_deferred: bool,
2461 },
2462 /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2463 /// named `<table>_<leading_col>_key` (single-column) or
2464 /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2465 /// uniqueness on INSERT.
2466 Unique {
2467 name: Option<String>,
2468 columns: Vec<String>,
2469 /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2470 /// G10). PG 15+ flips the NULL handling so any number of
2471 /// NULL rows collide on the constraint. Default is
2472 /// `false` (NULLS DISTINCT, standard SQL behaviour).
2473 nulls_not_distinct: bool,
2474 /// v7.39 (round 711) — see PrimaryKey.
2475 deferrable: bool,
2476 initially_deferred: bool,
2477 },
2478 /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2479 /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2480 /// this same variant at parse time. Engine evaluates the
2481 /// predicate against each INSERT/UPDATE candidate row; a
2482 /// false / NULL result rejects the mutation.
2483 /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2484 /// PG adds such a constraint without scanning the existing rows: new
2485 /// rows are checked, the ones already there are grandfathered in, and
2486 /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2487 /// scans and flips it. pg_dump emits the suffix for exactly those, so
2488 /// validating them on restore would refuse a dump PG itself produced.
2489 Check {
2490 name: Option<String>,
2491 expr: Expr,
2492 not_valid: bool,
2493 },
2494 /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2495 /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2496 /// every element (the booking/scheduling non-overlap constraint,
2497 /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2498 /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2499 /// enforcement doesn't build the index yet). Each element pairs a
2500 /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2501 Exclude {
2502 name: Option<String>,
2503 method: Option<String>,
2504 elements: Vec<(String, String)>,
2505 },
2506 /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2507 /// non-unique secondary-index declaration inline in CREATE
2508 /// TABLE. Engine builds a BTree index on the leading column
2509 /// (composite columns parse but only the leading column is
2510 /// honoured at v7.15 — matches the existing
2511 /// `CreateIndexStatement::extra_columns` semantics). Useful
2512 /// for `mysql/blog`-style schemas that lean on routine
2513 /// secondary indexes for ORM lookups.
2514 Index {
2515 name: Option<String>,
2516 columns: Vec<String>,
2517 },
2518 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2519 /// (cols)` inline declaration. Pre-v7.17 the parser
2520 /// silently dropped these so MyISAM-imported FULLTEXT
2521 /// indexes vanished; v7.17 routes them through the
2522 /// existing tsvector-GIN engine path so MATCH AGAINST
2523 /// queries get a real inverted index instead of falling
2524 /// back to a full scan. Multi-column FULLTEXT KEYs build
2525 /// one GIN per column at v7.17 (per-column posting lists);
2526 /// the leading column drives query planning.
2527 FulltextIndex {
2528 name: Option<String>,
2529 columns: Vec<String>,
2530 },
2531}
2532
2533#[derive(Debug, Clone, PartialEq)]
2534#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2535pub struct ColumnDef {
2536 pub name: String,
2537 pub ty: ColumnTypeName,
2538 pub nullable: bool,
2539 /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2540 /// evaluates this once (with an empty row) and caches the resulting
2541 /// `Value` on the column schema.
2542 pub default: Option<Expr>,
2543 /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2544 /// per such column and fills the slot when INSERT leaves it
2545 /// unbound (omitted from a column-list INSERT or explicitly NULL).
2546 pub auto_increment: bool,
2547 /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2548 /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2549 /// an implicit BTree index named `<table>_pkey` over this
2550 /// column at CREATE TABLE time, satisfying the parent-side
2551 /// index requirement for any FOREIGN KEY pointing at it.
2552 pub is_primary_key: bool,
2553 /// v7.13.0 — inline `UNIQUE` column constraint
2554 /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2555 /// into a single-column `TableConstraint::Unique` so the
2556 /// engine path stays uniform with table-level UNIQUE.
2557 pub is_unique: bool,
2558 /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2559 /// inline column constraint: treat NULL keys as equal so only one NULL
2560 /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2561 /// `TableConstraint::Unique { nulls_not_distinct }`.
2562 pub unique_nulls_not_distinct: bool,
2563 /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2564 /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2565 /// since this round so the fold into the table-level constraint keeps it.
2566 pub constraint_deferrable: bool,
2567 pub constraint_initially_deferred: bool,
2568 /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2569 /// (mailrs round-5 G3). Stored alongside the column so the
2570 /// CREATE TABLE handler can fold these into table-level
2571 /// CHECK constraints. Multiple inline CHECKs on the same
2572 /// column are concatenated with AND at the table level.
2573 pub check: Option<Expr>,
2574 /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2575 /// parser sees an unknown column-type ident (anything not in
2576 /// the built-in `parse_column_type_name` table), it sets
2577 /// `ty = ColumnTypeName::Text` and records the original name
2578 /// here. The engine resolves at CREATE TABLE time: if a
2579 /// catalog enum/domain with this name exists, the column is
2580 /// bound to it (label-checked on INSERT for enums; CHECK-
2581 /// constrained for domains); otherwise the CREATE TABLE
2582 /// errors with "unknown type".
2583 pub user_type_ref: Option<String>,
2584 /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2585 /// CURRENT_TIMESTAMP` column attribute. When set, an
2586 /// UPDATE that does NOT explicitly bind this column
2587 /// overrides the new value with `now()` (engine clock).
2588 /// Pre-v7.17 SPG silently accepted the syntax and never
2589 /// fired the override — `updated_at` columns from mysqldump
2590 /// stayed pinned at their initial DEFAULT forever, an
2591 /// audit Tier-S silent-failure. Generalised as a stored
2592 /// expression source so future shapes (`ON UPDATE
2593 /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2594 /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2595 pub on_update_runtime: Option<Expr>,
2596 /// v7.17.0 Phase 2.5 — text collation derived from the
2597 /// post-fix `COLLATE <name>` clause (and / or the table-level
2598 /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2599 /// per column). Pre-2.5 SPG accepted the clause and
2600 /// discarded the name, leaving every column byte-compared
2601 /// — a Tier-S silent failure when the customer expected
2602 /// `_ci` / `case_insensitive` semantics. Parser normalises
2603 /// the raw collation name into the variants in `Collation`.
2604 /// Default `Binary` preserves the legacy compare path.
2605 pub collation: Collation,
2606 /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2607 /// explicit `COLLATE <name>` clause rather than the default. Under the
2608 /// MySQL dialect a text column with NO explicit clause takes the
2609 /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2610 /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2611 /// flag is the only thing that tells them apart.
2612 pub collation_explicit: bool,
2613 /// v7.39 (round 676) — the collation name AS WRITTEN, because
2614 /// `collation` above cannot carry it: `Collation` is a two-variant
2615 /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2616 /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2617 /// tell them apart.
2618 pub collation_name: Option<String>,
2619 /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2620 /// 4.4 SPG accepted and discarded the keyword, leaving
2621 /// negative values silently accepted on a column the
2622 /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2623 /// rejects negative INSERT / UPDATE values on UNSIGNED int
2624 /// columns. SPG widening to `u64`-shaped storage is out of
2625 /// v7.17 scope; the upper bound remains the signed-type max
2626 /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2627 /// exceeds what every mailrs / Rails app actually uses.
2628 pub is_unsigned: bool,
2629 /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2630 /// value list captured at parse time. When `Some`, the parser
2631 /// recognised `ENUM(...)` in the type slot; the engine
2632 /// validates INSERT cells against this list at
2633 /// column_def_to_schema time and persists the variants on
2634 /// `ColumnSchema.inline_enum_variants`. None for all
2635 /// non-ENUM columns.
2636 pub inline_enum_variants: Option<Vec<String>>,
2637 /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2638 /// value list. Distinct from ENUM (subset semantics rather
2639 /// than pick-one). None for all non-SET columns.
2640 pub inline_set_variants: Option<Vec<String>>,
2641 /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2642 /// STORED` computed-column source. When `Some`, the engine
2643 /// stores the Display-form of the parsed expression on
2644 /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2645 /// and re-evaluates the expression against every INSERT /
2646 /// UPDATE candidate row, overwriting whatever the caller
2647 /// supplied for this column. Boxed to keep `ColumnDef` from
2648 /// blowing past the `large_enum_variant` clippy ceiling
2649 /// (`Expr` widens with vector literals).
2650 pub generated_stored_expr: Option<Box<Expr>>,
2651 /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2652 /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2653 /// `auto_increment`; this additionally marks the ALWAYS one, whose
2654 /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2655 /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2656 /// VALUE`. Only meaningful when the column is also an identity column.
2657 pub identity_always: bool,
2658 /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2659 /// integer width (TINYINT / MEDIUMINT), captured before the type
2660 /// collapses to SmallInt / Int. The engine copies it to
2661 /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2662 /// path can enforce the real range. None for every other column and
2663 /// under the PG dialect.
2664 pub mysql_int_width: Option<MysqlIntWidth>,
2665 /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2666 /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2667 /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2668 /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2669 /// CREATE TABLE time so the write path can truncate and the render path
2670 /// can pad. None under the PG dialect, where temporal columns keep full
2671 /// microseconds.
2672 pub mysql_fsp: Option<u8>,
2673}
2674
2675/// v7.17.0 Phase 2.5 — text collation classification surfaced
2676/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2677/// engine bridges between the two at CREATE TABLE time.
2678///
2679/// Recognised collation-name patterns (case-insensitive):
2680/// * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase` → CaseInsensitive
2681/// * Everything else (`C`, `POSIX`, `default`,
2682/// `pg_catalog.default`, `*_cs`, `*_bin`, unknown names) → Binary
2683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2684pub enum Collation {
2685 Binary,
2686 CaseInsensitive,
2687}
2688
2689/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2690/// integer width for a column whose `ColumnTypeName` is too wide to carry
2691/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2692/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2693/// TABLE time. Only recorded under the MySQL dialect.
2694#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2695pub enum MysqlIntWidth {
2696 Tiny,
2697 Small,
2698 Medium,
2699 Int,
2700 /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2701 Big,
2702}
2703
2704#[allow(clippy::derivable_impls)]
2705impl Default for Collation {
2706 fn default() -> Self {
2707 Self::Binary
2708 }
2709}
2710
2711impl Collation {
2712 /// Classify a `COLLATE <name>` ident into one of the supported
2713 /// variants. Empty / unknown names fall back to `Binary` —
2714 /// matches the pre-2.5 silent-accept behaviour for snapshots
2715 /// that load through but don't actually depend on the
2716 /// collation semantics.
2717 #[must_use]
2718 pub fn from_collation_name(name: &str) -> Self {
2719 let lc = name.trim().to_ascii_lowercase();
2720 // Strip any quotes / schema-qualifier the parser left on
2721 // (e.g. `pg_catalog.default`).
2722 let bare = lc
2723 .trim_matches(|c: char| c == '"' || c == '\'')
2724 .rsplit('.')
2725 .next()
2726 .unwrap_or("");
2727 if bare.is_empty() {
2728 return Self::Binary;
2729 }
2730 if bare == "case_insensitive" || bare == "nocase" {
2731 return Self::CaseInsensitive;
2732 }
2733 // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2734 // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2735 if bare.ends_with("_ci") {
2736 return Self::CaseInsensitive;
2737 }
2738 Self::Binary
2739 }
2740}
2741
2742/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2743/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2744/// parse into this shape — the column-level form has a single-entry
2745/// `columns` / `parent_columns`.
2746#[derive(Debug, Clone, PartialEq)]
2747pub struct ForeignKeyConstraint {
2748 /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2749 /// today but parses + stores it so a future ALTER TABLE DROP
2750 /// CONSTRAINT can target by name (v7.6.8).
2751 pub name: Option<String>,
2752 /// Local columns participating in the FK (≥ 1).
2753 pub columns: Vec<String>,
2754 /// Referenced parent table.
2755 pub parent_table: String,
2756 /// Referenced parent columns. Must have the same arity as
2757 /// `columns`; engine validates parent has a PK / UNIQUE index
2758 /// on exactly this column set (v7.6.1).
2759 pub parent_columns: Vec<String>,
2760 /// `ON DELETE` action. Defaults to `Restrict` if absent.
2761 pub on_delete: FkAction,
2762 /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2763 pub on_update: FkAction,
2764 /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2765 pub match_type: MatchType,
2766 /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2767 /// dropped on the floor, so a constraint declared DEFERRABLE was
2768 /// enforced immediately and a circular-FK migration could not load.
2769 pub deferrable: bool,
2770 /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2771 /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2772 pub initially_deferred: bool,
2773}
2774
2775/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2776/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2777/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2778#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2779pub enum MatchType {
2780 #[default]
2781 Simple,
2782 Full,
2783}
2784
2785/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2787pub enum FkAction {
2788 /// Reject the parent mutation if any child row references it.
2789 /// SQL spec default; SPG default when no clause is given.
2790 Restrict,
2791 /// Recursively propagate the parent's delete / update to the
2792 /// child rows. Same TX.
2793 Cascade,
2794 /// Set the child FK column(s) to NULL. Requires the FK columns
2795 /// to be NULL-able.
2796 SetNull,
2797 /// Set the child FK column(s) to their declared DEFAULT.
2798 /// Requires the child column(s) to have DEFAULT.
2799 SetDefault,
2800 /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2801 /// `Restrict` because the single-writer model has no deferred
2802 /// constraint window; the keyword is accepted for compatibility.
2803 NoAction,
2804}
2805
2806/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2807/// optional `USING <encoding>` clause; omitting it keeps the
2808/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2809/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2810/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2811/// binary16 (2× compression, ~3 decimal digits of precision).
2812#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2813pub enum VecEncoding {
2814 /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
2815 /// uncompressed `vector` type wire / storage layout.
2816 #[default]
2817 F32,
2818 /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
2819 /// `spg_storage::quantize::Sq8Vector` for the math + recall
2820 /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
2821 /// dim ≥ 32).
2822 Sq8,
2823 /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
2824 /// per-element. DDL keyword `HALF` (pgvector convention).
2825 /// Bit-exact dequantise to f32 at the storage layer; no
2826 /// rerank pass needed for kNN search.
2827 F16,
2828}
2829
2830impl fmt::Display for VecEncoding {
2831 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2832 match self {
2833 Self::F32 => f.write_str("F32"),
2834 Self::Sq8 => f.write_str("SQ8"),
2835 // pgvector convention: DDL keyword is `HALF`, not `F16`.
2836 Self::F16 => f.write_str("HALF"),
2837 }
2838 }
2839}
2840
2841/// SQL-level type names. The mapping to the storage runtime's `DataType`
2842/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
2843#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2844pub enum ColumnTypeName {
2845 /// v7.39 (round 291) — PG's `name`, the identifier type its
2846 /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
2847 /// answered `type "name" does not exist` to.
2848 Name,
2849 /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
2850 /// 32-bit wrapping counter the row header carries; `xid8` is the
2851 /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
2852 /// SPG answered `type "xid" does not exist` to.
2853 Xid,
2854 Xid8,
2855 /// v7.39 (round 667) — `OID`. `XID` was already a column type here
2856 /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
2857 /// `type "oid" does not exist` while `t(x XID)` built fine.
2858 Oid,
2859 SmallInt,
2860 Int,
2861 BigInt,
2862 Float,
2863 /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
2864 /// IEEE. It used to map to [`Self::Float`] on the theory that a
2865 /// wider float is harmless, but the width is observable: a `real`
2866 /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
2867 /// answered false where PG answers true.
2868 Real,
2869 Text,
2870 /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
2871 Varchar(u32),
2872 /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
2873 Char(u32),
2874 Bool,
2875 /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
2876 /// `USING <encoding>` clause; omitting it surfaces as
2877 /// `encoding = VecEncoding::F32` (the pre-v6 default).
2878 Vector {
2879 dim: u32,
2880 encoding: VecEncoding,
2881 },
2882 /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
2883 /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
2884 /// v7.39 (round 271) — scale widened to u16 alongside the value's.
2885 /// v7.39 (round 272) — precision too: PG's runs to 1000.
2886 /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
2887 /// a negative one rounds to tens / hundreds. A VALUE's display scale
2888 /// stays unsigned.
2889 Numeric(u16, i16),
2890 /// `DATE` — calendar day, no time-of-day component.
2891 Date,
2892 /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
2893 /// precision.
2894 Timestamp,
2895 /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
2896 /// stores all timestamps as UTC microseconds-since-epoch and
2897 /// does not carry per-row offset (PG's internal representation
2898 /// is the same — TZ is a display convention). The distinction
2899 /// from `TIMESTAMP` exists for the PG-wire layer to advertise
2900 /// OID 1184 so sqlx-style clients decode into
2901 /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
2902 Timestamptz,
2903 /// v4.9 `JSON` — text-backed JSON document. No parse-time
2904 /// validation; the engine round-trips the literal verbatim.
2905 /// PG OID 114 on the wire.
2906 Json,
2907 /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
2908 /// PG OID 3802 on the wire so sqlx-style binary-typed clients
2909 /// decode without a custom type registration.
2910 Jsonb,
2911 /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
2912 /// Literal forms (decoded by the engine at coercion time):
2913 /// - PG hex form: `'\xDEADBEEF'`
2914 /// - Escape form: `'foo\\000bar'` (backslash octal triples)
2915 Bytes,
2916 /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
2917 /// OID 1009. Literal forms accepted by the parser:
2918 /// - `ARRAY['a', 'b', NULL]`
2919 /// - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
2920 /// form at coerce time)
2921 TextArray,
2922 /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
2923 /// 1007. Same literal forms as TEXT[] (substituting integer
2924 /// elements).
2925 IntArray,
2926 /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
2927 /// OID 1016.
2928 BigIntArray,
2929 /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
2930 /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
2931 /// external form). G-CRIT-3.
2932 TsVector,
2933 /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
2934 /// wire OID 3615.
2935 TsQuery,
2936 /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
2937 /// Literal input accepts canonical hyphenated, unhyphenated,
2938 /// uppercase, and `{...}`-braced forms; display normalises to
2939 /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
2940 /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
2941 /// gen_random_uuid()`.
2942 Uuid,
2943 /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
2944 /// microseconds since 00:00:00. PG wire OID 1083. Literal
2945 /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
2946 /// (6-digit microsecond precision). Display normalises to
2947 /// the canonical `HH:MM:SS[.ffffff]`.
2948 Time,
2949 /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
2950 /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
2951 /// PG OID; advertised as INT4 on the wire. Display always
2952 /// 4 digits zero-padded.
2953 Year,
2954 /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
2955 /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
2956 /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
2957 /// Offset range: ±14 hours.
2958 TimeTz,
2959 /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
2960 /// (locale-independent storage). Wire OID 790. Literal input
2961 /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
2962 /// major units), optional leading `-`. Display: en_US locale.
2963 Money,
2964 /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
2965 /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
2966 /// — the engine bridges to `DataType::Range(RangeKind)`.
2967 Range(RangeKindAst),
2968 /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
2969 /// `text => text` map with NULL value support.
2970 Hstore,
2971 /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
2972 IntArray2D,
2973 BigIntArray2D,
2974 TextArray2D,
2975 /// v7.39 (read01 round 75) — `bool[][]`.
2976 BoolArray2D,
2977 /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
2978 /// three-field {months, days, micros} struct (PG-byte-equal),
2979 /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
2980 /// β-P2 `INTERVAL` was runtime-only — literal in expression
2981 /// position but rejected at CREATE TABLE.
2982 Interval,
2983 /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
2984 /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
2985 /// PG external form quotes each non-NULL element because
2986 /// interval text contains spaces / colons
2987 /// (`{"1 day","24:00:00",NULL}`).
2988 IntervalArray,
2989 /// v7.37.5 γ — full PG array-of-scalar family. Each variant
2990 /// mirrors a scalar `ColumnTypeName` that already existed.
2991 BoolArray,
2992 SmallIntArray,
2993 FloatArray,
2994 NumericArray,
2995 DateArray,
2996 TimestampArray,
2997 TimestamptzArray,
2998 UuidArray,
2999 JsonArray,
3000 JsonbArray,
3001 BytesArray,
3002 VarcharArray,
3003 CharArray,
3004 /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
3005 /// as `Range(RangeKindAst)` — one column type variant covers
3006 /// all six builtin multiranges, kind pins the element type.
3007 /// Wire OIDs in pgwire.
3008 Multirange(RangeKindAst),
3009 /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3010 /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3011 /// Wire OIDs in pgwire.
3012 Point,
3013 Lseg,
3014 Path,
3015 PgBox,
3016 Polygon,
3017 Line,
3018 Circle,
3019 /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3020 Inet,
3021 Cidr,
3022 Macaddr,
3023 Macaddr8,
3024 /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3025 Bit(u32),
3026 /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3027 BitVarying(u32),
3028 Xml,
3029 Char1,
3030 MoneyArray,
3031}
3032
3033/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3034/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3035/// crate doesn't depend on storage. Bridged at engine boundary.
3036#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3037pub enum RangeKindAst {
3038 Int4,
3039 Int8,
3040 Num,
3041 Ts,
3042 TsTz,
3043 Date,
3044}
3045
3046impl fmt::Display for ColumnTypeName {
3047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3048 match self {
3049 Self::SmallInt => f.write_str("SMALLINT"),
3050 Self::Int => f.write_str("INT"),
3051 Self::BigInt => f.write_str("BIGINT"),
3052 Self::Float => f.write_str("FLOAT"),
3053 Self::Real => f.write_str("REAL"),
3054 Self::Text => f.write_str("TEXT"),
3055 Self::Name => f.write_str("name"),
3056 Self::Xid => f.write_str("xid"),
3057 Self::Xid8 => f.write_str("xid8"),
3058 Self::Oid => f.write_str("oid"),
3059 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3060 Self::Char(n) => write!(f, "CHAR({n})"),
3061 Self::Bool => f.write_str("BOOL"),
3062 Self::Vector { dim, encoding } => match encoding {
3063 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3064 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3065 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3066 },
3067 Self::Json => f.write_str("JSON"),
3068 Self::Jsonb => f.write_str("JSONB"),
3069 Self::Bytes => f.write_str("BYTEA"),
3070 Self::TextArray => f.write_str("TEXT[]"),
3071 Self::IntArray => f.write_str("INT[]"),
3072 Self::BigIntArray => f.write_str("BIGINT[]"),
3073 Self::TsVector => f.write_str("TSVECTOR"),
3074 Self::TsQuery => f.write_str("TSQUERY"),
3075 Self::Uuid => f.write_str("UUID"),
3076 Self::Numeric(p, s) => {
3077 if *s == 0 {
3078 write!(f, "NUMERIC({p})")
3079 } else {
3080 write!(f, "NUMERIC({p}, {s})")
3081 }
3082 }
3083 Self::Date => f.write_str("DATE"),
3084 Self::Timestamp => f.write_str("TIMESTAMP"),
3085 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3086 Self::Time => f.write_str("TIME"),
3087 Self::Year => f.write_str("YEAR"),
3088 Self::TimeTz => f.write_str("TIMETZ"),
3089 Self::Money => f.write_str("MONEY"),
3090 Self::Range(k) => f.write_str(match k {
3091 RangeKindAst::Int4 => "INT4RANGE",
3092 RangeKindAst::Int8 => "INT8RANGE",
3093 RangeKindAst::Num => "NUMRANGE",
3094 RangeKindAst::Ts => "TSRANGE",
3095 RangeKindAst::TsTz => "TSTZRANGE",
3096 RangeKindAst::Date => "DATERANGE",
3097 }),
3098 Self::Hstore => f.write_str("HSTORE"),
3099 Self::Interval => f.write_str("INTERVAL"),
3100 Self::IntervalArray => f.write_str("INTERVAL[]"),
3101 Self::BoolArray => f.write_str("BOOL[]"),
3102 Self::SmallIntArray => f.write_str("SMALLINT[]"),
3103 Self::FloatArray => f.write_str("FLOAT[]"),
3104 Self::NumericArray => f.write_str("NUMERIC[]"),
3105 Self::DateArray => f.write_str("DATE[]"),
3106 Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3107 Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3108 Self::UuidArray => f.write_str("UUID[]"),
3109 Self::JsonArray => f.write_str("JSON[]"),
3110 Self::JsonbArray => f.write_str("JSONB[]"),
3111 Self::BytesArray => f.write_str("BYTEA[]"),
3112 Self::VarcharArray => f.write_str("VARCHAR[]"),
3113 Self::CharArray => f.write_str("CHAR[]"),
3114 Self::Multirange(k) => f.write_str(match k {
3115 RangeKindAst::Int4 => "INT4MULTIRANGE",
3116 RangeKindAst::Int8 => "INT8MULTIRANGE",
3117 RangeKindAst::Num => "NUMMULTIRANGE",
3118 RangeKindAst::Ts => "TSMULTIRANGE",
3119 RangeKindAst::TsTz => "TSTZMULTIRANGE",
3120 RangeKindAst::Date => "DATEMULTIRANGE",
3121 }),
3122 Self::Point => f.write_str("POINT"),
3123 Self::Lseg => f.write_str("LSEG"),
3124 Self::Path => f.write_str("PATH"),
3125 Self::PgBox => f.write_str("BOX"),
3126 Self::Polygon => f.write_str("POLYGON"),
3127 Self::Line => f.write_str("LINE"),
3128 Self::Circle => f.write_str("CIRCLE"),
3129 Self::Inet => f.write_str("INET"),
3130 Self::Cidr => f.write_str("CIDR"),
3131 Self::Macaddr => f.write_str("MACADDR"),
3132 Self::Macaddr8 => f.write_str("MACADDR8"),
3133 Self::Bit(0) => f.write_str("BIT"),
3134 Self::Bit(n) => write!(f, "BIT({n})"),
3135 Self::BitVarying(0) => f.write_str("VARBIT"),
3136 Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3137 Self::Xml => f.write_str("XML"),
3138 Self::Char1 => f.write_str("\"char\""),
3139 Self::MoneyArray => f.write_str("MONEY[]"),
3140 Self::IntArray2D => f.write_str("INT[][]"),
3141 Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3142 Self::TextArray2D => f.write_str("TEXT[][]"),
3143 Self::BoolArray2D => f.write_str("BOOL[][]"),
3144 }
3145 }
3146}
3147
3148/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3149/// engine evaluates `expr` per matched row in the table's row order
3150/// and rewrites cells in place. Indexed columns are dropped + re-
3151/// inserted into the affected B-tree on each row change.
3152/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3153/// tail on a DML statement. Boxed off the statement struct so the PG-only
3154/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3155/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3156/// the identical meaning, so both share this one payload rather than each
3157/// growing its own.
3158#[derive(Debug, Clone, PartialEq)]
3159pub struct DmlOrderLimit {
3160 pub order_by: Vec<OrderBy>,
3161 pub limit: Option<u32>,
3162}
3163
3164/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3165/// FROM, kept so the engine can finish the job.
3166///
3167/// The parser rewrites the statement onto correlated subqueries, and it
3168/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3169/// name belongs to the target or to a source needs their column lists,
3170/// which parse time does not have. Carrying the clause lets the engine
3171/// — which has the catalog — resolve the rest.
3172#[derive(Debug, Clone, PartialEq)]
3173pub struct UpdateFromSources {
3174 pub from: FromClause,
3175 pub sub_where: Option<Expr>,
3176}
3177
3178#[derive(Debug, Clone, PartialEq)]
3179pub struct UpdateStatement {
3180 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3181 /// level UPDATE. Empty for a plain UPDATE.
3182 pub ctes: Vec<Cte>,
3183 pub table: String,
3184 /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3185 /// to `t`'s own rows and not to anything that descends from it.
3186 ///
3187 /// Round 644 taught the FROM clause the keyword and left DML behind
3188 /// because it needed a field here, and this struct carries a warning
3189 /// that round 413 measured widening it in place overflowing the
3190 /// parser's nesting stack. That warning was about `from_sources`, a
3191 /// struct wide enough to need boxing; a `bool` lands in the padding
3192 /// already present — same as `CreateTableStatement::temporary`.
3193 ///
3194 /// It also earns its keep beyond the spelling: the inheritance
3195 /// fan-out needs a way to say "the parent's own rows" as a
3196 /// statement, or running one on the parent recurses forever.
3197 pub only: bool,
3198 /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3199 /// statement's expressions refer to the target row by. PG allows the
3200 /// bare spelling here (unlike INSERT, which requires AS).
3201 pub alias: Option<String>,
3202 pub assignments: Vec<(String, Expr)>,
3203 /// v7.39 (round 533) — boxed: round 413 measured that widening this
3204 /// struct in place overflows the parser's nesting stack.
3205 pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3206 pub where_: Option<Expr>,
3207 /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3208 /// mutate the first `limit` rows in the given order. PG has no such
3209 /// clause; the parser accepts it only under the MySQL dialect. Boxed
3210 /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3211 /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3212 /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3213 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3214 /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3215 /// clause (legacy CommandComplete path). Some = engine
3216 /// evaluates the projection over each mutated row and
3217 /// streams the result as a Rows QueryResult.
3218 pub returning: Option<Vec<SelectItem>>,
3219}
3220
3221/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3222/// from the active catalog and prunes them from every index.
3223#[derive(Debug, Clone, PartialEq)]
3224pub struct DeleteStatement {
3225 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3226 /// level DELETE. Empty for a plain DELETE.
3227 pub ctes: Vec<Cte>,
3228 pub table: String,
3229 /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3230 /// to `t`'s own rows and not to anything that descends from it.
3231 ///
3232 /// Round 644 taught the FROM clause the keyword and left DML behind
3233 /// because it needed a field here, and this struct carries a warning
3234 /// that round 413 measured widening it in place overflowing the
3235 /// parser's nesting stack. That warning was about `from_sources`, a
3236 /// struct wide enough to need boxing; a `bool` lands in the padding
3237 /// already present — same as `CreateTableStatement::temporary`.
3238 ///
3239 /// It also earns its keep beyond the spelling: the inheritance
3240 /// fan-out needs a way to say "the parent's own rows" as a
3241 /// statement, or running one on the parent recurses forever.
3242 pub only: bool,
3243 /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3244 /// the WHERE / RETURNING expressions refer to the target row by.
3245 pub alias: Option<String>,
3246 pub where_: Option<Expr>,
3247 /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3248 /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3249 /// form (round 413), so it shares that payload — and it is boxed for
3250 /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3251 /// statement tipped the parser's 512 KiB nesting stack.
3252 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3253 /// v7.9.4 — `RETURNING <projection>`.
3254 pub returning: Option<Vec<SelectItem>>,
3255}
3256
3257/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3258/// One WHEN clause fires per source row depending on whether the
3259/// `on` condition matched any target row(s); the executor walks
3260/// `clauses` in declaration order and fires the first whose
3261/// `matched` kind and optional `condition` are both satisfied.
3262#[derive(Debug, Clone, PartialEq)]
3263pub struct MergeStatement {
3264 /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3265 /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3266 /// in PG). Each CTE materialises before the merge runs and its alias
3267 /// resolves as a source relation.
3268 pub ctes: Vec<Cte>,
3269 pub target: String,
3270 pub target_alias: Option<String>,
3271 pub source: String,
3272 pub source_alias: Option<String>,
3273 /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3274 /// the engine materialises this SELECT for the source rows and `source`
3275 /// is empty; the alias (required by PG for a subquery source) is in
3276 /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3277 pub source_select: Option<Box<SelectStatement>>,
3278 /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3279 /// positional column-alias list after the source alias. Empty when
3280 /// the statement carries none; the engine renames the materialised
3281 /// source columns positionally (PG's rule).
3282 pub source_column_aliases: Vec<String>,
3283 pub on: Expr,
3284 pub clauses: Vec<MergeWhenClause>,
3285 /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3286 /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3287 /// target/source aliases. `None` = no RETURNING (the common form).
3288 pub returning: Option<Vec<SelectItem>>,
3289}
3290
3291#[derive(Debug, Clone, PartialEq)]
3292pub struct MergeWhenClause {
3293 pub matched: MergeMatched,
3294 /// Optional `AND <expr>` filter — when present, the clause
3295 /// only fires for the source rows whose match-pair satisfies
3296 /// the predicate.
3297 pub condition: Option<Expr>,
3298 pub action: MergeAction,
3299}
3300
3301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3302pub enum MergeMatched {
3303 Matched,
3304 /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3305 /// target row (the classic insert branch).
3306 NotMatched,
3307 /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3308 /// row no source row matches. Actions are UPDATE / DELETE / DO
3309 /// NOTHING only (INSERT is a syntax error, as in PG).
3310 NotMatchedBySource,
3311}
3312
3313#[derive(Debug, Clone, PartialEq)]
3314pub enum MergeAction {
3315 /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3316 /// explicit column list (the bare `INSERT VALUES (vals)`
3317 /// shape lands later).
3318 Insert {
3319 columns: Vec<String>,
3320 values: Vec<Expr>,
3321 },
3322 /// `UPDATE SET col = expr [, …]` — applied to every matched
3323 /// target row for the firing source row.
3324 Update { assignments: Vec<(String, Expr)> },
3325 /// `DELETE` — drop every matched target row.
3326 Delete,
3327 /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3328 /// the clause and SPG mirrors so a customer-side MERGE that
3329 /// uses it for branch-control doesn't error).
3330 DoNothing,
3331}
3332
3333#[derive(Debug, Clone, PartialEq)]
3334pub struct InsertStatement {
3335 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3336 /// level INSERT (writable CTE outer body). Empty for a plain
3337 /// INSERT. PG semantics: each CTE materialises before the
3338 /// outer INSERT runs, sharing the same transaction.
3339 pub ctes: Vec<Cte>,
3340 pub table: String,
3341 /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3342 /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3343 /// row by. PG requires the AS keyword in this position.
3344 pub alias: Option<String>,
3345 /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3346 /// `None`, every tuple is positional and must match the table arity.
3347 /// When `Some`, the engine maps each tuple slot to the named column and
3348 /// fills the rest with NULL (must be nullable).
3349 pub columns: Option<Vec<String>>,
3350 /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3351 /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3352 /// `select_source` is `Some` (the engine builds rows from the
3353 /// inner SELECT result set instead).
3354 pub rows: Vec<Vec<Expr>>,
3355 /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3356 /// round-5 G4). When present, `rows` is empty and the engine
3357 /// materialises the SELECT result, coerces each output tuple to
3358 /// the target column types, and inserts as a single batch.
3359 pub select_source: Option<Box<SelectStatement>>,
3360 /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3361 /// upsert clause. None = legacy INSERT (conflict raises a
3362 /// DuplicateKey error). mailrs migration blocker #2.
3363 pub on_conflict: Option<OnConflictClause>,
3364 /// v7.9.4 — `RETURNING <projection>`.
3365 pub returning: Option<Vec<SelectItem>>,
3366 /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3367 /// between the column list and VALUES. Governs how explicitly-supplied
3368 /// values interact with `GENERATED … AS IDENTITY` columns:
3369 /// * `None` — default. A `GENERATED ALWAYS` identity column rejects
3370 /// an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3371 /// * `System` — override the ALWAYS restriction: the explicit value
3372 /// is used verbatim, as for a `BY DEFAULT` column.
3373 /// * `User` — ignore any explicit value on a `BY DEFAULT` identity
3374 /// column and generate from the sequence instead (no effect on
3375 /// non-identity columns).
3376 pub overriding: Overriding,
3377 /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3378 /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3379 /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3380 /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3381 /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3382 /// into a NOT NULL column becomes the type's default), and the engine
3383 /// cannot recover that intent from the conflict clause alone. A plain
3384 /// `bool` lands in this struct's existing padding, so the AST does not
3385 /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3386 pub mysql_ignore: bool,
3387}
3388
3389/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3390#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3391pub enum Overriding {
3392 /// No `OVERRIDING` clause.
3393 #[default]
3394 None,
3395 /// `OVERRIDING SYSTEM VALUE`.
3396 System,
3397 /// `OVERRIDING USER VALUE`.
3398 User,
3399}
3400
3401/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3402#[derive(Debug, Clone, PartialEq)]
3403pub struct OnConflictClause {
3404 /// Local columns that identify the conflict (must match a
3405 /// UNIQUE / PRIMARY KEY index on the target table). Empty
3406 /// list means the user wrote `ON CONFLICT DO …` without a
3407 /// target — the engine arbitrates on every unique constraint
3408 /// (round 240).
3409 pub target_columns: Vec<String>,
3410 /// v7.39 (round 240) — the index predicate after the target list
3411 /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3412 /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3413 /// which satisfy any predicate, so it is parsed and carried but not
3414 /// consulted (recorded residual: partial-unique-index arbiters).
3415 pub index_where: Option<Expr>,
3416 /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3417 /// <name>`: the pg_dump conflict-target form. The engine
3418 /// resolves the name to the constraint's columns.
3419 pub constraint_name: Option<String>,
3420 /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3421 /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3422 /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3423 /// `ON CONFLICT DO UPDATE` is refused (42601).
3424 pub mysql_lowered: bool,
3425 /// The action on conflict.
3426 pub action: OnConflictAction,
3427}
3428
3429/// v7.9.7 — action on conflict.
3430#[derive(Debug, Clone, PartialEq)]
3431pub enum OnConflictAction {
3432 /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3433 /// silently skips conflicting ones.
3434 Nothing,
3435 /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3436 /// may reference `EXCLUDED.col` to read the incoming row's
3437 /// value (engine wires `EXCLUDED` as a virtual table).
3438 Update {
3439 assignments: Vec<(String, Expr)>,
3440 where_: Option<Expr>,
3441 },
3442}
3443
3444/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3445///
3446/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3447/// policies are spelled again here and mapped at the engine boundary.
3448#[derive(Debug, Clone, PartialEq, Eq)]
3449pub struct LockingClause {
3450 pub strength: LockStrength,
3451 /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3452 pub of_tables: Vec<String>,
3453 pub policy: LockWait,
3454}
3455
3456/// PG's four tuple-lock strengths, weakest first.
3457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3458pub enum LockStrength {
3459 KeyShare,
3460 Share,
3461 NoKeyUpdate,
3462 Update,
3463}
3464
3465/// What to do when the row is already locked.
3466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3467pub enum LockWait {
3468 /// Block until it is free — PG's default.
3469 #[default]
3470 Wait,
3471 /// `NOWAIT` — fail the statement with 55P03.
3472 NoWait,
3473 /// `SKIP LOCKED` — leave the row out of the result.
3474 SkipLocked,
3475}
3476
3477#[derive(Debug, Clone, PartialEq, Default)]
3478pub struct SelectStatement {
3479 /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3480 /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3481 /// whole syntax and locked nothing: two workers running the classic
3482 /// `SKIP LOCKED` queue take both took the same row.
3483 /// v7.39 (round 305) — boxed. A locking clause appears on a
3484 /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3485 /// cost every `SelectStatement` 32 bytes, and this struct sits in
3486 /// recursive evaluation frames where the engine already runs close to
3487 /// its stack budget (a 512 KB depth guard is the canary).
3488 pub locking: Option<alloc::boxed::Box<LockingClause>>,
3489 /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3490 /// expressions, materialised once at query start before the
3491 /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3492 /// only — no `WITH RECURSIVE` for v4.x.
3493 pub ctes: Vec<Cte>,
3494 pub distinct: bool,
3495 /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3496 /// keep the first row (per ORDER BY) of each group the
3497 /// expressions define. Empty = no DISTINCT ON.
3498 pub distinct_on: Vec<Expr>,
3499 pub items: Vec<SelectItem>,
3500 pub from: Option<FromClause>,
3501 pub where_: Option<Expr>,
3502 pub group_by: Option<Vec<Expr>>,
3503 /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3504 /// expands `group_by` to every non-aggregate SELECT-list item
3505 /// before the executor runs. Mutually exclusive with an
3506 /// explicit `group_by` list (the parser sets exactly one).
3507 pub group_by_all: bool,
3508 /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3509 /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3510 /// aggregate executor resolves them through the same synthetic
3511 /// schema used for the SELECT items.
3512 pub having: Option<Expr>,
3513 /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3514 /// itself a `SelectStatement` with `order_by = None` and `limit =
3515 /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3516 /// top of the chain).
3517 pub unions: Vec<(UnionKind, SelectStatement)>,
3518 /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3519 /// Keys are matched left-to-right: first key decides, ties break
3520 /// to the second, etc.
3521 pub order_by: Vec<OrderBy>,
3522 /// `LIMIT <n>` — bound on row output. `n` is an integer
3523 /// literal **or** (v7.9.24) a placeholder `$N` resolved
3524 /// against the prepared-statement Bind values. mailrs
3525 /// migration follow-up H2.
3526 pub limit: Option<LimitExpr>,
3527 /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3528 /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3529 pub offset: Option<LimitExpr>,
3530 /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3531 /// (SQL:2008). When true and an ORDER BY is present, the
3532 /// executor extends past the LIMIT-truncated tail to include
3533 /// every row whose ORDER BY key equals the last-kept row's
3534 /// key. Requires an ORDER BY; the executor errors otherwise
3535 /// (matching PG's `WITH TIES` rule). The parser was already
3536 /// accepting `WITH TIES` since Phase 5.1; this field captures
3537 /// the choice so the executor can act on it.
3538 pub limit_with_ties: bool,
3539 /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3540 /// that NOTHING referenced. PG analyses every definition whether
3541 /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3542 /// and silently succeeded here — the referenced ones get their columns
3543 /// resolved through the WindowFunction nodes they were inlined into,
3544 /// and the unreferenced ones used to be dropped at parse, unexamined.
3545 /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3546 ///
3547 /// Not part of `Display`: an unreferenced definition has no effect on
3548 /// the result, so a deparsed body (a stored view) omits it.
3549 pub window_check_exprs: Vec<Expr>,
3550}
3551
3552impl Expr {
3553 /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3554 /// directly inside this expression to `f`. `f` receives each nested
3555 /// statement once; descending further (into that statement's own
3556 /// clauses) is the caller's job, which keeps this walk finite and
3557 /// lets the caller order the recursion.
3558 ///
3559 /// The match is deliberately **wildcard-free**: a new `Expr` variant
3560 /// does not compile until it says whether it can carry a subquery.
3561 /// The row-count resolution pass is built on this, and a shape it
3562 /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3563 /// which every row-count reader would take as "no limit", i.e. the
3564 /// whole table. Compile-time exhaustiveness is what rules that out.
3565 /// Iterative on purpose. Expression trees here get deep (long
3566 /// boolean chains, big IN lists), and this walk is on the path of
3567 /// every statement; recursing would add a frame per node to a stack
3568 /// budget the engine already runs close to — a depth guard that runs
3569 /// on a deliberately small stack caught exactly that. Depth costs
3570 /// heap here instead.
3571 pub fn for_each_subquery_mut<E>(
3572 &mut self,
3573 f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3574 ) -> Result<(), E> {
3575 let mut stack: Vec<&mut Self> = alloc::vec![self];
3576 while let Some(e) = stack.pop() {
3577 match e {
3578 Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3579 Self::NamedArg { expr, .. }
3580 | Self::Variadic(expr)
3581 | Self::Unary { expr, .. }
3582 | Self::Cast { expr, .. }
3583 | Self::FieldAccess { base: expr, .. }
3584 | Self::IsNull { expr, .. }
3585 | Self::BoolTest { expr, .. }
3586 | Self::Extract { source: expr, .. } => stack.push(expr),
3587 Self::Binary { lhs, rhs, .. } => {
3588 stack.push(lhs);
3589 stack.push(rhs);
3590 }
3591 Self::Like { expr, pattern, .. } => {
3592 stack.push(expr);
3593 stack.push(pattern);
3594 }
3595 Self::ArraySubscript { target, index } => {
3596 stack.push(target);
3597 stack.push(index);
3598 }
3599 Self::ArraySlice { target, lo, hi } => {
3600 stack.push(target);
3601 stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
3602 }
3603 Self::AnyAll { expr, array, .. } => {
3604 stack.push(expr);
3605 stack.push(array);
3606 }
3607 Self::FunctionCall { args, .. } | Self::Array(args) => {
3608 stack.extend(args.iter_mut());
3609 }
3610 Self::AggregateOrdered {
3611 call,
3612 order_by,
3613 filter,
3614 ..
3615 } => {
3616 stack.push(call);
3617 stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
3618 stack.extend(filter.iter_mut().map(|b| &mut **b));
3619 }
3620 Self::WindowFunction {
3621 args,
3622 partition_by,
3623 order_by,
3624 filter,
3625 ..
3626 } => {
3627 // `frame` bounds hold folded numbers / interval
3628 // parts, never expressions — nothing to visit there.
3629 stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
3630 stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
3631 stack.extend(filter.iter_mut().map(|b| &mut **b));
3632 }
3633 Self::InList { expr, list, .. } => {
3634 stack.push(expr);
3635 stack.extend(list.iter_mut());
3636 }
3637 Self::Case {
3638 operand,
3639 branches,
3640 else_branch,
3641 } => {
3642 stack.extend(
3643 operand
3644 .iter_mut()
3645 .chain(else_branch.iter_mut())
3646 .map(|b| &mut **b),
3647 );
3648 for (when, then) in branches.iter_mut() {
3649 stack.push(when);
3650 stack.push(then);
3651 }
3652 }
3653 Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
3654 Self::InSubquery { expr, subquery, .. } => {
3655 stack.push(expr);
3656 f(subquery)?;
3657 }
3658 Self::RowInSubquery { row, subquery, .. }
3659 | Self::RowCmpSubquery { row, subquery, .. } => {
3660 stack.extend(row.iter_mut());
3661 f(subquery)?;
3662 }
3663 }
3664 }
3665 Ok(())
3666 }
3667}
3668
3669/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
3670/// time or a placeholder `$N` resolved during extended-query
3671/// Bind. mailrs migration follow-up H2.
3672///
3673/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
3674/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
3675/// made the compiler point at every site that used to duplicate a
3676/// row-count out of the AST, which is exactly the set that must not
3677/// bypass the resolution pre-pass.
3678#[derive(Debug, Clone, PartialEq)]
3679pub enum LimitExpr {
3680 /// `LIMIT 10` — value known at parse time.
3681 Literal(u32),
3682 /// `LIMIT $N` — the 1-based parameter index, resolved against
3683 /// the bind values when the prepared statement executes.
3684 Placeholder(u16),
3685 /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
3686 /// greatest(2,3)`: a row-count expression that isn't constant, so
3687 /// it can't be folded at parse time. Evaluated once, before
3688 /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
3689 /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
3690 /// "no limit"). **No execution path may see this variant** —
3691 /// `as_literal` would report `None`, which every row-count reader
3692 /// takes to mean "unlimited", i.e. the whole table.
3693 Expr(alloc::boxed::Box<Expr>),
3694}
3695
3696impl fmt::Display for LimitExpr {
3697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3698 match self {
3699 Self::Literal(n) => write!(f, "{n}"),
3700 Self::Placeholder(n) => write!(f, "${n}"),
3701 // Parenthesised so the round-trip text re-parses as one
3702 // row-count expression (`LIMIT (SELECT 4)`), which is also
3703 // the only spelling `FETCH FIRST` accepts.
3704 Self::Expr(e) => write!(f, "({e})"),
3705 }
3706 }
3707}
3708
3709impl LimitExpr {
3710 /// Convenience for the simple-query path where no placeholders
3711 /// can possibly exist. Returns the literal value or `None` if
3712 /// this is a placeholder (caller must surface as Unsupported).
3713 ///
3714 /// v7.39 (round 305) — `None` is read by every row-count consumer as
3715 /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
3716 /// therefore silently return the whole table, so the engine's
3717 /// `resolve_limit_exprs` pre-pass rewrites the variant away before
3718 /// dispatch. The assertion makes a missed nesting site fail loudly
3719 /// in every test build rather than quietly widening a result set.
3720 #[must_use]
3721 pub fn as_literal(&self) -> Option<u32> {
3722 match self {
3723 Self::Literal(n) => Some(*n),
3724 Self::Placeholder(_) => None,
3725 Self::Expr(_) => {
3726 debug_assert!(
3727 false,
3728 "LimitExpr::Expr reached execution — resolve_limit_exprs \
3729 missed a nesting site; treating it as `no limit` would \
3730 return every row"
3731 );
3732 None
3733 }
3734 }
3735 }
3736}
3737
3738/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
3739/// the engine's `substitute_placeholders` pass these are
3740/// always Literal; in the simple-query path a Placeholder
3741/// shape returns None (executor surfaces as
3742/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
3743impl SelectStatement {
3744 #[must_use]
3745 pub fn limit_literal(&self) -> Option<u32> {
3746 self.limit.as_ref().and_then(LimitExpr::as_literal)
3747 }
3748 #[must_use]
3749 pub fn offset_literal(&self) -> Option<u32> {
3750 self.offset.as_ref().and_then(LimitExpr::as_literal)
3751 }
3752}
3753
3754#[derive(Debug, Clone, PartialEq)]
3755pub struct Cte {
3756 pub name: String,
3757 /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
3758 /// classical case) or a data-modifying statement
3759 /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
3760 /// CTE semantics. The modifying body's RETURNING projection
3761 /// becomes the materialised CTE table the outer query can
3762 /// reference; the modifying statement runs once before the
3763 /// outer query, within the same transaction.
3764 pub body: CteBody,
3765 /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
3766 /// RECURSIVE keyword. Applies to every CTE in the clause per
3767 /// PG semantics. A non-recursive body in a RECURSIVE WITH is
3768 /// allowed; the engine just runs it once.
3769 pub recursive: bool,
3770 /// v4.22: optional `WITH name(a, b, c)` column-name list. When
3771 /// non-empty, these override the body's output column names
3772 /// position-by-position; the engine errors out if the count
3773 /// doesn't match the body's projection width.
3774 pub column_overrides: Vec<String>,
3775 /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
3776 /// SET seqcol` on a recursive CTE. Desugared at parse time into an
3777 /// extra ordering column on the body (see `rewrite_search_and_cycle`).
3778 pub search: Option<SearchClause>,
3779 /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
3780 /// USING pathcol` cycle detection, desugared at parse time.
3781 pub cycle: Option<CycleClause>,
3782}
3783
3784/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
3785#[derive(Debug, Clone, PartialEq)]
3786pub struct SearchClause {
3787 /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
3788 pub depth_first: bool,
3789 /// The CTE output columns the search orders by.
3790 pub by_columns: Vec<String>,
3791 /// The new column holding the ordering key (a row-array for depth,
3792 /// a `(depth, keys…)` row for breadth).
3793 pub set_column: String,
3794}
3795
3796/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
3797#[derive(Debug, Clone, PartialEq)]
3798pub struct CycleClause {
3799 /// Columns whose repetition along a path marks a cycle.
3800 pub columns: Vec<String>,
3801 /// The new boolean-ish column set to `mark_value` on a cycle.
3802 pub mark_column: String,
3803 /// Value written to `mark_column` when a cycle is detected (default
3804 /// `true`); `default_value` otherwise. PG allows any type; SPG carries
3805 /// them as literals.
3806 pub mark_value: Option<Literal>,
3807 pub default_value: Option<Literal>,
3808 /// The new column accumulating the visited-row path array.
3809 pub path_column: String,
3810}
3811
3812/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
3813/// (Insert / Update / Delete with optional RETURNING). The
3814/// data-modifying variants must carry a RETURNING projection for the
3815/// outer query to reference the CTE alias by; an empty RETURNING is
3816/// only valid if no outer reference materialises (rare — typically
3817/// caught at planning).
3818#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
3819#[derive(Debug, Clone, PartialEq)]
3820pub enum CteBody {
3821 Select(SelectStatement),
3822 Insert(Box<InsertStatement>),
3823 Update(Box<UpdateStatement>),
3824 Delete(Box<DeleteStatement>),
3825 /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
3826 /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
3827 Merge(Box<MergeStatement>),
3828}
3829
3830impl CteBody {
3831 /// Convenience accessor used by classical (read-only) CTE
3832 /// callsites that still expect a SELECT body. Returns None for
3833 /// data-modifying CTEs; callers must explicitly route those
3834 /// through `exec_with_ctes`'s modifying branch.
3835 #[must_use]
3836 pub fn as_select(&self) -> Option<&SelectStatement> {
3837 match self {
3838 Self::Select(s) => Some(s),
3839 _ => None,
3840 }
3841 }
3842
3843 #[must_use]
3844 pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
3845 match self {
3846 Self::Select(s) => Some(s),
3847 _ => None,
3848 }
3849 }
3850
3851 #[must_use]
3852 pub fn is_modifying(&self) -> bool {
3853 !matches!(self, Self::Select(_))
3854 }
3855}
3856
3857#[derive(Debug, Clone, PartialEq)]
3858pub struct OrderBy {
3859 pub expr: Expr,
3860 /// `false` = ASC (default), `true` = DESC.
3861 pub desc: bool,
3862 /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
3863 /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
3864 /// NULLS FIRST for DESC); the engine resolves the effective
3865 /// value via `nulls_first.unwrap_or(desc)`.
3866 pub nulls_first: Option<bool>,
3867 /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
3868 /// It lives here rather than in the expression for the same reason
3869 /// `desc` does: at an ORDER BY key a collation is ordering
3870 /// information, and nothing downstream of the sort needs it. A new
3871 /// `Expr` variant would instead put a new arm on `eval_expr`, which
3872 /// this repo has measured to overflow the debug stack.
3873 ///
3874 /// `None` means none was written, and the key falls back to whatever
3875 /// its COLUMN declares — which is every key that existed before this.
3876 pub collation: Option<String>,
3877}
3878
3879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3880pub enum UnionKind {
3881 /// `UNION` — dedupes the combined set.
3882 Distinct,
3883 /// `UNION ALL` — concatenates without dedup.
3884 All,
3885 /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
3886 /// present on both sides.
3887 Intersect,
3888 /// `INTERSECT ALL` — multiset intersection (min per-row count).
3889 IntersectAll,
3890 /// `EXCEPT` — distinct left rows absent from the right.
3891 Except,
3892 /// `EXCEPT ALL` — multiset subtraction.
3893 ExceptAll,
3894}
3895
3896#[derive(Debug, Clone, PartialEq)]
3897pub enum SelectItem {
3898 Wildcard,
3899 /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
3900 /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
3901 /// `NEW` pseudo-relation).
3902 QualifiedWildcard(String),
3903 Expr {
3904 expr: Expr,
3905 alias: Option<String>,
3906 },
3907}
3908
3909#[derive(Debug, Clone, PartialEq)]
3910pub struct TableRef {
3911 pub name: String,
3912 pub alias: Option<String>,
3913 /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
3914 /// children.
3915 ///
3916 /// The keyword used to be absorbed at parse time, on the reasoning
3917 /// that SPG's inheritance children are separate relations a plain
3918 /// scan does not descend into — so ONLY already described what the
3919 /// scan did. That stopped being true when a partition parent
3920 /// started unioning its children: measured, `SELECT count(*) FROM
3921 /// ONLY <partitioned parent>` answered 2 where PG answers 0.
3922 pub only: bool,
3923 /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
3924 /// When `Some(id)`, the scan restricts to rows that live in
3925 /// segment `<id>` only — useful for forensic inspection of a
3926 /// specific freezer-emitted segment without exposing the hot
3927 /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
3928 /// is STABILITY carve-out for v6.10 — needs the freezer to
3929 /// stamp each segment with a wall-clock at creation time.
3930 pub as_of_segment: Option<u32>,
3931 /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
3932 /// source. When `Some`, `name` is the alias (defaulting to
3933 /// `"unnest"` when no `AS` is given) and the engine builds a
3934 /// synthetic single-column table by evaluating the expression
3935 /// once at SELECT entry. Each TEXT[] element becomes one row;
3936 /// NULL elements become NULL cells. v7.11 supported
3937 /// uncorrelated UNNEST only as the FROM primary; v7.13.2
3938 /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
3939 /// position (cross-join with regular tables).
3940 pub unnest_expr: Option<Box<Expr>>,
3941 /// v7.13.2 — mailrs round-6 S5. PG-standard
3942 /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
3943 /// when non-empty, the first entry overrides the projected
3944 /// column name for the unnested column. Empty = fall back to
3945 /// the table alias (pre-v7.13.2 behaviour).
3946 pub unnest_column_aliases: Vec<String>,
3947 /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
3948 /// row-stream gains a trailing BIGINT column counting rows
3949 /// from 1 in element order. PG names it `ordinality`; a second
3950 /// entry in the column-alias list renames it.
3951 pub with_ordinality: bool,
3952 /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
3953 /// [, step])` set-returning source. When `Some`, the engine
3954 /// materialises a single-column virtual table by stepping
3955 /// `start` to `stop` inclusive. Args are the literal arg list
3956 /// (2 for default-step, 3 for explicit-step). Supports:
3957 /// * SmallInt / Int / BigInt with integer step (default = 1)
3958 /// * Timestamp with INTERVAL step (PG date-range pattern)
3959 /// Mutually exclusive with `unnest_expr` — both populate the
3960 /// same downstream dispatch slot. `name` defaults to
3961 /// `"generate_series"` when no alias is provided.
3962 pub generate_series_args: Option<Vec<Expr>>,
3963 /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
3964 /// table. When `Some`, the TableRef is a parenthesised SELECT
3965 /// that may reference columns from the preceding FROM items
3966 /// (correlated derived table). The executor materialises the
3967 /// subquery per left-row, substituting outer-column references
3968 /// against the current join row's values before running the
3969 /// inner SELECT, then cross-joins the result back.
3970 /// Mutually exclusive with `name` / `unnest_expr` /
3971 /// `generate_series_args`.
3972 pub lateral_subquery: Option<Box<SelectStatement>>,
3973 /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
3974 /// function as a FROM item. PG semantics: for each key/value
3975 /// pair in the JSONB object argument, emit one (key TEXT,
3976 /// value TEXT) row. When prefixed by `LATERAL` and joined via
3977 /// `CROSS JOIN LATERAL`, the argument may reference columns
3978 /// from a preceding FROM item, in which case the executor
3979 /// evaluates `<expr>` per outer row.
3980 /// Mutually exclusive with `unnest_expr` / `generate_series_args`
3981 /// / `lateral_subquery`. The optional `LATERAL` keyword does not
3982 /// require a separate flag — the executor evaluates per-row
3983 /// whenever the join sits in a JoinKind context.
3984 ///
3985 /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
3986 /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
3987 /// `json_each` / `json_each_text`) so the executor picks the
3988 /// value-column rendering (JSON text vs unwrapped text).
3989 pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
3990 /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
3991 /// function channel: `(lowercase fn name, args)`. Carries
3992 /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
3993 /// dispatches by name.
3994 pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
3995 /// v7.39 (read01 round 78) — this FROM item is a call to a function that
3996 /// returns a BASE type, so the item's row type IS that scalar: a whole-row
3997 /// reference to it yields the value, not a one-field composite
3998 /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
3999 /// desugared shape is indistinguishable from a hand-written
4000 /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
4001 /// only the parser knows which one it built, so it says so here.
4002 pub scalar_fn_item: bool,
4003 /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
4004 /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
4005 /// target-list SRFs follow — see round 67). The array-returning family keeps
4006 /// its own lowering; this channel carries the ones that have no array form
4007 /// (`generate_series`, a user `RETURNS SETOF` function).
4008 pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
4009 /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4010 /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4011 /// tables (implicit LATERAL, like every SRF channel). Executed by
4012 /// walking the row path over the parsed doc, then each column's
4013 /// path per row-item; NESTED expands as a per-parent outer join.
4014 pub json_table: Option<Box<JsonTable>>,
4015}
4016
4017/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4018#[derive(Debug, Clone, PartialEq)]
4019pub struct JsonTable {
4020 /// The document expression (jsonb/json/text). May reference outer
4021 /// columns → implicit LATERAL.
4022 pub doc: Box<Expr>,
4023 /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4024 /// match is one row's context item.
4025 pub row_path: String,
4026 /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4027 pub columns: Vec<JsonTableColumn>,
4028 /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4029 pub passing: Vec<(String, Expr)>,
4030}
4031
4032/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4033#[derive(Debug, Clone, PartialEq)]
4034pub enum JsonTableColumn {
4035 /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4036 Ordinality { name: String },
4037 /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4038 /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4039 /// `<name> <type> EXISTS [PATH '<p>']`.
4040 Regular {
4041 name: String,
4042 ty: ColumnTypeName,
4043 /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4044 path: String,
4045 /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4046 exists: bool,
4047 /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4048 format_json: bool,
4049 /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4050 wrapper: bool,
4051 /// Behaviour when the path matches nothing (default NULL).
4052 on_empty: JsonTableOnBehavior,
4053 /// Behaviour when coercion fails (default NULL).
4054 on_error: JsonTableOnBehavior,
4055 },
4056 /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4057 /// row like a LEFT JOIN (a parent with no nested match still emits one
4058 /// row, nested cols NULL).
4059 Nested {
4060 path: String,
4061 columns: Vec<JsonTableColumn>,
4062 },
4063}
4064
4065/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4066#[derive(Debug, Clone, PartialEq)]
4067pub enum JsonTableOnBehavior {
4068 /// Default: the column value is NULL.
4069 Null,
4070 /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4071 Error,
4072 /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4073 Default(Box<Expr>),
4074}
4075
4076/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4077/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4078/// joins evaluate left-associatively in nested-loop order.
4079#[derive(Debug, Clone, PartialEq)]
4080pub struct FromClause {
4081 pub primary: TableRef,
4082 pub joins: Vec<FromJoin>,
4083}
4084
4085#[derive(Debug, Clone, PartialEq)]
4086pub struct FromJoin {
4087 pub kind: JoinKind,
4088 pub table: TableRef,
4089 /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4090 pub on: Option<Expr>,
4091 /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4092 /// USING column list so the executor can perform PG's column-merge
4093 /// (the join columns collapse to a single unqualified output column,
4094 /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4095 /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4096 /// USING into an equivalent `on` predicate so the join filter/count
4097 /// path works unchanged; `using_cols` drives only the output-shape
4098 /// rewrite. Empty/`None` for `ON` and CROSS joins.
4099 pub using_cols: Option<Vec<String>>,
4100 /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4101 /// column names are not known until the table schemas are available
4102 /// (parse time is schema-less), so the parser only sets this flag and
4103 /// leaves `on`/`using_cols` empty; the engine resolves the common
4104 /// columns at execution time, synthesises the `on` predicate + the
4105 /// USING column-merge, and clears the flag. If there are no common
4106 /// columns PG treats it as a CROSS join.
4107 pub natural: bool,
4108}
4109
4110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4111pub enum JoinKind {
4112 Inner,
4113 Left,
4114 Cross,
4115 /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4116 /// NULL-filling the left (drive) columns on unmatched right rows.
4117 /// The executor runs the LEFT algorithm's mirror: it tracks which
4118 /// peer rows matched and emits the unmatched ones with a NULL-left
4119 /// tuple after the probe loop. Output column order is unchanged
4120 /// (left-table cols then right-table cols).
4121 Right,
4122 /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4123 /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4124 FullOuter,
4125 /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4126 /// once, paired with the first peer row that satisfies the ON. Not
4127 /// reachable from SQL — the EXISTS pull-up emits it, which is what
4128 /// frees positive EXISTS from the round-721 uniqueness gate (an
4129 /// INNER join would multiply the outer rows; a semi join cannot).
4130 Semi,
4131}
4132
4133#[derive(Debug, Clone, PartialEq)]
4134pub enum Expr {
4135 Literal(Literal),
4136 Column(ColumnName),
4137 /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4138 /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4139 /// callee's declared parameter names, and a user function's live in the
4140 /// catalog — which the parser cannot see. So the name rides along in the
4141 /// tree and the evaluator, which has the catalog, does the reordering.
4142 /// Appears only inside a `FunctionCall`'s argument list.
4143 NamedArg {
4144 name: String,
4145 expr: Box<Expr>,
4146 },
4147 /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4148 /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4149 /// expression evaluates to an array whose elements the evaluator splices
4150 /// into the call as individual trailing arguments. Appears only inside a
4151 /// `FunctionCall`'s argument list.
4152 Variadic(Box<Expr>),
4153 /// v6.1.1 — `$N` parameter placeholder for the extended query
4154 /// protocol. The number is 1-based per PostgreSQL convention.
4155 /// Evaluation looks up `params[N-1]` from the prepared-statement
4156 /// bind buffer; out-of-range indices raise a runtime error
4157 /// (same shape as a column-not-found miss).
4158 Placeholder(u16),
4159 Binary {
4160 lhs: Box<Expr>,
4161 op: BinOp,
4162 rhs: Box<Expr>,
4163 },
4164 Unary {
4165 op: UnOp,
4166 expr: Box<Expr>,
4167 },
4168 /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4169 /// TEXT, BOOL targets; engine coerces at evaluation time.
4170 Cast {
4171 expr: Box<Expr>,
4172 target: CastTarget,
4173 },
4174 /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4175 /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4176 /// whole-row reference, or a composite-returning function); `field` names
4177 /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4178 /// column names for a whole-row). Only the parenthesised form reaches
4179 /// here — a bare `a.b` is parsed as a qualified column reference.
4180 FieldAccess {
4181 base: Box<Expr>,
4182 field: String,
4183 },
4184 /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4185 IsNull {
4186 expr: Box<Expr>,
4187 negated: bool,
4188 },
4189 /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4190 /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4191 /// `Some(false)` for FALSE and `None` for UNKNOWN.
4192 ///
4193 /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4194 /// The semantics were right, but the AST then had no way to say what
4195 /// the user wrote, so every renderer printed the lowering:
4196 /// `CHECK ((a > 1) IS TRUE)` came back as
4197 /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4198 /// dumped view lost the form too.
4199 BoolTest {
4200 expr: Box<Expr>,
4201 value: Option<bool>,
4202 negated: bool,
4203 },
4204 /// Function call `name(args...)`. v1.4 supports a small built-in set
4205 /// (length, upper, lower, abs, coalesce); unknown names error at eval
4206 /// time so the parser stays open for v1.5 aggregates.
4207 FunctionCall {
4208 name: String,
4209 args: Vec<Expr>,
4210 },
4211 /// v7.24 (mailrs round-16 A) — an aggregate call with an
4212 /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4213 /// Wraps the plain [`Expr::FunctionCall`] so every existing
4214 /// FunctionCall consumer stays untouched; only the aggregate
4215 /// executor (and the expression walkers) know the wrapper.
4216 /// Non-aggregate evaluation contexts reject it at eval time.
4217 AggregateOrdered {
4218 call: Box<Expr>,
4219 order_by: Vec<OrderBy>,
4220 /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4221 /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4222 /// aggregate modifier so plain FunctionCall stays untouched.
4223 distinct: bool,
4224 /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4225 /// Only the rows where `cond` is true contribute to this
4226 /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4227 /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4228 /// END)`, which is faithful for NULL-ignoring aggregates but
4229 /// WRONG for `array_agg` (it would collect a NULL per excluded
4230 /// row). The executor instead skips excluded rows before
4231 /// accumulation, which is correct for every aggregate.
4232 filter: Option<Box<Expr>>,
4233 },
4234 /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4235 /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4236 /// the next char (so `\%` matches a literal `%`).
4237 Like {
4238 expr: Box<Expr>,
4239 pattern: Box<Expr>,
4240 negated: bool,
4241 /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4242 /// match. PG folds both operands.
4243 case_insensitive: bool,
4244 },
4245 /// v4.12 window function call: `name(args) OVER (PARTITION BY
4246 /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4247 /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4248 /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4249 /// unordered windows and "from start of partition through
4250 /// current row" for ordered windows — no explicit ROWS /
4251 /// RANGE clause in v4.12 MVP.
4252 WindowFunction {
4253 name: String,
4254 args: Vec<Expr>,
4255 partition_by: Vec<Expr>,
4256 /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4257 /// (None = PG default, same contract as [`OrderBy`]).
4258 order_by: Vec<(
4259 Expr,
4260 bool, /* desc */
4261 Option<bool>, /* nulls_first */
4262 )>,
4263 /// v4.20 explicit frame. `None` means "use the default":
4264 /// whole-partition when unordered, running aggregate from
4265 /// partition start through current row when ordered.
4266 frame: Option<WindowFrame>,
4267 /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4268 /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4269 /// `Respect` (PG / ANSI default — NULLs participate). Other
4270 /// window functions ignore this flag.
4271 null_treatment: NullTreatment,
4272 /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4273 /// = no FILTER. Only aggregate window functions honor it; the
4274 /// predicate restricts which peer rows contribute within the frame.
4275 filter: Option<Box<Expr>>,
4276 },
4277 /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4278 /// position. Must return exactly one row × one column at eval
4279 /// time; the engine errors out otherwise. Uncorrelated only —
4280 /// the inner SELECT cannot reference outer columns.
4281 ScalarSubquery(Box<SelectStatement>),
4282 /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4283 /// projection is ignored; only row-count matters.
4284 Exists {
4285 subquery: Box<SelectStatement>,
4286 negated: bool,
4287 },
4288 /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4289 /// project exactly one column; membership is tested by Eq
4290 /// against each row's value (NULL handling follows ANSI:
4291 /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4292 InSubquery {
4293 expr: Box<Expr>,
4294 subquery: Box<SelectStatement>,
4295 negated: bool,
4296 },
4297 /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4298 /// against a multi-column subquery. Row comparisons against a *list*
4299 /// decompose to OR-of-AND at parse time, but the subquery form can't
4300 /// (its rows are only known at runtime), so this survives as its own
4301 /// node evaluated with PG's row-comparison three-valued logic.
4302 RowInSubquery {
4303 row: Vec<Expr>,
4304 subquery: Box<SelectStatement>,
4305 negated: bool,
4306 },
4307 /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4308 /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4309 /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4310 /// subquery form can't, so it survives as its own node. The subquery
4311 /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4312 RowCmpSubquery {
4313 row: Vec<Expr>,
4314 op: BinOp,
4315 subquery: Box<SelectStatement>,
4316 },
4317 /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4318 /// list. Both the parser's literal-list path and the engine's
4319 /// IN-subquery materialisation used to desugar into a left-deep
4320 /// OR-Eq chain, so expression depth scaled with the element count
4321 /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4322 /// (recursive eval AND recursive Box drop) and aborted embedding
4323 /// host processes. The flat node keeps depth constant: eval is an
4324 /// iterative scan with PG three-valued logic, drop is a Vec drop.
4325 InList {
4326 expr: Box<Expr>,
4327 list: Vec<Expr>,
4328 negated: bool,
4329 },
4330 /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4331 /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4332 /// because the `FROM` keyword is what separates the two halves,
4333 /// not a comma.
4334 Extract {
4335 field: ExtractField,
4336 source: Box<Expr>,
4337 },
4338 /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4339 /// element is evaluated independently; NULLs are allowed.
4340 /// v7.10 supports only single-dimension TEXT[] semantically;
4341 /// non-text elements coerce at engine evaluation time when
4342 /// the surrounding context (column type / cast) makes the
4343 /// target clear.
4344 Array(Vec<Expr>),
4345 /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4346 /// engine returns NULL for out-of-range indices.
4347 ArraySubscript {
4348 target: Box<Expr>,
4349 index: Box<Expr>,
4350 },
4351 /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4352 /// inclusive; a missing bound extends to that end of the
4353 /// array and out-of-range bounds clamp. Returns an array of
4354 /// the same element type.
4355 ArraySlice {
4356 target: Box<Expr>,
4357 lo: Option<Box<Expr>>,
4358 hi: Option<Box<Expr>>,
4359 },
4360 /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4361 /// operator is the comparison binary op (Eq / Ne / Lt / …);
4362 /// the engine desugars: `ANY` returns true if any element
4363 /// satisfies; `ALL` returns true only if every element does.
4364 /// NULL handling follows PG's three-valued logic.
4365 AnyAll {
4366 expr: Box<Expr>,
4367 op: BinOp,
4368 array: Box<Expr>,
4369 /// `true` = ANY, `false` = ALL.
4370 is_any: bool,
4371 },
4372 /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4373 /// (searched form, `operand` is None) and
4374 /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4375 /// `operand` is the lead expression compared against each
4376 /// branch's match). Each `(when_expr, then_expr)` branch
4377 /// stays as written; engine short-circuits on the first match.
4378 /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4379 /// mailrs round-5 G9.
4380 Case {
4381 operand: Option<Box<Expr>>,
4382 branches: Vec<(Expr, Expr)>,
4383 else_branch: Option<Box<Expr>>,
4384 },
4385}
4386
4387/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4388/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4389/// in the offset walk. `Ignore` causes the function to skip NULL
4390/// values in the argument expression, returning the next non-NULL.
4391#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4392pub enum NullTreatment {
4393 #[default]
4394 Respect,
4395 Ignore,
4396}
4397
4398/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4399/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4400/// where end implicitly = CURRENT ROW.
4401#[derive(Debug, Clone, PartialEq, Eq)]
4402pub struct WindowFrame {
4403 pub kind: FrameKind,
4404 pub start: FrameBound,
4405 pub end: Option<FrameBound>,
4406 /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4407 /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4408 /// no-op; CURRENT ROW drops the current row from the frame.
4409 pub exclude: FrameExclusion,
4410}
4411
4412#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4413pub enum FrameExclusion {
4414 /// Default — exclude nothing.
4415 #[default]
4416 NoOthers,
4417 /// Drop the current row from the frame.
4418 CurrentRow,
4419 /// Drop the current row's whole peer group.
4420 Group,
4421 /// Drop the current row's peers but keep the current row.
4422 Ties,
4423}
4424
4425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4426pub enum FrameKind {
4427 Rows,
4428 Range,
4429 /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4430 /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4431 /// bounds (no explicit integer offsets) GROUPS behaves identically
4432 /// to RANGE — both consult the peer-group of the current row.
4433 /// Integer offsets are not yet supported; the executor rejects
4434 /// them at run time.
4435 Groups,
4436}
4437
4438#[derive(Debug, Clone, PartialEq, Eq)]
4439pub enum FrameBound {
4440 UnboundedPreceding,
4441 OffsetPreceding(u64),
4442 CurrentRow,
4443 OffsetFollowing(u64),
4444 UnboundedFollowing,
4445 /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4446 /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4447 /// interval is folded to its (months, days, micros) components at
4448 /// parse time.
4449 IntervalPreceding {
4450 months: i32,
4451 days: i32,
4452 micros: i64,
4453 },
4454 IntervalFollowing {
4455 months: i32,
4456 days: i32,
4457 micros: i64,
4458 },
4459}
4460
4461impl fmt::Display for FrameBound {
4462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4463 match self {
4464 Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4465 Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4466 Self::CurrentRow => f.write_str("CURRENT ROW"),
4467 Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4468 Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4469 Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4470 Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4471 }
4472 }
4473}
4474
4475#[derive(Debug, Clone, PartialEq, Eq)]
4476pub enum ExtractField {
4477 Year,
4478 Month,
4479 Day,
4480 Hour,
4481 Minute,
4482 Second,
4483 Microsecond,
4484 /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4485 /// SPG keeps the integer convention — truncated seconds).
4486 Epoch,
4487 /// Day of week, 0 = Sunday … 6 = Saturday.
4488 Dow,
4489 /// ISO day of week, 1 = Monday … 7 = Sunday.
4490 Isodow,
4491 /// Day of year, 1-366.
4492 Doy,
4493 /// ISO 8601 week number, 1-53.
4494 Week,
4495 /// ISO 8601 week-numbering year (pairs with `Week`).
4496 Isoyear,
4497 /// Quarter, 1-4.
4498 Quarter,
4499 /// Year divided by 10 (floor).
4500 Decade,
4501 /// Century — 2001-2100 is century 21.
4502 Century,
4503 /// Millennium — 2001-3000 is millennium 3.
4504 Millennium,
4505 /// Julian day number (truncated for timestamps).
4506 Julian,
4507 /// Seconds and fraction in milliseconds (ss·1000 + frac).
4508 Millisecond,
4509 /// UTC offset in seconds — SPG sessions run UTC, so 0.
4510 Timezone,
4511 /// Hour component of the UTC offset — 0.
4512 TimezoneHour,
4513 /// Minute component of the UTC offset — 0.
4514 TimezoneMinute,
4515 /// v7.39 (round 253) — a field name the parser does not know. PG
4516 /// resolves EXTRACT fields at RUNTIME and reports them with the
4517 /// source type (`unit "nosuch" not recognized for type timestamp
4518 /// without time zone`, 22023), so the parser carries the raw name
4519 /// instead of rejecting.
4520 Other(String),
4521}
4522
4523impl fmt::Display for ExtractField {
4524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4525 f.write_str(match self {
4526 Self::Year => "YEAR",
4527 Self::Month => "MONTH",
4528 Self::Day => "DAY",
4529 Self::Hour => "HOUR",
4530 Self::Minute => "MINUTE",
4531 Self::Second => "SECOND",
4532 Self::Microsecond => "MICROSECOND",
4533 Self::Epoch => "EPOCH",
4534 Self::Dow => "DOW",
4535 Self::Isodow => "ISODOW",
4536 Self::Doy => "DOY",
4537 Self::Week => "WEEK",
4538 Self::Isoyear => "ISOYEAR",
4539 Self::Quarter => "QUARTER",
4540 Self::Decade => "DECADE",
4541 Self::Century => "CENTURY",
4542 Self::Millennium => "MILLENNIUM",
4543 Self::Julian => "JULIAN",
4544 Self::Millisecond => "MILLISECOND",
4545 Self::Timezone => "TIMEZONE",
4546 Self::TimezoneHour => "TIMEZONE_HOUR",
4547 Self::TimezoneMinute => "TIMEZONE_MINUTE",
4548 Self::Other(name) => return f.write_str(name),
4549 })
4550 }
4551}
4552
4553#[derive(Debug, Clone, PartialEq, Eq)]
4554pub enum CastTarget {
4555 Int,
4556 BigInt,
4557 Float,
4558 Text,
4559 Bool,
4560 Vector,
4561 Date,
4562 Timestamp,
4563 /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4564 /// H3a. Engine reuses the existing runtime-interval / timestamp
4565 /// paths (parse the text input, return the matching Value).
4566 Interval,
4567 Timestamptz,
4568 /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4569 /// types (v7.9.0); the cast just routes Text→Json with the
4570 /// requested OID for the wire layer.
4571 Json,
4572 Jsonb,
4573 /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4574 /// compatibility; engine surfaces as Unsupported with a
4575 /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4576 RegType,
4577 RegClass,
4578 /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
4579 /// the PG external array form `{a,b,NULL}`.
4580 TextArray,
4581 /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
4582 /// `{1,2,3}` or widens a `TextArray` whose elements are
4583 /// integer-shaped.
4584 IntArray,
4585 BigIntArray,
4586 /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
4587 /// external form text representation. Used by pg_dump output
4588 /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
4589 TsVector,
4590 TsQuery,
4591 /// v7.17.0 — `::uuid`. Decodes the LHS Text via
4592 /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
4593 /// unhyphenated, uppercase, and brace-wrapped forms); malformed
4594 /// input is a SQL error.
4595 Uuid,
4596 /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
4597 /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
4598 /// inputs pass through unchanged. Closes the mailrs D-pre #3
4599 /// reverse-acceptance gap — anywhere a PG schema writes
4600 /// `expr::bytea`, SPG now matches.
4601 Bytea,
4602 /// v7.37.5 ship triage — generic cast target for the long tail
4603 /// of PG type names the parser meets in `expr::TYPE` shapes that
4604 /// don't deserve their own enum variant. The engine routes these
4605 /// through `column_type_to_data_type` + the existing typed
4606 /// `coerce_value` dispatch, so adding a new PG type to SPG
4607 /// implicitly adds its cast-target form too — no parser change
4608 /// per type. The string carries the lowercase PG type ident
4609 /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
4610 /// a clear message when the type isn't known.
4611 Named(String),
4612}
4613
4614impl fmt::Display for CastTarget {
4615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4616 f.write_str(match self {
4617 Self::Int => "int",
4618 Self::BigInt => "bigint",
4619 Self::Float => "float",
4620 Self::Text => "text",
4621 Self::Bool => "bool",
4622 Self::Vector => "vector",
4623 Self::Interval => "interval",
4624 Self::Timestamptz => "timestamptz",
4625 Self::Json => "json",
4626 Self::Jsonb => "jsonb",
4627 Self::RegType => "regtype",
4628 Self::RegClass => "regclass",
4629 Self::Date => "date",
4630 Self::Timestamp => "timestamp",
4631 Self::TextArray => "TEXT[]",
4632 Self::IntArray => "INT[]",
4633 Self::BigIntArray => "BIGINT[]",
4634 Self::TsVector => "tsvector",
4635 Self::TsQuery => "tsquery",
4636 Self::Uuid => "uuid",
4637 Self::Bytea => "bytea",
4638 // v7.37.5 — `Self::Named` carries its own canonical name.
4639 Self::Named(name) => return f.write_str(name),
4640 })
4641 }
4642}
4643
4644#[derive(Debug, Clone, PartialEq)]
4645pub enum Literal {
4646 Integer(i64),
4647 Float(f64),
4648 /// Exact decimal literal — a bare `12.34`-style token, kept as
4649 /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
4650 /// before it becomes a `Value::Numeric`. PG parses such literals as
4651 /// `numeric`, not `double precision`. (Scientific/huge literals stay
4652 /// `Float`.)
4653 Numeric {
4654 unscaled: i128,
4655 /// v7.39 (round 271) — widened to u16. At u8 a literal with more
4656 /// than 255 decimal places could not be represented, and the
4657 /// conversion's `.expect("lexer-validated decimal")` aborted the
4658 /// query with an internal error on SQL PG accepts.
4659 scale: u16,
4660 },
4661 /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
4662 /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
4663 /// `Value::NumericBig` at eval; previously such literals fell back to double.
4664 NumericBig(String),
4665 String(String),
4666 Bool(bool),
4667 Null,
4668 /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
4669 Vector(Vec<f32>),
4670 /// TEXT[] value carried through the prepared-bind path
4671 /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
4672 /// text form, so the array rides the AST natively).
4673 TextArray(Vec<Option<String>>),
4674 /// INT[] value carried through the prepared-bind path.
4675 IntArray(Vec<Option<i32>>),
4676 /// BIGINT[] value carried through the prepared-bind path.
4677 BigIntArray(Vec<Option<i64>>),
4678 /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
4679 /// Three independent dimensions: `months` (variable-length;
4680 /// year/month), `days` (fixed 86400 seconds at non-DST, but
4681 /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
4682 /// stays distinguishable), and `micros` (sub-day; can carry).
4683 /// `text` keeps the original spelling so Display round-trips
4684 /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
4685 Interval {
4686 months: i32,
4687 days: i32,
4688 micros: i64,
4689 text: String,
4690 },
4691}
4692
4693#[derive(Debug, Clone, PartialEq, Eq)]
4694pub struct ColumnName {
4695 pub qualifier: Option<String>,
4696 pub name: String,
4697}
4698
4699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4700pub enum BinOp {
4701 Or,
4702 And,
4703 Eq,
4704 NotEq,
4705 /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
4706 /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
4707 /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
4708 /// non-NULL behaviour matches `<>` / `=` exactly. Common in
4709 /// PG-style JOIN ON predicates and pg_dump output.
4710 IsDistinctFrom,
4711 IsNotDistinctFrom,
4712 /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
4713 /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
4714 /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
4715 /// is a real division (round 351).
4716 IntDiv,
4717 Lt,
4718 LtEq,
4719 Gt,
4720 GtEq,
4721 Add,
4722 Sub,
4723 Mul,
4724 Div,
4725 /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
4726 /// precedence as Mul/Div; result type follows left operand.
4727 Mod,
4728 /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
4729 /// operands of equal dimension; engine returns `Value::Float(d)`.
4730 L2Distance,
4731 /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
4732 GeomParallel,
4733 /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
4734 OverLeft,
4735 OverRight,
4736 /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
4737 GeomPerp,
4738 /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
4739 GeomSameAs,
4740 /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
4741 /// object to the left-hand one.
4742 ClosestPoint,
4743 /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
4744 GeomHoriz,
4745 /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
4746 /// more similar" remains true (matches pgvector's published convention).
4747 InnerProduct,
4748 /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
4749 CosineDistance,
4750 /// SQL string concatenation `||`. NULL propagates.
4751 Concat,
4752 /// Bitwise OR `|` on integers.
4753 BitOr,
4754 /// Bitwise AND `&` on integers.
4755 BitAnd,
4756 /// Bitwise XOR `#` on integers and equal-length bit strings.
4757 BitXor,
4758 /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
4759 /// sides as truth values and returns their exclusive-or (`1 XOR 0`
4760 /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
4761 /// MySQL dialect produces it; PG has no logical XOR. Its precedence
4762 /// sits between OR (loosest) and AND.
4763 LogicalXor,
4764 /// v4.14 `json -> key` — element access by string key (object)
4765 /// or integer index (array). Returns a JSON value.
4766 JsonGet,
4767 /// v4.14 `json ->> key` — same access, returns the result as
4768 /// TEXT (unwraps a top-level JSON string; renders other scalars
4769 /// as their canonical text).
4770 JsonGetText,
4771 /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
4772 /// text array literal like `'{a,0,b}'`. Returns JSON.
4773 JsonGetPath,
4774 /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
4775 JsonGetPathText,
4776 /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
4777 /// when every key/value in `sub_json` is structurally present in
4778 /// the left side. Matches PG semantics (top-level + recursive).
4779 JsonContains,
4780 /// `@?` — jsonb path existence (jsonb_path_exists).
4781 JsonPathExists,
4782 /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
4783 /// `a <@ b` is defined as `b @> a` (same semantics, swapped
4784 /// sides). Eval dispatch reuses `JsonContains` with swapped args.
4785 JsonContainedBy,
4786 /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
4787 /// returns BOOL. For an object, true if `key` is an existing
4788 /// member name; for an array, true if any element is the string
4789 /// `key` (PG semantics).
4790 JsonKeyExists,
4791 /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
4792 /// returns BOOL.
4793 JsonKeysAny,
4794 /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
4795 /// returns BOOL.
4796 JsonKeysAll,
4797 /// `jsonb #- path_text[]` — delete the value at a nested path.
4798 /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
4799 JsonDeletePath,
4800 /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
4801 /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
4802 /// tsvector` and engine eval normalises either ordering.
4803 TsMatch,
4804 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
4805 /// `<<`. LHS network is strictly inside RHS network (no equality).
4806 InetContainedBy,
4807 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
4808 /// `<<=`. LHS network ⊆ RHS network.
4809 InetContainedByEq,
4810 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
4811 /// LHS network strictly contains RHS network.
4812 InetContains,
4813 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
4814 /// LHS network ⊇ RHS network.
4815 InetContainsEq,
4816 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
4817 /// True iff either network contains any address of the other.
4818 InetOverlap,
4819 /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
4820 /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
4821 Intersects,
4822 /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
4823 /// (point, box).
4824 IsBelow,
4825 IsAbove,
4826 /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
4827 /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
4828 /// where `'A' < 'a'` is false under a non-C collation, which is the
4829 /// whole reason the operator family exists — it is what makes a LIKE
4830 /// prefix index-usable. pg_dump writes these into index definitions.
4831 PatternLt,
4832 PatternLtEq,
4833 PatternGt,
4834 PatternGtEq,
4835}
4836
4837#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4838pub enum UnOp {
4839 Not,
4840 Neg,
4841 /// Bitwise NOT `~` on integers.
4842 BitNot,
4843 /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
4844 /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
4845 /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
4846 /// while PG18 and MariaDB accept every one of them.
4847 ///
4848 /// It is not a no-op to drop at parse time — PG refuses it on
4849 /// non-numeric operands ("operator does not exist: + boolean"), so the
4850 /// operand's type has to be seen at eval.
4851 Plus,
4852}
4853
4854// --- Display impls (round-trip-safe) --------------------------------------
4855
4856impl Statement {
4857 /// v7.18 — classify whether the statement is read-only at
4858 /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
4859 /// route SELECT-shaped traffic through the fan-out
4860 /// `AsyncReadHandle` (no writer-lock contention) while
4861 /// keeping DML / DDL / TX-control on the single-writer path.
4862 ///
4863 /// The classification matches what
4864 /// `Engine::execute_readonly_with_cancel` accepts: anything
4865 /// that does NOT mutate catalog, statistics, session state,
4866 /// or transaction state. WaitForWalPosition is included
4867 /// (engine returns `Unsupported`, but the classification is
4868 /// semantically read-only — no mutation). Empty is excluded
4869 /// out of an abundance of caution — the no-op routes
4870 /// through the writer so any future side effect lands
4871 /// uniformly.
4872 ///
4873 /// **Not connection-state aware**. `SET LOCAL` / `RESET`
4874 /// affect session parameters and must run on the writer
4875 /// engine that owns the session state; they classify as
4876 /// writer-path here. Same for `BEGIN` / `COMMIT` /
4877 /// `ROLLBACK` / `SAVEPOINT` — transaction control is
4878 /// always writer-path.
4879 /// v7.39 (round 435) — does this statement implicitly COMMIT an open
4880 /// transaction under MySQL?
4881 ///
4882 /// PG runs DDL inside the transaction; MySQL commits before (and after)
4883 /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
4884 /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
4885 /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
4886 /// nested START TRANSACTION; and measured NOT to fire for `CREATE
4887 /// TEMPORARY TABLE`, `SET`, or a SELECT.
4888 ///
4889 /// A positive list, not "everything that is not DML": a statement
4890 /// wrongly listed here commits a client's data early, which is as bad as
4891 /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
4892 /// COMPACT) are left out — a MySQL session never sends them.
4893 #[must_use]
4894 pub fn mysql_implicit_commit(&self) -> bool {
4895 match self {
4896 // MySQL's documented exception, measured on MariaDB 11: a
4897 // TEMPORARY table is not DDL for this purpose and does not
4898 // commit. (Round 435 got this for free because the parser then
4899 // lowered that spelling to `Statement::Empty`; round 436 made it
4900 // a real CREATE TABLE, and the round-435 pin caught it.)
4901 Self::CreateTable(c) => !c.temporary,
4902 // MySQL commits the open transaction and opens a fresh one.
4903 Self::Begin { .. }
4904 | Self::DropTable { .. }
4905 | Self::DropIndex { .. }
4906 | Self::CreateIndex(_)
4907 | Self::AlterIndex { .. }
4908 | Self::AlterTable(_)
4909 | Self::Truncate { .. }
4910 | Self::Analyze { .. }
4911 | Self::CreateStatistics { .. }
4912 | Self::DropStatistics { .. }
4913 | Self::CreateView { .. }
4914 | Self::DropView { .. }
4915 | Self::CreateMaterializedView { .. }
4916 | Self::RefreshMaterializedView { .. }
4917 | Self::DropMaterializedView { .. }
4918 | Self::CreateSequence(_)
4919 | Self::AlterSequence { .. }
4920 | Self::DropSequence { .. }
4921 | Self::CreateFunction(_)
4922 | Self::DropFunction { .. }
4923 | Self::CreateTrigger(_)
4924 | Self::DropTrigger { .. }
4925 | Self::CreateRule(_)
4926 | Self::DropRule { .. }
4927 | Self::CreateType(_)
4928 | Self::DropType { .. }
4929 | Self::AlterTypeAddValue { .. }
4930 | Self::AlterTypeRenameValue { .. }
4931 | Self::CreateDomain(_)
4932 | Self::AlterDomain { .. }
4933 | Self::DropDomain { .. }
4934 | Self::CreateSchema { .. }
4935 | Self::DropSchema { .. }
4936 | Self::CreateUser { .. }
4937 | Self::DropUser { .. }
4938 | Self::Grant { .. }
4939 | Self::Revoke { .. }
4940 | Self::CreatePolicy(_)
4941 | Self::AlterPolicy(_)
4942 | Self::DropPolicy { .. }
4943 | Self::CommentOn { .. }
4944 | Self::CreateExtension { .. } => true,
4945 _ => false,
4946 }
4947 }
4948
4949 #[must_use]
4950 pub fn is_readonly(&self) -> bool {
4951 match self {
4952 // v7.39 (round 288) — SET CONSTRAINTS changes transaction
4953 // state, and IMMEDIATE can run the deferred checks there and
4954 // then; writer-path.
4955 Statement::SetConstraints { .. } => false,
4956 // v7.39 (round 695) — it writes nothing (SPG has no
4957 // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
4958 // writer and a read-only session refuses it there too.
4959 Statement::AlterSystem { .. } => false,
4960 // Same shape: a no-op here, a writer to PG, so a read-only
4961 // session refuses it as PG's would.
4962 Statement::NoOpPreventedInTransaction { .. } => false,
4963 Statement::DropDatabase { .. } => false,
4964 // v7.39 (round 696) — they perform nothing, so nothing is
4965 // written; PG classes LOCK and the OWNED BY pair as writers and
4966 // a read-only session refuses them there.
4967 Statement::ValidateOnly { .. } => false,
4968 // v7.39 (round 750) — a credential rotation persists.
4969 Statement::AlterRolePassword { .. } => true,
4970 Statement::DropAggregate { .. } => false,
4971 // v7.39 (round 547) — records a GUC default in the catalog.
4972 Statement::SetDbRoleSetting(_) => false,
4973 // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
4974 // but they name a relation and PG refuses one that is not
4975 // there, so they are not read-only in the sense this asks.
4976 Statement::Maintain { .. } => false,
4977 // v7.39 (round 277) — the prepared-statement surface is
4978 // session state, like SET; writer-path so it lands on the
4979 // engine that owns the session. EXECUTE may also run a
4980 // write, and its body is only known at execution time.
4981 Statement::Prepare { .. }
4982 | Statement::Execute { .. }
4983 | Statement::Deallocate(_)
4984 | Statement::Call(_)
4985 | Statement::PrepareTransaction(_)
4986 | Statement::CreateStatistics { .. }
4987 | Statement::DropStatistics { .. }
4988 // v7.39 (round 318, V51) — KILL signals another connection;
4989 // it must run on the writer path that owns the registry hook.
4990 | Statement::Kill { .. }
4991 // v7.39 (round 320, V53) — DISCARD throws session state away;
4992 // writer path, like SET / RESET.
4993 | Statement::Discard(_) => false,
4994 // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
4995 // locks MUTATES the lock table, so it is not a read. Left as
4996 // a read it went to the read-only executor and the locking
4997 // pre-pass never ran at all — the clause was honoured only
4998 // inside an explicit transaction, and silently ignored in
4999 // autocommit, which is where a queue worker runs it.
5000 Statement::Select(s) if s.locking.is_some() => false,
5001 Statement::Select(_)
5002 | Statement::CopyTo { .. }
5003 | Statement::CopyToFile { .. }
5004 | Statement::Explain(_)
5005 | Statement::ShowTables
5006 | Statement::ShowDatabases
5007 | Statement::ShowCreateTable(_)
5008 | Statement::ShowIndexes(_)
5009 | Statement::ShowStatus
5010 | Statement::ShowVariables
5011 | Statement::ShowProcesslist
5012 | Statement::ShowColumns(_)
5013 | Statement::ShowUsers
5014 | Statement::ShowPublications
5015 | Statement::ShowSubscriptions
5016 | Statement::WaitForWalPosition { .. } => true,
5017 // Everything else mutates catalog, statistics,
5018 // session state, or transaction state — writer path.
5019 // Listed explicitly so a new Statement variant fails
5020 // the match exhaustiveness check and forces a
5021 // classification decision at add-site.
5022 Statement::Empty
5023 // v7.39 (round 169) — VACUUM mutates storage (reclaims
5024 // tombstoned versions): writer path.
5025 | Statement::Vacuum { .. }
5026 | Statement::DropTable { .. }
5027 | Statement::DropIndex { .. }
5028 | Statement::CreateTable(_)
5029 | Statement::CreateExtension(_)
5030 | Statement::DoBlock(_)
5031 | Statement::CreateIndex(_)
5032 | Statement::Insert(_)
5033 | Statement::Update(_)
5034 | Statement::Delete(_)
5035 | Statement::Merge(_)
5036 | Statement::Begin(_)
5037 | Statement::Commit
5038 | Statement::Rollback
5039 | Statement::Savepoint(_)
5040 | Statement::RollbackToSavepoint(_)
5041 | Statement::ReleaseSavepoint(_)
5042 | Statement::CreateUser(_)
5043 | Statement::DropUser { .. }
5044 | Statement::SetRole(_)
5045 | Statement::Grant(_)
5046 | Statement::Revoke(_)
5047 | Statement::CreatePolicy(_)
5048 | Statement::AlterPolicy(_)
5049 | Statement::DropPolicy(_)
5050 | Statement::AlterIndex(_)
5051 | Statement::AlterTable(_)
5052 | Statement::CreatePublication(_)
5053 | Statement::DropPublication { .. }
5054 | Statement::CreateSubscription(_)
5055 | Statement::DropSubscription { .. }
5056 | Statement::Analyze(_)
5057 | Statement::Truncate { .. }
5058 | Statement::CompactColdSegments
5059 | Statement::SetParameter { .. }
5060 | Statement::SetParameterList(_)
5061 | Statement::SetUserVars(..)
5062 | Statement::SetTransaction { .. }
5063 | Statement::ShowParameter(_)
5064 | Statement::ResetParameter(_)
5065 | Statement::CreateFunction(_)
5066 | Statement::CreateTrigger(_)
5067 | Statement::DropTrigger { .. }
5068 | Statement::CreateRule(_)
5069 | Statement::DropRule { .. }
5070 | Statement::DropFunction { .. }
5071 | Statement::CreateSequence(_)
5072 | Statement::AlterSequence(_)
5073 | Statement::DropSequence { .. }
5074 | Statement::CreateView(_)
5075 | Statement::DropView { .. }
5076 | Statement::CreateMaterializedView(_)
5077 | Statement::RefreshMaterializedView { .. }
5078 | Statement::DropMaterializedView { .. }
5079 | Statement::CreateType(_)
5080 | Statement::AlterTypeAddValue { .. }
5081 | Statement::AlterTypeRenameValue { .. }
5082 | Statement::CommentOn { .. }
5083 | Statement::DropType { .. }
5084 | Statement::CreateDomain(_)
5085 | Statement::DropDomain { .. }
5086 | Statement::CreateSchema { .. }
5087 | Statement::DropSchema { .. }
5088 // v7.39 (round 218) — cursors mutate per-session cursor state
5089 // (open/position/close) on the writer engine: writer path.
5090 | Statement::DeclareCursor { .. }
5091 | Statement::FetchCursor { .. }
5092 | Statement::MoveCursor { .. }
5093 | Statement::CloseCursor { .. }
5094 // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5095 // state / the notification queue: writer path.
5096 | Statement::Listen(_)
5097 | Statement::Notify { .. }
5098 | Statement::Unlisten(_)
5099 | Statement::CopyFromFile { .. }
5100 | Statement::AlterDomain { .. } => false,
5101 }
5102 }
5103}
5104
5105/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5106/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5107#[derive(Debug, Clone, PartialEq, Eq)]
5108pub struct GrantStatement {
5109 /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5110 /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5111 /// is why they keep the case the user typed.
5112 pub privileges: Vec<GrantPriv>,
5113 /// What the privileges are on.
5114 pub object: GrantObject,
5115 /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5116 pub grantees: Vec<String>,
5117 /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5118 /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5119 /// privilege itself).
5120 pub grant_option: bool,
5121}
5122
5123/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5124/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5125/// An empty column list means the privilege is table-wide.
5126#[derive(Debug, Clone, PartialEq, Eq)]
5127pub struct GrantPriv {
5128 pub word: String,
5129 pub columns: Vec<String>,
5130}
5131
5132/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5133/// privileges; every other object class parses and is accepted as a no-op, so
5134/// a pg_dump that grants on schemas / sequences / functions still restores.
5135#[derive(Debug, Clone, PartialEq, Eq)]
5136pub enum GrantObject {
5137 /// `ON [TABLE] a, b` — the enforced case.
5138 Tables(Vec<String>),
5139 /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5140 /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5141 /// granted roles; the grantees are the members.
5142 Roles(Vec<String>),
5143 /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5144 /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5145 Sequences(Vec<String>),
5146 /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5147 Schemas(Vec<String>),
5148 /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5149 Databases(Vec<String>),
5150 /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5151 /// (SPG keys functions by name); the argument list parses and is dropped.
5152 Functions(Vec<(String, Option<Vec<String>>)>),
5153 /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5154 /// every table at GRANT time, exactly like PG.
5155 AllTablesInSchema,
5156 /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5157 /// message.
5158 Other(String),
5159}
5160
5161impl GrantStatement {
5162 /// Round-trip text. `grant = false` renders the REVOKE form.
5163 fn render(&self, grant: bool) -> alloc::string::String {
5164 use core::fmt::Write as _;
5165 let mut s = alloc::string::String::new();
5166 let privs = if self.privileges.is_empty() {
5167 alloc::string::String::from("ALL")
5168 } else {
5169 let parts: Vec<_> = self
5170 .privileges
5171 .iter()
5172 .map(|p| {
5173 if p.columns.is_empty() {
5174 p.word.clone()
5175 } else {
5176 let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5177 alloc::format!("{} ({})", p.word, cols.join(", "))
5178 }
5179 })
5180 .collect();
5181 parts.join(", ")
5182 };
5183 let obj = match &self.object {
5184 GrantObject::Tables(t) => {
5185 let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5186 alloc::format!("TABLE {}", names.join(", "))
5187 }
5188 GrantObject::Roles(r) => {
5189 let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5190 names.join(", ")
5191 }
5192 GrantObject::Sequences(n) => {
5193 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5194 alloc::format!("SEQUENCE {}", names.join(", "))
5195 }
5196 GrantObject::Schemas(n) => {
5197 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5198 alloc::format!("SCHEMA {}", names.join(", "))
5199 }
5200 GrantObject::Databases(n) => {
5201 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5202 alloc::format!("DATABASE {}", names.join(", "))
5203 }
5204 GrantObject::Functions(n) => {
5205 let names: Vec<_> = n
5206 .iter()
5207 .map(|(name, args)| match args {
5208 Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5209 None => quote_ident(name),
5210 })
5211 .collect();
5212 alloc::format!("FUNCTION {}", names.join(", "))
5213 }
5214 GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5215 GrantObject::Other(k) => k.clone(),
5216 };
5217 let who: Vec<_> = self
5218 .grantees
5219 .iter()
5220 .map(|g| {
5221 if g.is_empty() {
5222 "PUBLIC".into()
5223 } else {
5224 quote_ident(g)
5225 }
5226 })
5227 .collect();
5228 if let GrantObject::Roles(_) = &self.object {
5229 let _ = if grant {
5230 write!(s, "GRANT {obj} TO {}", who.join(", "))
5231 } else {
5232 write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5233 };
5234 return s;
5235 }
5236 if grant {
5237 let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5238 if self.grant_option {
5239 s.push_str(" WITH GRANT OPTION");
5240 }
5241 } else {
5242 s.push_str("REVOKE ");
5243 if self.grant_option {
5244 s.push_str("GRANT OPTION FOR ");
5245 }
5246 let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5247 }
5248 s
5249 }
5250}
5251
5252impl fmt::Display for Statement {
5253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5254 match self {
5255 Self::Empty => Ok(()),
5256 // v7.39 (round 695) — deparsed the way PG writes it.
5257 // v7.39 (round 696) — never deparsed into a dump (nothing is
5258 // stored), so the shortest faithful spelling of what it was.
5259 Self::DropAggregate { if_exists, items } => {
5260 f.write_str("DROP AGGREGATE ")?;
5261 if *if_exists {
5262 f.write_str("IF EXISTS ")?;
5263 }
5264 for (i, (name, args)) in items.iter().enumerate() {
5265 if i > 0 {
5266 f.write_str(", ")?;
5267 }
5268 match args {
5269 Some(a) => write!(f, "{name}({})", a.join(", "))?,
5270 None => write!(f, "{name}(*)")?,
5271 }
5272 }
5273 Ok(())
5274 }
5275 Self::AlterRolePassword { name, password } => {
5276 write!(f, "ALTER ROLE {}", quote_ident(name))?;
5277 match password {
5278 Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5279 None => f.write_str(" PASSWORD NULL"),
5280 }
5281 }
5282 Self::ValidateOnly { kind, names } => match kind {
5283 ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5284 ValidateOnlyKind::RoleName => {
5285 write!(f, "DROP OWNED BY {}", names.join(", "))
5286 }
5287 ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5288 ValidateOnlyKind::ExtensionAvailable => {
5289 write!(f, "CREATE EXTENSION {}", names.join(", "))
5290 }
5291 ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5292 ValidateOnlyKind::CollationName => {
5293 write!(f, "DROP COLLATION {}", names.join(", "))
5294 }
5295 ValidateOnlyKind::TsConfigName => {
5296 write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5297 }
5298 ValidateOnlyKind::EventTriggerName => {
5299 write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5300 }
5301 ValidateOnlyKind::TablespaceName => {
5302 write!(f, "DROP TABLESPACE {}", names.join(", "))
5303 }
5304 ValidateOnlyKind::LargeObjectOid => {
5305 write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5306 }
5307 ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5308 ValidateOnlyKind::AggregateName => {
5309 write!(f, "ALTER AGGREGATE {}", names.join(", "))
5310 }
5311 ValidateOnlyKind::ConversionName => {
5312 write!(f, "DROP CONVERSION {}", names.join(", "))
5313 }
5314 ValidateOnlyKind::LanguageName => {
5315 write!(f, "DROP LANGUAGE {}", names.join(", "))
5316 }
5317 ValidateOnlyKind::ExtensionInstalled => {
5318 write!(f, "DROP EXTENSION {}", names.join(", "))
5319 }
5320 },
5321 Self::AlterSystem { parameter } => match parameter {
5322 Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5323 None => f.write_str("ALTER SYSTEM RESET ALL"),
5324 },
5325 // v7.39 (round 547) — round-trips as PG writes it.
5326 Self::SetDbRoleSetting(st) => {
5327 match (&st.database, &st.role) {
5328 (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5329 (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5330 (None, None) => f.write_str("ALTER ROLE ALL")?,
5331 }
5332 if let (Some(d), Some(_)) = (&st.database, &st.role) {
5333 write!(f, " IN DATABASE {d}")?;
5334 }
5335 match (&st.param, &st.value) {
5336 (None, _) => f.write_str(" RESET ALL"),
5337 (Some(p), None) => write!(f, " RESET {p}"),
5338 (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5339 }
5340 }
5341 Self::Maintain {
5342 kind,
5343 concurrently,
5344 target,
5345 } => {
5346 f.write_str(match kind {
5347 crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5348 _ => "REINDEX ",
5349 })?;
5350 if *concurrently {
5351 f.write_str("CONCURRENTLY ")?;
5352 }
5353 if let Some(t) = target {
5354 f.write_str(t)?;
5355 }
5356 Ok(())
5357 }
5358 Self::DropDatabase { name, if_exists } => {
5359 f.write_str("DROP DATABASE ")?;
5360 if *if_exists {
5361 f.write_str("IF EXISTS ")?;
5362 }
5363 f.write_str(name)
5364 }
5365 Self::NoOpPreventedInTransaction { what } => f.write_str(what),
5366 Self::SetConstraints { names, deferred } => {
5367 f.write_str("SET CONSTRAINTS ")?;
5368 if names.is_empty() {
5369 f.write_str("ALL")?;
5370 } else {
5371 for (i, n) in names.iter().enumerate() {
5372 if i > 0 {
5373 f.write_str(", ")?;
5374 }
5375 f.write_str(n)?;
5376 }
5377 }
5378 f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5379 }
5380 // v7.39 (round 277) — the source text is kept verbatim so
5381 // `pg_prepared_statements.statement` can report it the way
5382 // PG does (the whole PREPARE statement, not just the body).
5383 Self::Prepare { source, .. } => f.write_str(source),
5384 Self::Execute { name, args } => {
5385 write!(f, "EXECUTE {}", quote_ident(name))?;
5386 if !args.is_empty() {
5387 f.write_str("(")?;
5388 for (i, a) in args.iter().enumerate() {
5389 if i > 0 {
5390 f.write_str(", ")?;
5391 }
5392 write!(f, "{a}")?;
5393 }
5394 f.write_str(")")?;
5395 }
5396 Ok(())
5397 }
5398 Self::CreateStatistics {
5399 name,
5400 if_not_exists,
5401 kinds,
5402 columns,
5403 table,
5404 } => {
5405 f.write_str("CREATE STATISTICS ")?;
5406 if *if_not_exists {
5407 f.write_str("IF NOT EXISTS ")?;
5408 }
5409 write!(f, "{}", quote_ident(name))?;
5410 if !kinds.is_empty() {
5411 write!(f, " ({})", kinds.join(", "))?;
5412 }
5413 write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5414 }
5415 Self::DropStatistics { name, if_exists } => {
5416 f.write_str("DROP STATISTICS ")?;
5417 if *if_exists {
5418 f.write_str("IF EXISTS ")?;
5419 }
5420 write!(f, "{}", quote_ident(name))
5421 }
5422 Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5423 Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5424 Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5425 Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5426 Self::DeclareCursor {
5427 name,
5428 scroll,
5429 hold,
5430 query,
5431 } => {
5432 write!(f, "DECLARE {} ", quote_ident(name))?;
5433 match scroll {
5434 Some(true) => f.write_str("SCROLL ")?,
5435 Some(false) => f.write_str("NO SCROLL ")?,
5436 None => {}
5437 }
5438 f.write_str("CURSOR ")?;
5439 if *hold {
5440 f.write_str("WITH HOLD ")?;
5441 }
5442 write!(f, "FOR {query}")
5443 }
5444 Self::FetchCursor { name, direction } => {
5445 write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5446 }
5447 Self::MoveCursor { name, direction } => {
5448 write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5449 }
5450 Self::CloseCursor { name } => match name {
5451 Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5452 None => f.write_str("CLOSE ALL"),
5453 },
5454 Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5455 Self::Notify { channel, payload } => {
5456 write!(f, "NOTIFY {}", quote_ident(channel))?;
5457 if let Some(p) = payload {
5458 write!(f, ", '{}'", p.replace('\'', "''"))?;
5459 }
5460 Ok(())
5461 }
5462 Self::Unlisten(ch) => match ch {
5463 Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5464 None => f.write_str("UNLISTEN *"),
5465 },
5466 Self::CopyTo {
5467 table,
5468 columns,
5469 query,
5470 options,
5471 } => {
5472 if let Some(q) = query {
5473 write!(f, "COPY ({q})")?;
5474 } else {
5475 write!(f, "COPY {table}")?;
5476 if let Some(cols) = columns {
5477 write!(f, " ({})", cols.join(", "))?;
5478 }
5479 }
5480 write!(f, " TO STDOUT")?;
5481 let mut parts: Vec<String> = Vec::new();
5482 if options.format == CopyFormat::Csv {
5483 parts.push("FORMAT csv".to_string());
5484 }
5485 if options.header {
5486 parts.push("HEADER true".to_string());
5487 }
5488 if let Some(d) = options.delimiter {
5489 parts.push(alloc::format!("DELIMITER '{d}'"));
5490 }
5491 if let Some(n) = &options.null_str {
5492 parts.push(alloc::format!("NULL '{n}'"));
5493 }
5494 if let Some(q) = options.quote {
5495 parts.push(alloc::format!("QUOTE '{q}'"));
5496 }
5497 if !parts.is_empty() {
5498 write!(f, " WITH ({})", parts.join(", "))?;
5499 }
5500 Ok(())
5501 }
5502 Self::CopyFromFile {
5503 table,
5504 columns,
5505 path,
5506 options,
5507 } => {
5508 write!(f, "COPY {table}")?;
5509 if let Some(cols) = columns {
5510 write!(f, " ({})", cols.join(", "))?;
5511 }
5512 write!(f, " FROM '{path}'")?;
5513 let mut parts: Vec<String> = Vec::new();
5514 if options.format == CopyFormat::Csv {
5515 parts.push("FORMAT csv".to_string());
5516 }
5517 if options.header {
5518 parts.push("HEADER true".to_string());
5519 }
5520 if let Some(d) = options.delimiter {
5521 parts.push(alloc::format!("DELIMITER '{d}'"));
5522 }
5523 if let Some(n) = &options.null_str {
5524 parts.push(alloc::format!("NULL '{n}'"));
5525 }
5526 if let Some(q) = options.quote {
5527 parts.push(alloc::format!("QUOTE '{q}'"));
5528 }
5529 if !parts.is_empty() {
5530 write!(f, " WITH ({})", parts.join(", "))?;
5531 }
5532 Ok(())
5533 }
5534 Self::CopyToFile {
5535 table,
5536 columns,
5537 query,
5538 path,
5539 options,
5540 } => {
5541 if let Some(q) = query {
5542 write!(f, "COPY ({q})")?;
5543 } else {
5544 write!(f, "COPY {table}")?;
5545 if let Some(cols) = columns {
5546 write!(f, " ({})", cols.join(", "))?;
5547 }
5548 }
5549 write!(f, " TO '{path}'")?;
5550 let mut parts: Vec<String> = Vec::new();
5551 if options.format == CopyFormat::Csv {
5552 parts.push("FORMAT csv".to_string());
5553 }
5554 if options.header {
5555 parts.push("HEADER true".to_string());
5556 }
5557 if let Some(d) = options.delimiter {
5558 parts.push(alloc::format!("DELIMITER '{d}'"));
5559 }
5560 if let Some(n) = &options.null_str {
5561 parts.push(alloc::format!("NULL '{n}'"));
5562 }
5563 if let Some(q) = options.quote {
5564 parts.push(alloc::format!("QUOTE '{q}'"));
5565 }
5566 if !parts.is_empty() {
5567 write!(f, " WITH ({})", parts.join(", "))?;
5568 }
5569 Ok(())
5570 }
5571 Self::AlterDomain { name, action } => {
5572 write!(f, "ALTER DOMAIN {name} ")?;
5573 match action {
5574 AlterDomainAction::AddConstraint { name: cn, check } => match cn {
5575 Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
5576 None => write!(f, "ADD CHECK ({check})"),
5577 },
5578 AlterDomainAction::DropConstraint {
5579 name: cn,
5580 if_exists,
5581 } => {
5582 if *if_exists {
5583 write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
5584 } else {
5585 write!(f, "DROP CONSTRAINT {cn}")
5586 }
5587 }
5588 AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
5589 AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
5590 AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
5591 AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
5592 AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
5593 }
5594 }
5595 Self::Truncate {
5596 tables,
5597 restart_identity,
5598 cascade,
5599 only,
5600 } => {
5601 f.write_str("TRUNCATE TABLE ")?;
5602 if *only {
5603 f.write_str("ONLY ")?;
5604 }
5605 for (i, t) in tables.iter().enumerate() {
5606 if i > 0 {
5607 f.write_str(", ")?;
5608 }
5609 f.write_str(t)?;
5610 }
5611 if *restart_identity {
5612 f.write_str(" RESTART IDENTITY")?;
5613 }
5614 if *cascade {
5615 f.write_str(" CASCADE")?;
5616 }
5617 Ok(())
5618 }
5619 Self::DropTable { names, if_exists } => {
5620 f.write_str("DROP TABLE ")?;
5621 if *if_exists {
5622 f.write_str("IF EXISTS ")?;
5623 }
5624 for (i, n) in names.iter().enumerate() {
5625 if i > 0 {
5626 f.write_str(", ")?;
5627 }
5628 write!(f, "{}", quote_ident(n))?;
5629 }
5630 Ok(())
5631 }
5632 Self::DropIndex { name, if_exists } => {
5633 f.write_str("DROP INDEX ")?;
5634 if *if_exists {
5635 f.write_str("IF EXISTS ")?;
5636 }
5637 write!(f, "{}", quote_ident(name))
5638 }
5639 Self::Select(s) => s.fmt(f),
5640 Self::CreateTable(s) => s.fmt(f),
5641 Self::CreateIndex(s) => s.fmt(f),
5642 Self::Insert(s) => s.fmt(f),
5643 Self::Update(s) => s.fmt(f),
5644 Self::Delete(s) => s.fmt(f),
5645 Self::Merge(s) => s.fmt(f),
5646 Self::Vacuum { table, analyze } => {
5647 f.write_str("VACUUM")?;
5648 if *analyze {
5649 f.write_str(" ANALYZE")?;
5650 }
5651 if let Some(t) = table {
5652 write!(f, " {}", quote_ident(t))?;
5653 }
5654 Ok(())
5655 }
5656 Self::Begin(None) => f.write_str("BEGIN"),
5657 Self::Begin(Some(level)) => write!(f, "BEGIN ISOLATION LEVEL {level}"),
5658 Self::Commit => f.write_str("COMMIT"),
5659 Self::Rollback => f.write_str("ROLLBACK"),
5660 Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
5661 Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
5662 Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
5663 Self::ShowTables => f.write_str("SHOW TABLES"),
5664 Self::ShowDatabases => f.write_str("SHOW DATABASES"),
5665 Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
5666 Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
5667 Self::ShowStatus => f.write_str("SHOW STATUS"),
5668 Self::ShowVariables => f.write_str("SHOW VARIABLES"),
5669 Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
5670 Self::Discard(t) => write!(f, "DISCARD {t}"),
5671 Self::Kill { query_only, id } => {
5672 if *query_only {
5673 write!(f, "KILL QUERY {id}")
5674 } else {
5675 write!(f, "KILL CONNECTION {id}")
5676 }
5677 }
5678 Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
5679 Self::CreateUser(s) => write!(
5680 f,
5681 "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
5682 quote_ident(&s.name),
5683 s.role
5684 ),
5685 Self::DropUser { name, if_exists } => {
5686 let ie = if *if_exists { "IF EXISTS " } else { "" };
5687 write!(f, "DROP USER {ie}{}", quote_ident(name))
5688 }
5689 Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
5690 Self::SetRole(None) => f.write_str("RESET ROLE"),
5691 Self::Grant(g) => write!(f, "{}", g.render(true)),
5692 Self::Revoke(g) => write!(f, "{}", g.render(false)),
5693 Self::CreatePolicy(s) => {
5694 write!(
5695 f,
5696 "CREATE POLICY {} ON {}",
5697 quote_ident(&s.name),
5698 quote_ident(&s.table)
5699 )?;
5700 if !s.permissive {
5701 f.write_str(" AS RESTRICTIVE")?;
5702 }
5703 if !matches!(s.cmd, PolicyCmd::All) {
5704 let w = match s.cmd {
5705 PolicyCmd::Select => "SELECT",
5706 PolicyCmd::Insert => "INSERT",
5707 PolicyCmd::Update => "UPDATE",
5708 PolicyCmd::Delete => "DELETE",
5709 PolicyCmd::All => unreachable!(),
5710 };
5711 write!(f, " FOR {w}")?;
5712 }
5713 if !s.roles.is_empty() {
5714 write!(f, " TO {}", s.roles.join(", "))?;
5715 }
5716 if let Some(u) = &s.using {
5717 write!(f, " USING ({u})")?;
5718 }
5719 if let Some(c) = &s.with_check {
5720 write!(f, " WITH CHECK ({c})")?;
5721 }
5722 Ok(())
5723 }
5724 Self::AlterPolicy(s) => {
5725 write!(
5726 f,
5727 "ALTER POLICY {} ON {}",
5728 quote_ident(&s.name),
5729 quote_ident(&s.table)
5730 )?;
5731 if let Some(nn) = &s.rename_to {
5732 return write!(f, " RENAME TO {}", quote_ident(nn));
5733 }
5734 if let Some(roles) = &s.roles {
5735 write!(f, " TO {}", roles.join(", "))?;
5736 }
5737 if let Some(u) = &s.using {
5738 write!(f, " USING ({u})")?;
5739 }
5740 if let Some(c) = &s.with_check {
5741 write!(f, " WITH CHECK ({c})")?;
5742 }
5743 Ok(())
5744 }
5745 Self::DropPolicy(s) => {
5746 f.write_str("DROP POLICY ")?;
5747 if s.if_exists {
5748 f.write_str("IF EXISTS ")?;
5749 }
5750 write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
5751 }
5752 Self::ShowUsers => f.write_str("SHOW USERS"),
5753 Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
5754 Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
5755 Self::CreateSubscription(s) => {
5756 write!(
5757 f,
5758 "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
5759 quote_ident(&s.name),
5760 s.conn_str.replace('\'', "''")
5761 )?;
5762 for (i, p) in s.publications.iter().enumerate() {
5763 if i > 0 {
5764 f.write_str(", ")?;
5765 }
5766 write!(f, "{}", quote_ident(p))?;
5767 }
5768 Ok(())
5769 }
5770 Self::DropSubscription { name, if_exists } => {
5771 let opt = if *if_exists { "IF EXISTS " } else { "" };
5772 write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
5773 }
5774 Self::WaitForWalPosition { pos, timeout_ms } => {
5775 write!(f, "WAIT FOR WAL POSITION {pos}")?;
5776 if let Some(ms) = timeout_ms {
5777 write!(f, " WITH TIMEOUT {ms}")?;
5778 }
5779 Ok(())
5780 }
5781 Self::Analyze(None) => f.write_str("ANALYZE"),
5782 Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
5783 Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
5784 Self::Explain(e) => {
5785 if e.suggest {
5786 write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
5787 } else if e.analyze {
5788 write!(f, "EXPLAIN ANALYZE {}", e.inner)
5789 } else {
5790 write!(f, "EXPLAIN {}", e.inner)
5791 }
5792 }
5793 Self::AlterIndex(a) => {
5794 write!(f, "ALTER INDEX ")?;
5795 match &a.target {
5796 // Parameters are consumed, not stored; the shortest
5797 // faithful spelling.
5798 AlterIndexTarget::StorageParams => {
5799 write!(f, "{} SET ()", quote_ident(&a.name))
5800 }
5801 AlterIndexTarget::Rebuild { encoding } => {
5802 write!(f, "{} REBUILD", quote_ident(&a.name))?;
5803 if let Some(enc) = encoding {
5804 write!(f, " WITH (encoding = {enc})")?;
5805 }
5806 Ok(())
5807 }
5808 AlterIndexTarget::Rename { new, if_exists } => {
5809 if *if_exists {
5810 f.write_str("IF EXISTS ")?;
5811 }
5812 write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
5813 }
5814 }
5815 }
5816 Self::AlterTable(a) => {
5817 write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
5818 for (i, t) in a.targets.iter().enumerate() {
5819 if i > 0 {
5820 f.write_str(", ")?;
5821 }
5822 fmt_alter_target(f, t)?;
5823 }
5824 Ok(())
5825 }
5826 Self::CreatePublication(p) => {
5827 write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
5828 match &p.scope {
5829 PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
5830 PublicationScope::ForTables(ts) => {
5831 f.write_str(" FOR TABLE ")?;
5832 for (i, t) in ts.iter().enumerate() {
5833 if i > 0 {
5834 f.write_str(", ")?;
5835 }
5836 write!(f, "{}", quote_ident(t))?;
5837 }
5838 Ok(())
5839 }
5840 PublicationScope::TablesInSchema(schema) => {
5841 write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
5842 Ok(())
5843 }
5844 PublicationScope::AllTablesExcept(ts) => {
5845 f.write_str(" FOR ALL TABLES EXCEPT ")?;
5846 for (i, t) in ts.iter().enumerate() {
5847 if i > 0 {
5848 f.write_str(", ")?;
5849 }
5850 write!(f, "{}", quote_ident(t))?;
5851 }
5852 Ok(())
5853 }
5854 }
5855 }
5856 Self::CreateExtension(name) => {
5857 write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
5858 }
5859 Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
5860 Self::DropPublication { name, if_exists } => {
5861 let opt = if *if_exists { "IF EXISTS " } else { "" };
5862 write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
5863 }
5864 Self::SetParameter { name, value, local } => {
5865 write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
5866 match value {
5867 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
5868 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
5869 SetValue::Default => f.write_str("DEFAULT"),
5870 }
5871 }
5872 Self::SetTransaction { isolation } => {
5873 write!(f, "SET TRANSACTION ISOLATION LEVEL ")?;
5874 let name = match isolation {
5875 IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
5876 IsolationLevel::ReadCommitted => "READ COMMITTED",
5877 IsolationLevel::RepeatableRead => "REPEATABLE READ",
5878 IsolationLevel::Serializable => "SERIALIZABLE",
5879 };
5880 f.write_str(name)
5881 }
5882 Self::ShowParameter(name) => write!(f, "SHOW {name}"),
5883 Self::SetUserVars(assigns, _) => {
5884 f.write_str("SET ")?;
5885 for (i, (name, value)) in assigns.iter().enumerate() {
5886 if i > 0 {
5887 f.write_str(", ")?;
5888 }
5889 write!(f, "@{name} = {value}")?;
5890 }
5891 Ok(())
5892 }
5893 Self::SetParameterList(pairs) => {
5894 f.write_str("SET ")?;
5895 for (i, (name, value)) in pairs.iter().enumerate() {
5896 if i > 0 {
5897 f.write_str(", ")?;
5898 }
5899 write!(f, "{name} = ")?;
5900 match value {
5901 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
5902 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
5903 SetValue::Default => f.write_str("DEFAULT")?,
5904 }
5905 }
5906 Ok(())
5907 }
5908 Self::ResetParameter(None) => f.write_str("RESET ALL"),
5909 Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
5910 Self::CreateFunction(s) => s.fmt(f),
5911 Self::CreateTrigger(s) => s.fmt(f),
5912 Self::DropTrigger {
5913 name,
5914 table,
5915 if_exists,
5916 } => {
5917 f.write_str("DROP TRIGGER ")?;
5918 if *if_exists {
5919 f.write_str("IF EXISTS ")?;
5920 }
5921 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
5922 }
5923 Self::DropFunction {
5924 name,
5925 args,
5926 if_exists,
5927 } => {
5928 f.write_str("DROP FUNCTION ")?;
5929 if *if_exists {
5930 f.write_str("IF EXISTS ")?;
5931 }
5932 write!(f, "{}", quote_ident(name))?;
5933 if let Some(a) = args {
5934 write!(f, "({})", a.join(", "))?;
5935 }
5936 Ok(())
5937 }
5938 Self::CreateSequence(s) => s.fmt(f),
5939 Self::AlterSequence(s) => s.fmt(f),
5940 Self::DropSequence { names, if_exists } => {
5941 f.write_str("DROP SEQUENCE ")?;
5942 if *if_exists {
5943 f.write_str("IF EXISTS ")?;
5944 }
5945 for (i, n) in names.iter().enumerate() {
5946 if i > 0 {
5947 f.write_str(", ")?;
5948 }
5949 write!(f, "{}", quote_ident(n))?;
5950 }
5951 Ok(())
5952 }
5953 Self::CreateView(v) => v.fmt(f),
5954 Self::DropView { names, if_exists } => {
5955 f.write_str("DROP VIEW ")?;
5956 if *if_exists {
5957 f.write_str("IF EXISTS ")?;
5958 }
5959 for (i, n) in names.iter().enumerate() {
5960 if i > 0 {
5961 f.write_str(", ")?;
5962 }
5963 write!(f, "{}", quote_ident(n))?;
5964 }
5965 Ok(())
5966 }
5967 Self::CreateMaterializedView(v) => v.fmt(f),
5968 Self::RefreshMaterializedView { name, with_data } => {
5969 write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
5970 if !*with_data {
5971 f.write_str(" WITH NO DATA")?;
5972 }
5973 Ok(())
5974 }
5975 Self::DropMaterializedView { names, if_exists } => {
5976 f.write_str("DROP MATERIALIZED VIEW ")?;
5977 if *if_exists {
5978 f.write_str("IF EXISTS ")?;
5979 }
5980 for (i, n) in names.iter().enumerate() {
5981 if i > 0 {
5982 f.write_str(", ")?;
5983 }
5984 write!(f, "{}", quote_ident(n))?;
5985 }
5986 Ok(())
5987 }
5988 Self::CreateType(t) => t.fmt(f),
5989 Self::CommentOn {
5990 kind,
5991 name,
5992 comment,
5993 } => {
5994 let body = match comment {
5995 Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
5996 None => "NULL".into(),
5997 };
5998 write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
5999 }
6000 Self::AlterTypeRenameValue {
6001 type_name,
6002 old,
6003 new,
6004 } => write!(
6005 f,
6006 "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
6007 quote_ident(type_name),
6008 old.replace('\'', "''"),
6009 new.replace('\'', "''")
6010 ),
6011 Self::AlterTypeAddValue {
6012 type_name,
6013 label,
6014 if_not_exists,
6015 position,
6016 } => {
6017 write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6018 if *if_not_exists {
6019 write!(f, "IF NOT EXISTS ")?;
6020 }
6021 write!(f, "'{label}'")?;
6022 if let Some((is_before, anchor)) = position {
6023 write!(
6024 f,
6025 " {} '{anchor}'",
6026 if *is_before { "BEFORE" } else { "AFTER" }
6027 )?;
6028 }
6029 Ok(())
6030 }
6031 Self::DropType { names, if_exists } => {
6032 f.write_str("DROP TYPE ")?;
6033 if *if_exists {
6034 f.write_str("IF EXISTS ")?;
6035 }
6036 for (i, n) in names.iter().enumerate() {
6037 if i > 0 {
6038 f.write_str(", ")?;
6039 }
6040 write!(f, "{}", quote_ident(n))?;
6041 }
6042 Ok(())
6043 }
6044 Self::CreateDomain(d) => d.fmt(f),
6045 Self::DropDomain { names, if_exists } => {
6046 f.write_str("DROP DOMAIN ")?;
6047 if *if_exists {
6048 f.write_str("IF EXISTS ")?;
6049 }
6050 for (i, n) in names.iter().enumerate() {
6051 if i > 0 {
6052 f.write_str(", ")?;
6053 }
6054 write!(f, "{}", quote_ident(n))?;
6055 }
6056 Ok(())
6057 }
6058 Self::CreateSchema {
6059 name,
6060 if_not_exists,
6061 } => {
6062 f.write_str("CREATE SCHEMA ")?;
6063 if *if_not_exists {
6064 f.write_str("IF NOT EXISTS ")?;
6065 }
6066 write!(f, "{}", quote_ident(name))
6067 }
6068 Self::DropSchema { names, if_exists } => {
6069 f.write_str("DROP SCHEMA ")?;
6070 if *if_exists {
6071 f.write_str("IF EXISTS ")?;
6072 }
6073 for (i, n) in names.iter().enumerate() {
6074 if i > 0 {
6075 f.write_str(", ")?;
6076 }
6077 write!(f, "{}", quote_ident(n))?;
6078 }
6079 Ok(())
6080 }
6081 Self::CreateRule(r) => {
6082 f.write_str("CREATE ")?;
6083 if r.or_replace {
6084 f.write_str("OR REPLACE ")?;
6085 }
6086 write!(
6087 f,
6088 "RULE {} AS ON {} TO {}",
6089 quote_ident(&r.name),
6090 r.event,
6091 quote_ident(&r.table)
6092 )?;
6093 if let Some(w) = &r.when_condition {
6094 write!(f, " WHERE {w}")?;
6095 }
6096 f.write_str(if r.instead {
6097 " DO INSTEAD "
6098 } else {
6099 " DO ALSO "
6100 })?;
6101 if r.commands.is_empty() {
6102 f.write_str("NOTHING")?;
6103 } else if r.commands.len() == 1 {
6104 write!(f, "{}", r.commands[0])?;
6105 } else {
6106 f.write_str("(")?;
6107 for (i, c) in r.commands.iter().enumerate() {
6108 if i > 0 {
6109 f.write_str("; ")?;
6110 }
6111 write!(f, "{c}")?;
6112 }
6113 f.write_str(")")?;
6114 }
6115 Ok(())
6116 }
6117 Self::DropRule {
6118 name,
6119 table,
6120 if_exists,
6121 } => {
6122 f.write_str("DROP RULE ")?;
6123 if *if_exists {
6124 f.write_str("IF EXISTS ")?;
6125 }
6126 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6127 }
6128 }
6129 }
6130}
6131
6132impl fmt::Display for CreateDomainStatement {
6133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6134 write!(
6135 f,
6136 "CREATE DOMAIN {} AS {}",
6137 quote_ident(&self.name),
6138 self.base_type
6139 )?;
6140 if let Some(d) = &self.default {
6141 write!(f, " DEFAULT {d}")?;
6142 }
6143 if self.not_null {
6144 f.write_str(" NOT NULL")?;
6145 }
6146 for c in &self.checks {
6147 write!(f, " CHECK ({c})")?;
6148 }
6149 Ok(())
6150 }
6151}
6152
6153impl fmt::Display for CreateTypeStatement {
6154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6155 write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6156 match &self.kind {
6157 TypeKind::Enum { labels } => {
6158 f.write_str("ENUM (")?;
6159 for (i, l) in labels.iter().enumerate() {
6160 if i > 0 {
6161 f.write_str(", ")?;
6162 }
6163 write!(f, "'{}'", l.replace('\'', "''"))?;
6164 }
6165 f.write_str(")")
6166 }
6167 TypeKind::Composite { fields, .. } => {
6168 f.write_str("(")?;
6169 for (i, (n, t)) in fields.iter().enumerate() {
6170 if i > 0 {
6171 f.write_str(", ")?;
6172 }
6173 write!(f, "{} {}", quote_ident(n), t)?;
6174 }
6175 f.write_str(")")
6176 }
6177 }
6178 }
6179}
6180
6181impl fmt::Display for CreateMaterializedViewStatement {
6182 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6183 f.write_str("CREATE MATERIALIZED VIEW ")?;
6184 if self.if_not_exists {
6185 f.write_str("IF NOT EXISTS ")?;
6186 }
6187 write!(f, "{}", quote_ident(&self.name))?;
6188 if !self.columns.is_empty() {
6189 f.write_str(" (")?;
6190 for (i, c) in self.columns.iter().enumerate() {
6191 if i > 0 {
6192 f.write_str(", ")?;
6193 }
6194 write!(f, "{}", quote_ident(c))?;
6195 }
6196 f.write_str(")")?;
6197 }
6198 write!(f, " AS {}", self.body)?;
6199 if !self.with_data {
6200 f.write_str(" WITH NO DATA")?;
6201 }
6202 Ok(())
6203 }
6204}
6205
6206impl fmt::Display for CreateViewStatement {
6207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6208 f.write_str("CREATE ")?;
6209 if self.or_replace {
6210 f.write_str("OR REPLACE ")?;
6211 }
6212 if self.temporary {
6213 f.write_str("TEMPORARY ")?;
6214 }
6215 f.write_str("VIEW ")?;
6216 if self.if_not_exists {
6217 f.write_str("IF NOT EXISTS ")?;
6218 }
6219 write!(f, "{}", quote_ident(&self.name))?;
6220 if !self.columns.is_empty() {
6221 f.write_str(" (")?;
6222 for (i, c) in self.columns.iter().enumerate() {
6223 if i > 0 {
6224 f.write_str(", ")?;
6225 }
6226 write!(f, "{}", quote_ident(c))?;
6227 }
6228 f.write_str(")")?;
6229 }
6230 write!(f, " AS {}", self.body)?;
6231 match self.check_option {
6232 Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6233 Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6234 None => Ok(()),
6235 }
6236 }
6237}
6238
6239impl fmt::Display for CreateSequenceStatement {
6240 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6241 f.write_str("CREATE ")?;
6242 if self.temporary {
6243 f.write_str("TEMPORARY ")?;
6244 }
6245 f.write_str("SEQUENCE ")?;
6246 if self.if_not_exists {
6247 f.write_str("IF NOT EXISTS ")?;
6248 }
6249 write!(f, "{}", quote_ident(&self.name))?;
6250 if let Some(dt) = self.data_type {
6251 write!(f, " AS {dt}")?;
6252 }
6253 write_sequence_options(f, &self.options)
6254 }
6255}
6256
6257impl fmt::Display for AlterSequenceStatement {
6258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6259 f.write_str("ALTER SEQUENCE ")?;
6260 if self.if_exists {
6261 f.write_str("IF EXISTS ")?;
6262 }
6263 write!(f, "{}", quote_ident(&self.name))?;
6264 write_sequence_options(f, &self.options)
6265 }
6266}
6267
6268impl fmt::Display for SequenceDataType {
6269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6270 f.write_str(match self {
6271 Self::SmallInt => "smallint",
6272 Self::Int => "integer",
6273 Self::BigInt => "bigint",
6274 })
6275 }
6276}
6277
6278fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6279 if let Some(n) = o.increment {
6280 write!(f, " INCREMENT BY {n}")?;
6281 }
6282 match o.min_value {
6283 Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6284 Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6285 None => {}
6286 }
6287 match o.max_value {
6288 Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6289 Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6290 None => {}
6291 }
6292 if let Some(n) = o.start {
6293 write!(f, " START WITH {n}")?;
6294 }
6295 match o.restart {
6296 Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6297 Some(None) => f.write_str(" RESTART")?,
6298 None => {}
6299 }
6300 if let Some(n) = o.cache {
6301 write!(f, " CACHE {n}")?;
6302 }
6303 match o.cycle {
6304 Some(true) => f.write_str(" CYCLE")?,
6305 Some(false) => f.write_str(" NO CYCLE")?,
6306 None => {}
6307 }
6308 if let Some(ob) = &o.owned_by {
6309 match ob {
6310 SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6311 SequenceOwnedBy::Column { table, column } => {
6312 write!(
6313 f,
6314 " OWNED BY {}.{}",
6315 quote_ident(table),
6316 quote_ident(column)
6317 )?;
6318 }
6319 }
6320 }
6321 Ok(())
6322}
6323
6324impl fmt::Display for CreateFunctionStatement {
6325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6326 f.write_str("CREATE ")?;
6327 if self.or_replace {
6328 f.write_str("OR REPLACE ")?;
6329 }
6330 write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6331 for (i, arg) in self.args.iter().enumerate() {
6332 if i > 0 {
6333 f.write_str(", ")?;
6334 }
6335 match arg.mode {
6336 FunctionArgMode::In => {}
6337 FunctionArgMode::Out => f.write_str("OUT ")?,
6338 FunctionArgMode::InOut => f.write_str("INOUT ")?,
6339 }
6340 if let Some(name) = &arg.name {
6341 write!(f, "{} ", quote_ident(name))?;
6342 }
6343 match &arg.ty {
6344 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6345 FunctionArgType::Raw(s) => f.write_str(s)?,
6346 }
6347 }
6348 f.write_str(") RETURNS ")?;
6349 match &self.returns {
6350 FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6351 FunctionReturn::Void => f.write_str("VOID")?,
6352 FunctionReturn::Type(t) => write!(f, "{t}")?,
6353 FunctionReturn::Other(s) => f.write_str(s)?,
6354 }
6355 write!(f, " LANGUAGE {} AS $$", self.language)?;
6356 match &self.body {
6357 FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6358 FunctionBody::Raw(s) => f.write_str(s)?,
6359 }
6360 f.write_str("$$")
6361 }
6362}
6363
6364impl fmt::Display for PlPgSqlBlock {
6365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6366 if !self.declarations.is_empty() {
6367 f.write_str("DECLARE\n")?;
6368 for d in &self.declarations {
6369 write!(f, " {} ", quote_ident(&d.name))?;
6370 match &d.ty {
6371 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6372 FunctionArgType::Raw(s) => f.write_str(s)?,
6373 }
6374 if let Some(e) = &d.default {
6375 write!(f, " := {e}")?;
6376 }
6377 f.write_str(";\n")?;
6378 }
6379 }
6380 f.write_str("BEGIN\n")?;
6381 for stmt in &self.statements {
6382 writeln!(f, " {stmt};")?;
6383 }
6384 // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6385 // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6386 // parsed block through it — so every exception handler a function
6387 // declared was thrown away AT STORE TIME. The block executed fine while
6388 // it was still an AST (a DO block never round-trips through text), which
6389 // is why only functions and triggers lost theirs.
6390 if !self.exception_handlers.is_empty() {
6391 f.write_str("EXCEPTION\n")?;
6392 for h in &self.exception_handlers {
6393 writeln!(f, " WHEN {} THEN", h.conditions.join(" OR "))?;
6394 for stmt in &h.body {
6395 writeln!(f, " {stmt};")?;
6396 }
6397 }
6398 }
6399 f.write_str("END")
6400 }
6401}
6402
6403impl fmt::Display for PlPgSqlStmt {
6404 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6405 match self {
6406 Self::Assign { target, value } => write!(f, "{target} := {value}"),
6407 Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6408 Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6409 Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6410 Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6411 Self::Return(t) => match t {
6412 ReturnTarget::New => f.write_str("RETURN NEW"),
6413 ReturnTarget::Old => f.write_str("RETURN OLD"),
6414 ReturnTarget::Null => f.write_str("RETURN NULL"),
6415 ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6416 },
6417 Self::If {
6418 branches,
6419 else_branch,
6420 } => {
6421 for (i, (cond, body)) in branches.iter().enumerate() {
6422 if i == 0 {
6423 write!(f, "IF {cond} THEN ")?;
6424 } else {
6425 write!(f, " ELSIF {cond} THEN ")?;
6426 }
6427 for (j, s) in body.iter().enumerate() {
6428 if j > 0 {
6429 f.write_str("; ")?;
6430 }
6431 write!(f, "{s}")?;
6432 }
6433 }
6434 if !else_branch.is_empty() {
6435 f.write_str(" ELSE ")?;
6436 for (j, s) in else_branch.iter().enumerate() {
6437 if j > 0 {
6438 f.write_str("; ")?;
6439 }
6440 write!(f, "{s}")?;
6441 }
6442 }
6443 f.write_str(" END IF")
6444 }
6445 Self::Raise {
6446 level,
6447 message,
6448 args,
6449 } => {
6450 let lvl = match level {
6451 RaiseLevel::Notice => "NOTICE",
6452 RaiseLevel::Warning => "WARNING",
6453 RaiseLevel::Info => "INFO",
6454 RaiseLevel::Log => "LOG",
6455 RaiseLevel::Debug => "DEBUG",
6456 RaiseLevel::Exception => "EXCEPTION",
6457 };
6458 write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6459 for a in args {
6460 write!(f, ", {a}")?;
6461 }
6462 Ok(())
6463 }
6464 Self::EmbeddedSql(s) => write!(f, "{s}"),
6465 Self::Assert { condition, message } => {
6466 write!(f, "ASSERT {condition}")?;
6467 if let Some(m) = message {
6468 write!(f, ", {m}")?;
6469 }
6470 Ok(())
6471 }
6472 Self::While { condition, body } => {
6473 writeln!(f, "WHILE {condition} LOOP")?;
6474 for s in body {
6475 writeln!(f, " {s};")?;
6476 }
6477 f.write_str("END LOOP")
6478 }
6479 Self::ForRange {
6480 var,
6481 start,
6482 end,
6483 reverse,
6484 body,
6485 } => {
6486 write!(f, "FOR {var} IN ")?;
6487 if *reverse {
6488 f.write_str("REVERSE ")?;
6489 }
6490 writeln!(f, "{start}..{end} LOOP")?;
6491 for s in body {
6492 writeln!(f, " {s};")?;
6493 }
6494 f.write_str("END LOOP")
6495 }
6496 Self::Loop { body } => {
6497 writeln!(f, "LOOP")?;
6498 for s in body {
6499 writeln!(f, " {s};")?;
6500 }
6501 f.write_str("END LOOP")
6502 }
6503 Self::Exit { when } => {
6504 f.write_str("EXIT")?;
6505 if let Some(c) = when {
6506 write!(f, " WHEN {c}")?;
6507 }
6508 Ok(())
6509 }
6510 Self::Continue { when } => {
6511 f.write_str("CONTINUE")?;
6512 if let Some(c) = when {
6513 write!(f, " WHEN {c}")?;
6514 }
6515 Ok(())
6516 }
6517 Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
6518 Self::ForQuery { var, query, body } => {
6519 writeln!(f, "FOR {var} IN ({query}) LOOP")?;
6520 for s in body {
6521 writeln!(f, " {s};")?;
6522 }
6523 f.write_str("END LOOP")
6524 }
6525 Self::ForExecute {
6526 var,
6527 sql_expr,
6528 body,
6529 } => {
6530 writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
6531 for s in body {
6532 writeln!(f, " {s};")?;
6533 }
6534 f.write_str("END LOOP")
6535 }
6536 }
6537 }
6538}
6539
6540impl fmt::Display for AssignTarget {
6541 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6542 match self {
6543 Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
6544 Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
6545 Self::Local(n) => f.write_str(n),
6546 }
6547 }
6548}
6549
6550impl fmt::Display for CreateTriggerStatement {
6551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6552 f.write_str("CREATE ")?;
6553 if self.or_replace {
6554 f.write_str("OR REPLACE ")?;
6555 }
6556 write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
6557 match self.timing {
6558 TriggerTiming::Before => f.write_str("BEFORE")?,
6559 TriggerTiming::After => f.write_str("AFTER")?,
6560 TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
6561 }
6562 for (i, e) in self.events.iter().enumerate() {
6563 if i == 0 {
6564 f.write_str(" ")?;
6565 } else {
6566 f.write_str(" OR ")?;
6567 }
6568 match e {
6569 TriggerEvent::Insert => f.write_str("INSERT")?,
6570 TriggerEvent::Update => {
6571 f.write_str("UPDATE")?;
6572 if !self.update_columns.is_empty() {
6573 f.write_str(" OF ")?;
6574 for (j, col) in self.update_columns.iter().enumerate() {
6575 if j > 0 {
6576 f.write_str(", ")?;
6577 }
6578 f.write_str("e_ident(col))?;
6579 }
6580 }
6581 }
6582 TriggerEvent::Delete => f.write_str("DELETE")?,
6583 TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
6584 }
6585 }
6586 write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
6587 match self.for_each {
6588 TriggerForEach::Row => f.write_str("ROW")?,
6589 TriggerForEach::Statement => f.write_str("STATEMENT")?,
6590 }
6591 write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
6592 }
6593}
6594
6595impl fmt::Display for CreateIndexStatement {
6596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6597 if self.is_unique {
6598 f.write_str("CREATE UNIQUE INDEX ")?;
6599 } else {
6600 f.write_str("CREATE INDEX ")?;
6601 }
6602 if self.if_not_exists {
6603 f.write_str("IF NOT EXISTS ")?;
6604 }
6605 write!(
6606 f,
6607 "{} ON {} ",
6608 quote_ident(&self.name),
6609 quote_ident(&self.table)
6610 )?;
6611 match self.method {
6612 IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
6613 IndexMethod::Brin => f.write_str("USING brin ")?,
6614 IndexMethod::Gin => f.write_str("USING gin ")?,
6615 IndexMethod::BTree => {}
6616 }
6617 if let Some(expr) = &self.expression {
6618 write!(f, "({})", expr)?;
6619 } else if self.extra_columns.is_empty() {
6620 // v7.15.0 — preserve operator class on round-trip
6621 // (`(col opclass)`) so WAL replay reconstructs the
6622 // engine-routing intent (e.g. `gin_trgm_ops` →
6623 // trigram-GIN build path).
6624 if let Some(op) = &self.opclass {
6625 write!(f, "({} {})", quote_ident(&self.column), op)?;
6626 } else {
6627 write!(f, "({})", quote_ident(&self.column))?;
6628 }
6629 } else {
6630 // v7.9.14 — multi-column key. Emit each column quoted
6631 // so the round-tripped form re-parses to identical AST.
6632 f.write_str("(")?;
6633 write!(f, "{}", quote_ident(&self.column))?;
6634 for c in &self.extra_columns {
6635 write!(f, ", {}", quote_ident(c))?;
6636 }
6637 f.write_str(")")?;
6638 }
6639 if !self.included_columns.is_empty() {
6640 f.write_str(" INCLUDE (")?;
6641 for (i, c) in self.included_columns.iter().enumerate() {
6642 if i > 0 {
6643 f.write_str(", ")?;
6644 }
6645 write!(f, "{}", quote_ident(c))?;
6646 }
6647 f.write_str(")")?;
6648 }
6649 if let Some(pred) = &self.partial_predicate {
6650 write!(f, " WHERE {}", pred)?;
6651 }
6652 Ok(())
6653 }
6654}
6655
6656impl fmt::Display for CreateTableStatement {
6657 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6658 f.write_str("CREATE TABLE ")?;
6659 if self.if_not_exists {
6660 f.write_str("IF NOT EXISTS ")?;
6661 }
6662 write!(f, "{}", quote_ident(&self.name))?;
6663 // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
6664 // no column list and no constraints; the table inherits its
6665 // columns from the parent at engine-DDL time.
6666 if let Some(spec) = &self.partition_of {
6667 write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
6668 return match &spec.bounds {
6669 PartitionOfBoundsAst::Range { lower, upper } => {
6670 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
6671 }
6672 PartitionOfBoundsAst::List { values } => {
6673 f.write_str("FOR VALUES IN (")?;
6674 for (i, v) in values.iter().enumerate() {
6675 if i > 0 {
6676 f.write_str(", ")?;
6677 }
6678 write!(f, "{}", v)?;
6679 }
6680 f.write_str(")")
6681 }
6682 PartitionOfBoundsAst::Hash { modulus, remainder } => {
6683 write!(
6684 f,
6685 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
6686 modulus, remainder
6687 )
6688 }
6689 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
6690 };
6691 }
6692 f.write_str(" (")?;
6693 for (i, col) in self.columns.iter().enumerate() {
6694 if i > 0 {
6695 f.write_str(", ")?;
6696 }
6697 write!(f, "{col}")?;
6698 }
6699 // v7.6.0 — render FK constraints in table-level form, after
6700 // the column list. WAL replay round-trips through Display, so
6701 // every FK must serialise here for replay to reconstruct the
6702 // schema bit-for-bit.
6703 for fk in &self.foreign_keys {
6704 f.write_str(", ")?;
6705 write!(f, "{fk}")?;
6706 }
6707 // v7.13.0 — render table-level constraints (PRIMARY KEY /
6708 // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
6709 // column-level UNIQUE / CHECK get lifted to this list at
6710 // parse time, so emitting only here avoids double-counting.
6711 for tc in &self.table_constraints {
6712 f.write_str(", ")?;
6713 write!(f, "{tc}")?;
6714 }
6715 f.write_str(")")?;
6716 // v7.37.6-B — partition-parent suffix renders after the
6717 // closing column-list paren, before the optional MySQL
6718 // table-options tail (which Display doesn't currently emit).
6719 if let Some(spec) = &self.partition_by {
6720 f.write_str(" PARTITION BY ")?;
6721 match spec.kind {
6722 PartitionKindAst::Range => f.write_str("RANGE ")?,
6723 PartitionKindAst::List => f.write_str("LIST ")?,
6724 PartitionKindAst::Hash => f.write_str("HASH ")?,
6725 }
6726 f.write_str("(")?;
6727 for (i, col) in spec.key_columns.iter().enumerate() {
6728 if i > 0 {
6729 f.write_str(", ")?;
6730 }
6731 f.write_str("e_ident(col))?;
6732 }
6733 f.write_str(")")?;
6734 }
6735 Ok(())
6736 }
6737}
6738
6739fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
6740 match t {
6741 AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
6742 AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
6743 write!(f, "REPLICA IDENTITY USING INDEX {index}")
6744 }
6745 AlterTableTarget::Inherit { parent, detach } => {
6746 if *detach {
6747 write!(f, "NO INHERIT {parent}")
6748 } else {
6749 write!(f, "INHERIT {parent}")
6750 }
6751 }
6752 AlterTableTarget::SetHotTierBytes(n) => {
6753 write!(f, "SET hot_tier_bytes = {n}")
6754 }
6755 AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
6756 AlterTableTarget::DropForeignKey { name, if_exists } => {
6757 f.write_str("DROP CONSTRAINT ")?;
6758 if *if_exists {
6759 f.write_str("IF EXISTS ")?;
6760 }
6761 write!(f, "{}", quote_ident(name))
6762 }
6763 AlterTableTarget::DropIndex { name, if_exists } => {
6764 f.write_str("DROP INDEX ")?;
6765 if *if_exists {
6766 f.write_str("IF EXISTS ")?;
6767 }
6768 write!(f, "{}", quote_ident(name))
6769 }
6770 AlterTableTarget::AddColumn {
6771 column,
6772 if_not_exists,
6773 } => {
6774 f.write_str("ADD COLUMN ")?;
6775 if *if_not_exists {
6776 f.write_str("IF NOT EXISTS ")?;
6777 }
6778 write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
6779 if !column.nullable {
6780 f.write_str(" NOT NULL")?;
6781 }
6782 if let Some(d) = &column.default {
6783 write!(f, " DEFAULT {d}")?;
6784 }
6785 if column.auto_increment {
6786 f.write_str(" AUTO_INCREMENT")?;
6787 }
6788 if column.is_primary_key {
6789 f.write_str(" PRIMARY KEY")?;
6790 }
6791 Ok(())
6792 }
6793 AlterTableTarget::AlterColumnType {
6794 column,
6795 new_type,
6796 using,
6797 collation,
6798 } => {
6799 write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
6800 if let Some((_, name)) = collation {
6801 write!(f, " COLLATE {}", quote_ident(name))?;
6802 }
6803 if let Some(u) = using {
6804 write!(f, " USING {u}")?;
6805 }
6806 Ok(())
6807 }
6808 AlterTableTarget::DropColumn {
6809 column,
6810 if_exists,
6811 cascade,
6812 } => {
6813 f.write_str("DROP COLUMN ")?;
6814 if *if_exists {
6815 f.write_str("IF EXISTS ")?;
6816 }
6817 write!(f, "{}", quote_ident(column))?;
6818 if *cascade {
6819 f.write_str(" CASCADE")?;
6820 }
6821 Ok(())
6822 }
6823 AlterTableTarget::AddTableConstraint(tc) => {
6824 write!(f, "ADD {tc}")
6825 }
6826 AlterTableTarget::ValidateConstraint { name } => {
6827 write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
6828 }
6829 AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
6830 AlterTableTarget::ClusterOn { index } => match index {
6831 Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
6832 None => f.write_str("SET WITHOUT CLUSTER"),
6833 },
6834 AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
6835 // Round-trip-safe spelling: re-parsing this form lowers
6836 // back to SetColumnAutoIncrement (the nextval default is
6837 // how pg_dump says "serial").
6838 let seq = seq_name
6839 .clone()
6840 .unwrap_or_else(|| alloc::format!("{column}_seq"));
6841 write!(
6842 f,
6843 "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
6844 quote_ident(column)
6845 )
6846 }
6847 AlterTableTarget::RenameColumn { old, new } => {
6848 write!(
6849 f,
6850 "RENAME COLUMN {} TO {}",
6851 quote_ident(old),
6852 quote_ident(new)
6853 )
6854 }
6855 AlterTableTarget::RenameConstraint { old, new } => {
6856 write!(
6857 f,
6858 "RENAME CONSTRAINT {} TO {}",
6859 quote_ident(old),
6860 quote_ident(new)
6861 )
6862 }
6863 AlterTableTarget::RenameTable { new } => {
6864 write!(f, "RENAME TO {}", quote_ident(new))
6865 }
6866 AlterTableTarget::SetTriggerEnabled { which, enabled } => {
6867 f.write_str(if *enabled {
6868 "ENABLE TRIGGER "
6869 } else {
6870 "DISABLE TRIGGER "
6871 })?;
6872 match which {
6873 TriggerSelector::All => f.write_str("ALL"),
6874 TriggerSelector::Named(n) => f.write_str("e_ident(n)),
6875 }
6876 }
6877 AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
6878 (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
6879 (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
6880 (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
6881 (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
6882 (None, None) => Ok(()),
6883 },
6884 AlterTableTarget::AttachPartition { child, bounds } => {
6885 write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
6886 match bounds {
6887 PartitionOfBoundsAst::Range { lower, upper } => {
6888 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
6889 }
6890 PartitionOfBoundsAst::List { values } => {
6891 f.write_str("FOR VALUES IN (")?;
6892 for (i, v) in values.iter().enumerate() {
6893 if i > 0 {
6894 f.write_str(", ")?;
6895 }
6896 write!(f, "{}", v)?;
6897 }
6898 f.write_str(")")
6899 }
6900 PartitionOfBoundsAst::Hash { modulus, remainder } => {
6901 write!(
6902 f,
6903 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
6904 modulus, remainder
6905 )
6906 }
6907 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
6908 }
6909 }
6910 AlterTableTarget::DetachPartition {
6911 child,
6912 concurrently,
6913 finalize,
6914 } => {
6915 write!(f, "DETACH PARTITION {}", quote_ident(child))?;
6916 if *concurrently {
6917 f.write_str(" CONCURRENTLY")?;
6918 }
6919 if *finalize {
6920 f.write_str(" FINALIZE")?;
6921 }
6922 Ok(())
6923 }
6924 AlterTableTarget::AlterColumnSetDefault {
6925 column,
6926 default_expr,
6927 } => write!(
6928 f,
6929 "ALTER COLUMN {} SET DEFAULT {}",
6930 quote_ident(column),
6931 default_expr
6932 ),
6933 AlterTableTarget::AlterColumnDropDefault { column } => {
6934 write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
6935 }
6936 AlterTableTarget::AlterColumnSetNotNull { column } => {
6937 write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
6938 }
6939 AlterTableTarget::AlterColumnDropNotNull { column } => {
6940 write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
6941 }
6942 AlterTableTarget::AlterColumnRestart { column, with } => {
6943 write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
6944 if let Some(n) = with {
6945 write!(f, " WITH {n}")?;
6946 }
6947 Ok(())
6948 }
6949 AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
6950 write!(
6951 f,
6952 "ALTER COLUMN {} DROP EXPRESSION{}",
6953 quote_ident(column),
6954 if *if_exists { " IF EXISTS" } else { "" }
6955 )
6956 }
6957 AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
6958 write!(
6959 f,
6960 "ALTER COLUMN {} DROP IDENTITY{}",
6961 quote_ident(column),
6962 if *if_exists { " IF EXISTS" } else { "" }
6963 )
6964 }
6965 AlterTableTarget::AlterColumnSetExpression { column, expr } => {
6966 write!(
6967 f,
6968 "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
6969 quote_ident(column)
6970 )
6971 }
6972 }
6973}
6974
6975impl fmt::Display for TableConstraint {
6976 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6977 match self {
6978 Self::PrimaryKey { name, columns, .. } => {
6979 if let Some(n) = name {
6980 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
6981 }
6982 f.write_str("PRIMARY KEY (")?;
6983 for (i, c) in columns.iter().enumerate() {
6984 if i > 0 {
6985 f.write_str(", ")?;
6986 }
6987 f.write_str("e_ident(c))?;
6988 }
6989 f.write_str(")")
6990 }
6991 Self::Unique {
6992 name,
6993 columns,
6994 nulls_not_distinct,
6995 ..
6996 } => {
6997 if let Some(n) = name {
6998 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
6999 }
7000 f.write_str("UNIQUE ")?;
7001 if *nulls_not_distinct {
7002 f.write_str("NULLS NOT DISTINCT ")?;
7003 }
7004 f.write_str("(")?;
7005 for (i, c) in columns.iter().enumerate() {
7006 if i > 0 {
7007 f.write_str(", ")?;
7008 }
7009 f.write_str("e_ident(c))?;
7010 }
7011 f.write_str(")")
7012 }
7013 Self::Check {
7014 name,
7015 expr,
7016 not_valid,
7017 } => {
7018 if let Some(n) = name {
7019 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7020 }
7021 write!(f, "CHECK ({expr})")?;
7022 if *not_valid {
7023 write!(f, " NOT VALID")?;
7024 }
7025 Ok(())
7026 }
7027 Self::Index { name, columns } => {
7028 f.write_str("KEY ")?;
7029 if let Some(n) = name {
7030 write!(f, "{} ", quote_ident(n))?;
7031 }
7032 f.write_str("(")?;
7033 for (i, c) in columns.iter().enumerate() {
7034 if i > 0 {
7035 f.write_str(", ")?;
7036 }
7037 f.write_str("e_ident(c))?;
7038 }
7039 f.write_str(")")
7040 }
7041 Self::FulltextIndex { name, columns } => {
7042 // Mysqldump emits `FULLTEXT KEY name (cols)` —
7043 // Display rounds back to that shape so dump
7044 // replay reproduces the input verbatim.
7045 f.write_str("FULLTEXT KEY ")?;
7046 if let Some(n) = name {
7047 write!(f, "{} ", quote_ident(n))?;
7048 }
7049 f.write_str("(")?;
7050 for (i, c) in columns.iter().enumerate() {
7051 if i > 0 {
7052 f.write_str(", ")?;
7053 }
7054 f.write_str("e_ident(c))?;
7055 }
7056 f.write_str(")")
7057 }
7058 Self::Exclude {
7059 name,
7060 method,
7061 elements,
7062 } => {
7063 if let Some(n) = name {
7064 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7065 }
7066 f.write_str("EXCLUDE ")?;
7067 if let Some(m) = method {
7068 write!(f, "USING {m} ")?;
7069 }
7070 f.write_str("(")?;
7071 for (i, (col, op)) in elements.iter().enumerate() {
7072 if i > 0 {
7073 f.write_str(", ")?;
7074 }
7075 write!(f, "{} WITH {op}", quote_ident(col))?;
7076 }
7077 f.write_str(")")
7078 }
7079 }
7080 }
7081}
7082
7083impl fmt::Display for ForeignKeyConstraint {
7084 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7085 if let Some(name) = &self.name {
7086 write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7087 }
7088 f.write_str("FOREIGN KEY (")?;
7089 for (i, c) in self.columns.iter().enumerate() {
7090 if i > 0 {
7091 f.write_str(", ")?;
7092 }
7093 f.write_str("e_ident(c))?;
7094 }
7095 write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7096 if !self.parent_columns.is_empty() {
7097 f.write_str(" (")?;
7098 for (i, c) in self.parent_columns.iter().enumerate() {
7099 if i > 0 {
7100 f.write_str(", ")?;
7101 }
7102 f.write_str("e_ident(c))?;
7103 }
7104 f.write_str(")")?;
7105 }
7106 // Only render non-default actions to keep Display output
7107 // close to user input. SPG's default is RESTRICT (matches
7108 // SQL spec).
7109 if self.on_delete != FkAction::Restrict {
7110 write!(f, " ON DELETE {}", self.on_delete)?;
7111 }
7112 if self.on_update != FkAction::Restrict {
7113 write!(f, " ON UPDATE {}", self.on_update)?;
7114 }
7115 Ok(())
7116 }
7117}
7118
7119impl fmt::Display for FkAction {
7120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7121 match self {
7122 Self::Restrict => f.write_str("RESTRICT"),
7123 Self::Cascade => f.write_str("CASCADE"),
7124 Self::SetNull => f.write_str("SET NULL"),
7125 Self::SetDefault => f.write_str("SET DEFAULT"),
7126 Self::NoAction => f.write_str("NO ACTION"),
7127 }
7128 }
7129}
7130
7131impl fmt::Display for ColumnDef {
7132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7133 // v7.30.1 (mailrs round-24 class audit) — the type position
7134 // must re-parse to the same ColumnDef: a user-defined type
7135 // reference and the MySQL inline ENUM / SET value lists all
7136 // lower `ty` to Text, so rendering `ty` lost them.
7137 write!(f, "{}", quote_ident(&self.name))?;
7138 if let Some(ut) = &self.user_type_ref {
7139 write!(f, " {}", quote_ident(ut))?;
7140 } else if let Some(variants) = &self.inline_enum_variants {
7141 write_variant_list(f, "ENUM", variants)?;
7142 } else if let Some(variants) = &self.inline_set_variants {
7143 write_variant_list(f, "SET", variants)?;
7144 } else {
7145 write!(f, " {}", self.ty)?;
7146 }
7147 if self.is_unsigned {
7148 f.write_str(" UNSIGNED")?;
7149 }
7150 // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7151 // DDL. Only emits when non-default so the typical output
7152 // stays unchanged.
7153 match self.collation {
7154 Collation::Binary => {}
7155 Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7156 }
7157 if let Some(d) = &self.default {
7158 write!(f, " DEFAULT {d}")?;
7159 }
7160 if self.auto_increment {
7161 f.write_str(" AUTO_INCREMENT")?;
7162 }
7163 if !self.nullable {
7164 f.write_str(" NOT NULL")?;
7165 }
7166 // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7167 // is NOT lifted to a table-level constraint at parse time
7168 // (unlike UNIQUE / CHECK), so the WAL round trip of a
7169 // prepared CREATE TABLE silently dropped the primary key.
7170 if self.is_primary_key {
7171 f.write_str(" PRIMARY KEY")?;
7172 }
7173 // The parser accepts only CURRENT_TIMESTAMP here (stored as
7174 // now()), so that spelling is the lossless round trip.
7175 if self.on_update_runtime.is_some() {
7176 f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7177 }
7178 // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7179 // replay reconstructs the computed-column declaration. The
7180 // expression sits inside a single set of parens; STORED is
7181 // the only variant the parser accepts.
7182 if let Some(gen_expr) = &self.generated_stored_expr {
7183 write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7184 }
7185 Ok(())
7186 }
7187}
7188
7189/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7190/// types (MySQL flavour; `ty` is Text underneath).
7191fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7192 write!(f, " {kw}(")?;
7193 for (i, v) in variants.iter().enumerate() {
7194 if i > 0 {
7195 f.write_str(", ")?;
7196 }
7197 write!(f, "'{}'", v.replace('\'', "''"))?;
7198 }
7199 f.write_str(")")
7200}
7201
7202impl fmt::Display for InsertStatement {
7203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7204 write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7205 if let Some(cols) = &self.columns {
7206 f.write_str(" (")?;
7207 for (i, c) in cols.iter().enumerate() {
7208 if i > 0 {
7209 f.write_str(", ")?;
7210 }
7211 f.write_str("e_ident(c))?;
7212 }
7213 f.write_str(")")?;
7214 }
7215 // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7216 // skipping the VALUES list (mailrs round-5 G4).
7217 if let Some(sel) = &self.select_source {
7218 write!(f, " {sel}")?;
7219 } else {
7220 f.write_str(" VALUES ")?;
7221 for (ri, row) in self.rows.iter().enumerate() {
7222 if ri > 0 {
7223 f.write_str(", ")?;
7224 }
7225 f.write_str("(")?;
7226 for (i, v) in row.iter().enumerate() {
7227 if i > 0 {
7228 f.write_str(", ")?;
7229 }
7230 write!(f, "{v}")?;
7231 }
7232 f.write_str(")")?;
7233 }
7234 }
7235 // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7236 // Display round trip: WAL persistence renders the bind-final
7237 // AST through this impl, and a replayed bare INSERT turns a
7238 // legal upsert no-op into a UNIQUE violation that refuses to
7239 // open the catalog.
7240 if let Some(oc) = &self.on_conflict {
7241 write!(f, " {oc}")?;
7242 }
7243 write_returning(self.returning.as_deref(), f)?;
7244 Ok(())
7245 }
7246}
7247
7248/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7249/// parser produced, so the AST→SQL round trip preserves upsert
7250/// semantics (WAL replay depends on it).
7251impl fmt::Display for OnConflictClause {
7252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7253 f.write_str("ON CONFLICT")?;
7254 if let Some(name) = &self.constraint_name {
7255 write!(f, " ON CONSTRAINT {name}")?;
7256 }
7257 if !self.target_columns.is_empty() {
7258 f.write_str(" (")?;
7259 for (i, c) in self.target_columns.iter().enumerate() {
7260 if i > 0 {
7261 f.write_str(", ")?;
7262 }
7263 f.write_str("e_ident(c))?;
7264 }
7265 f.write_str(")")?;
7266 }
7267 if let Some(w) = &self.index_where {
7268 write!(f, " WHERE {w}")?;
7269 }
7270 match &self.action {
7271 OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7272 OnConflictAction::Update {
7273 assignments,
7274 where_,
7275 } => {
7276 f.write_str(" DO UPDATE SET ")?;
7277 for (i, (col, expr)) in assignments.iter().enumerate() {
7278 if i > 0 {
7279 f.write_str(", ")?;
7280 }
7281 write!(f, "{} = {expr}", quote_ident(col))?;
7282 }
7283 if let Some(w) = where_ {
7284 write!(f, " WHERE {w}")?;
7285 }
7286 Ok(())
7287 }
7288 }
7289 }
7290}
7291
7292/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7293/// tail for the three DML Display impls.
7294fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7295 let Some(items) = ret else {
7296 return Ok(());
7297 };
7298 f.write_str(" RETURNING ")?;
7299 for (i, item) in items.iter().enumerate() {
7300 if i > 0 {
7301 f.write_str(", ")?;
7302 }
7303 write!(f, "{item}")?;
7304 }
7305 Ok(())
7306}
7307
7308impl fmt::Display for UpdateStatement {
7309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7310 write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7311 for (i, (col, expr)) in self.assignments.iter().enumerate() {
7312 if i > 0 {
7313 f.write_str(", ")?;
7314 }
7315 write!(f, "{} = {expr}", quote_ident(col))?;
7316 }
7317 if let Some(w) = &self.where_ {
7318 write!(f, " WHERE {w}")?;
7319 }
7320 // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7321 if let Some(ol) = self.order_limit.as_deref() {
7322 if !ol.order_by.is_empty() {
7323 f.write_str(" ORDER BY ")?;
7324 for (i, o) in ol.order_by.iter().enumerate() {
7325 if i > 0 {
7326 f.write_str(", ")?;
7327 }
7328 write!(f, "{}", o.expr)?;
7329 if o.desc {
7330 f.write_str(" DESC")?;
7331 }
7332 match o.nulls_first {
7333 Some(true) => f.write_str(" NULLS FIRST")?,
7334 Some(false) => f.write_str(" NULLS LAST")?,
7335 None => {}
7336 }
7337 }
7338 }
7339 if let Some(n) = ol.limit {
7340 write!(f, " LIMIT {n}")?;
7341 }
7342 }
7343 write_returning(self.returning.as_deref(), f)?;
7344 Ok(())
7345 }
7346}
7347
7348impl fmt::Display for DeleteStatement {
7349 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7350 write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7351 if let Some(w) = &self.where_ {
7352 write!(f, " WHERE {w}")?;
7353 }
7354 write_returning(self.returning.as_deref(), f)?;
7355 Ok(())
7356 }
7357}
7358
7359impl fmt::Display for CteBody {
7360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7361 match self {
7362 Self::Select(s) => write!(f, "{s}"),
7363 Self::Insert(s) => write!(f, "{s}"),
7364 Self::Update(s) => write!(f, "{s}"),
7365 Self::Delete(s) => write!(f, "{s}"),
7366 Self::Merge(s) => write!(f, "{s}"),
7367 }
7368 }
7369}
7370
7371impl fmt::Display for MergeStatement {
7372 // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7373 // (it round-trips for the cases tests cover, not for
7374 // round-tripping every edge of the surface).
7375 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7376 fmt_with_clause(&self.ctes, f)?;
7377 f.write_str("MERGE INTO ")?;
7378 write!(f, "{}", quote_ident(&self.target))?;
7379 if let Some(a) = &self.target_alias {
7380 write!(f, " {}", quote_ident(a))?;
7381 }
7382 f.write_str(" USING ")?;
7383 if let Some(sub) = &self.source_select {
7384 write!(f, "({sub})")?;
7385 } else {
7386 write!(f, "{}", quote_ident(&self.source))?;
7387 }
7388 if let Some(a) = &self.source_alias {
7389 write!(f, " {}", quote_ident(a))?;
7390 }
7391 if !self.source_column_aliases.is_empty() {
7392 f.write_str("(")?;
7393 for (i, c) in self.source_column_aliases.iter().enumerate() {
7394 if i > 0 {
7395 f.write_str(", ")?;
7396 }
7397 write!(f, "{}", quote_ident(c))?;
7398 }
7399 f.write_str(")")?;
7400 }
7401 write!(f, " ON {}", self.on)?;
7402 for clause in &self.clauses {
7403 f.write_str(" WHEN ")?;
7404 f.write_str(match clause.matched {
7405 MergeMatched::Matched => "MATCHED",
7406 MergeMatched::NotMatched => "NOT MATCHED",
7407 MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7408 })?;
7409 if let Some(c) = &clause.condition {
7410 write!(f, " AND {c}")?;
7411 }
7412 f.write_str(" THEN ")?;
7413 match &clause.action {
7414 MergeAction::Insert { columns, values } => {
7415 f.write_str("INSERT ")?;
7416 // A column list is optional (round 146): the bare
7417 // `INSERT VALUES (…)` form maps positionally.
7418 if !columns.is_empty() {
7419 f.write_str("(")?;
7420 for (i, c) in columns.iter().enumerate() {
7421 if i > 0 {
7422 f.write_str(", ")?;
7423 }
7424 write!(f, "{}", quote_ident(c))?;
7425 }
7426 f.write_str(") ")?;
7427 }
7428 f.write_str("VALUES (")?;
7429 for (i, v) in values.iter().enumerate() {
7430 if i > 0 {
7431 f.write_str(", ")?;
7432 }
7433 write!(f, "{v}")?;
7434 }
7435 f.write_str(")")?;
7436 }
7437 MergeAction::Update { assignments } => {
7438 f.write_str("UPDATE SET ")?;
7439 for (i, (c, e)) in assignments.iter().enumerate() {
7440 if i > 0 {
7441 f.write_str(", ")?;
7442 }
7443 write!(f, "{} = {e}", quote_ident(c))?;
7444 }
7445 }
7446 MergeAction::Delete => f.write_str("DELETE")?,
7447 MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7448 }
7449 }
7450 if let Some(items) = &self.returning {
7451 f.write_str(" RETURNING ")?;
7452 for (i, it) in items.iter().enumerate() {
7453 if i > 0 {
7454 f.write_str(", ")?;
7455 }
7456 write!(f, "{it}")?;
7457 }
7458 }
7459 Ok(())
7460 }
7461}
7462
7463/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
7464/// carry a CTE list and must round-trip it identically.
7465fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
7466 if ctes.is_empty() {
7467 return Ok(());
7468 }
7469 f.write_str("WITH ")?;
7470 if ctes.iter().any(|c| c.recursive) {
7471 f.write_str("RECURSIVE ")?;
7472 }
7473 for (i, cte) in ctes.iter().enumerate() {
7474 if i > 0 {
7475 f.write_str(", ")?;
7476 }
7477 f.write_str("e_ident(&cte.name))?;
7478 if !cte.column_overrides.is_empty() {
7479 f.write_str(" (")?;
7480 for (ci, c) in cte.column_overrides.iter().enumerate() {
7481 if ci > 0 {
7482 f.write_str(", ")?;
7483 }
7484 f.write_str("e_ident(c))?;
7485 }
7486 f.write_str(")")?;
7487 }
7488 write!(f, " AS ({})", cte.body)?;
7489 }
7490 f.write_str(" ")
7491}
7492
7493impl fmt::Display for SelectStatement {
7494 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7495 // v7.30.1 (mailrs round-24 class audit) — the WITH clause
7496 // must survive the round trip; a CTE-using statement
7497 // re-parsed without it references undefined tables.
7498 fmt_with_clause(&self.ctes, f)?;
7499 write_bare_select(self, f)?;
7500 for (kind, peer) in &self.unions {
7501 f.write_str(match kind {
7502 UnionKind::Distinct => " UNION ",
7503 UnionKind::All => " UNION ALL ",
7504 UnionKind::Intersect => " INTERSECT ",
7505 UnionKind::IntersectAll => " INTERSECT ALL ",
7506 UnionKind::Except => " EXCEPT ",
7507 UnionKind::ExceptAll => " EXCEPT ALL ",
7508 })?;
7509 write_bare_select(peer, f)?;
7510 }
7511 if !self.order_by.is_empty() {
7512 f.write_str(" ORDER BY ")?;
7513 for (i, o) in self.order_by.iter().enumerate() {
7514 if i > 0 {
7515 f.write_str(", ")?;
7516 }
7517 write!(f, "{}", o.expr)?;
7518 if o.desc {
7519 f.write_str(" DESC")?;
7520 }
7521 match o.nulls_first {
7522 Some(true) => f.write_str(" NULLS FIRST")?,
7523 Some(false) => f.write_str(" NULLS LAST")?,
7524 None => {}
7525 }
7526 }
7527 }
7528 // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
7529 // exists in the FETCH FIRST spelling; rendering it as LIMIT
7530 // dropped the tie-extension semantics on replay. The parser
7531 // accepts OFFSET before FETCH, so keep that order here.
7532 if self.limit_with_ties {
7533 if let Some(o) = &self.offset {
7534 write!(f, " OFFSET {o}")?;
7535 }
7536 if let Some(n) = &self.limit {
7537 write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
7538 }
7539 } else {
7540 if let Some(n) = &self.limit {
7541 write!(f, " LIMIT {n}")?;
7542 }
7543 if let Some(o) = &self.offset {
7544 write!(f, " OFFSET {o}")?;
7545 }
7546 }
7547 Ok(())
7548 }
7549}
7550
7551fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7552 f.write_str("SELECT ")?;
7553 if s.distinct {
7554 f.write_str("DISTINCT ")?;
7555 }
7556 write_bare_select_body(s, f)
7557}
7558
7559fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7560 for (i, item) in s.items.iter().enumerate() {
7561 if i > 0 {
7562 f.write_str(", ")?;
7563 }
7564 write!(f, "{item}")?;
7565 }
7566 if let Some(t) = &s.from {
7567 write!(f, " FROM {t}")?;
7568 }
7569 if let Some(e) = &s.where_ {
7570 write!(f, " WHERE {e}")?;
7571 }
7572 if let Some(gs) = &s.group_by {
7573 f.write_str(" GROUP BY ")?;
7574 for (i, g) in gs.iter().enumerate() {
7575 if i > 0 {
7576 f.write_str(", ")?;
7577 }
7578 write!(f, "{g}")?;
7579 }
7580 } else if s.group_by_all {
7581 // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
7582 // shortcut parses to group_by: None + this flag; dropping
7583 // it turned an aggregate query into a bare projection on
7584 // re-parse.
7585 f.write_str(" GROUP BY ALL")?;
7586 }
7587 if let Some(h) = &s.having {
7588 write!(f, " HAVING {h}")?;
7589 }
7590 Ok(())
7591}
7592
7593impl fmt::Display for SelectItem {
7594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7595 match self {
7596 Self::Wildcard => f.write_str("*"),
7597 Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
7598 Self::Expr { expr, alias } => {
7599 write!(f, "{expr}")?;
7600 if let Some(a) = alias {
7601 write!(f, " AS {}", quote_ident(a))?;
7602 }
7603 Ok(())
7604 }
7605 }
7606 }
7607}
7608
7609impl fmt::Display for FromClause {
7610 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7611 write!(f, "{}", self.primary)?;
7612 for j in &self.joins {
7613 match j.kind {
7614 JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
7615 JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
7616 JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
7617 JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
7618 JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
7619 JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
7620 }
7621 if let Some(on) = &j.on {
7622 write!(f, " ON {on}")?;
7623 }
7624 }
7625 Ok(())
7626 }
7627}
7628
7629/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
7630/// for NESTED). Kept close to the parser's grammar so it re-parses.
7631fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
7632 for (i, c) in cols.iter().enumerate() {
7633 if i > 0 {
7634 f.write_str(", ")?;
7635 }
7636 match c {
7637 JsonTableColumn::Ordinality { name } => {
7638 write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
7639 }
7640 JsonTableColumn::Nested { path, columns } => {
7641 write!(f, "NESTED PATH '{path}' COLUMNS (")?;
7642 fmt_json_table_columns(f, columns)?;
7643 f.write_str(")")?;
7644 }
7645 JsonTableColumn::Regular {
7646 name,
7647 ty,
7648 path,
7649 exists,
7650 format_json,
7651 wrapper,
7652 on_empty,
7653 on_error,
7654 } => {
7655 write!(f, "{} {ty}", quote_ident(name))?;
7656 if *format_json {
7657 f.write_str(" FORMAT JSON")?;
7658 }
7659 if *exists {
7660 write!(f, " EXISTS PATH '{path}'")?;
7661 } else {
7662 write!(f, " PATH '{path}'")?;
7663 }
7664 if *wrapper {
7665 f.write_str(" WITH WRAPPER")?;
7666 }
7667 if let JsonTableOnBehavior::Error = on_empty {
7668 f.write_str(" ERROR ON EMPTY")?;
7669 } else if let JsonTableOnBehavior::Default(e) = on_empty {
7670 write!(f, " DEFAULT {e} ON EMPTY")?;
7671 }
7672 if let JsonTableOnBehavior::Error = on_error {
7673 f.write_str(" ERROR ON ERROR")?;
7674 } else if let JsonTableOnBehavior::Default(e) = on_error {
7675 write!(f, " DEFAULT {e} ON ERROR")?;
7676 }
7677 }
7678 }
7679 }
7680 Ok(())
7681}
7682
7683impl fmt::Display for TableRef {
7684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7685 // v7.30.1 (mailrs round-24 class audit) — the dynamic
7686 // table-ref shapes must round-trip: rendering only the
7687 // (synthetic) name turned LATERAL / unnest() /
7688 // generate_series() into references to nonexistent tables
7689 // on re-parse.
7690 // v7.39 (round 205) — JSON_TABLE round-trips through Display
7691 // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
7692 if let Some(jt) = &self.json_table {
7693 write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
7694 if !jt.passing.is_empty() {
7695 f.write_str(" PASSING ")?;
7696 for (i, (n, e)) in jt.passing.iter().enumerate() {
7697 if i > 0 {
7698 f.write_str(", ")?;
7699 }
7700 write!(f, "{e} AS {}", quote_ident(n))?;
7701 }
7702 }
7703 f.write_str(" COLUMNS (")?;
7704 fmt_json_table_columns(f, &jt.columns)?;
7705 f.write_str(")")?;
7706 if let Some(a) = &self.alias {
7707 write!(f, " AS {}", quote_ident(a))?;
7708 }
7709 return Ok(());
7710 }
7711 if let Some(inner) = &self.lateral_subquery {
7712 write!(f, "LATERAL ({inner})")?;
7713 if let Some(a) = &self.alias {
7714 write!(f, " AS {}", quote_ident(a))?;
7715 // v7.37 D.28 — a derived table on the lateral_subquery channel
7716 // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
7717 // lowers here). Rendering the alias without the column list lost
7718 // the column names on re-parse (a view body round-trips through
7719 // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
7720 if !self.unnest_column_aliases.is_empty() {
7721 f.write_str(" (")?;
7722 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
7723 if i > 0 {
7724 f.write_str(", ")?;
7725 }
7726 f.write_str("e_ident(c))?;
7727 }
7728 f.write_str(")")?;
7729 }
7730 }
7731 return Ok(());
7732 }
7733 if let Some(expr) = &self.unnest_expr {
7734 write!(f, "UNNEST({expr})")?;
7735 if let Some(a) = &self.alias {
7736 write!(f, " AS {}", quote_ident(a))?;
7737 if !self.unnest_column_aliases.is_empty() {
7738 f.write_str(" (")?;
7739 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
7740 if i > 0 {
7741 f.write_str(", ")?;
7742 }
7743 f.write_str("e_ident(c))?;
7744 }
7745 f.write_str(")")?;
7746 }
7747 }
7748 return Ok(());
7749 }
7750 if let Some(args) = &self.generate_series_args {
7751 f.write_str("generate_series(")?;
7752 for (i, a) in args.iter().enumerate() {
7753 if i > 0 {
7754 f.write_str(", ")?;
7755 }
7756 write!(f, "{a}")?;
7757 }
7758 f.write_str(")")?;
7759 if let Some(a) = &self.alias {
7760 write!(f, " AS {}", quote_ident(a))?;
7761 }
7762 return Ok(());
7763 }
7764 write!(f, "{}", quote_ident(&self.name))?;
7765 if let Some(seg) = self.as_of_segment {
7766 write!(f, " AS OF SEGMENT {seg}")?;
7767 }
7768 if let Some(a) = &self.alias {
7769 write!(f, " AS {}", quote_ident(a))?;
7770 }
7771 Ok(())
7772 }
7773}
7774
7775impl fmt::Display for ColumnName {
7776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7777 if let Some(q) = &self.qualifier {
7778 write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
7779 } else {
7780 write!(f, "{}", quote_ident(&self.name))
7781 }
7782 }
7783}
7784
7785/// v7.39 (round 311) — render the left spine of an AND / OR chain
7786/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
7787/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
7788/// SAME operator flattens; anything else is an ordinary operand.
7789fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
7790 if let Expr::Binary {
7791 lhs,
7792 op: inner,
7793 rhs,
7794 } = e
7795 && *inner == op
7796 {
7797 write_bool_chain(f, lhs, op)?;
7798 return write!(f, " {op} {rhs}");
7799 }
7800 write!(f, "{e}")
7801}
7802
7803/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
7804/// form `pg_get_constraintdef(oid, true)` and friends return.
7805///
7806/// The default [`fmt::Display`] parenthesises every operator node, which
7807/// is what PG's non-pretty deparse does and what makes the text
7808/// round-trip. Pretty drops the pairs the grammar can put back, and the
7809/// rule is NOT plain precedence minimisation — measured against PG 18.4
7810/// across 37 shapes:
7811///
7812/// * the boolean layer follows precedence (NOT > AND > OR): an OR
7813/// under an AND keeps its parens, an AND under an OR does not, and a
7814/// comparison under any of them does not (`NOT a > 1`);
7815/// * an associative chain flattens completely, even where the source
7816/// nested it to the right (`a AND (b AND c)` prints as one chain);
7817/// * but an operand of a comparison or arithmetic operator keeps its
7818/// parens whenever it is itself an operator expression — so
7819/// `(a + b) > 10` and `(- a) + b`, even though precedence alone
7820/// would not require either. A cast, function call, column or
7821/// literal in that position does not (`a::text = t`,
7822/// `length(code) > 2`); a cast counts as compound exactly when the
7823/// thing it casts is (`((a + b)::text) = t`).
7824///
7825/// Anything outside that layer defers to `Display`, which is never
7826/// wrong — only more parenthesised than PG would print.
7827#[must_use]
7828pub fn pretty_expr(e: &Expr) -> String {
7829 let mut out = String::new();
7830 write_pretty(&mut out, e, PrettyParent::None, false, false);
7831 out
7832}
7833
7834/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
7835/// writes it.
7836///
7837/// MariaDB names the offending expression in its out-of-range message
7838/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
7839/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
7840/// MySQL client, for a cast the client had just written the other way.
7841#[must_use]
7842pub fn pretty_expr_mysql(e: &Expr) -> String {
7843 let mut out = String::new();
7844 write_pretty(&mut out, e, PrettyParent::None, false, true);
7845 out
7846}
7847
7848/// v7.39 (round 505) — how strongly an expression suggests its own column
7849/// name. A cast keeps its argument's name only when that name is STRONG;
7850/// otherwise the cast reports the type it casts to.
7851///
7852/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
7853/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
7854/// itself `text` — so `case` and a function name cannot be the same kind of
7855/// answer, even though a bare `CASE …` does report `case`.
7856#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
7857enum NameStrength {
7858 /// Nothing to go on — PG reports `?column?`.
7859 None,
7860 /// A name, but one a cast overrides: `case`, or a type name.
7861 Weak,
7862 /// A name a cast keeps: a column, or the function that produced it.
7863 Strong,
7864}
7865
7866/// v7.39 (round 505) — the column name PG18 gives a projected expression
7867/// that carries no `AS` alias. `None` means `?column?`.
7868///
7869/// SPG used to print the parsed expression back out, which matched neither
7870/// oracle and made name-keyed row access miss on both wires:
7871///
7872/// | query | PG18 | SPG (before) |
7873/// |--------------|------------|--------------|
7874/// | `upper(s)` | `upper` | `upper(s)` |
7875/// | `a+b` | `?column?` | `(a + b)` |
7876/// | `'lit'` | `?column?` | `'lit'` |
7877/// | `CASE …` | `case` | `CASE WHEN (a = 1) THEN …` |
7878///
7879/// Every rule below is one of those measurements, taken with `\gdesc`
7880/// against PG18: a call is named for its function, a cast recurses into its
7881/// argument and falls back to the type, a scalar subquery takes the name of
7882/// the column it selects, and operators have no name at all.
7883#[must_use]
7884pub fn figure_column_name(expr: &Expr) -> Option<String> {
7885 let (name, _) = figure_name_inner(expr);
7886 name
7887}
7888
7889/// The name a function reports, which is not always the name SPG parsed it
7890/// under: `count(*)` is held as `count_star` so the star arity survives the
7891/// AST, and that internal spelling must not reach a client. PG18 reports
7892/// `count`.
7893fn canonical_function_name(name: &str) -> String {
7894 match name {
7895 "count_star" => "count".to_string(),
7896 other => other.to_ascii_lowercase(),
7897 }
7898}
7899
7900fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
7901 let strong = |n: String| (Some(n), NameStrength::Strong);
7902 match expr {
7903 // A column keeps its own name, qualifier and all discarded:
7904 // `lbl.a` reports `a`.
7905 Expr::Column(c) => strong(c.name.clone()),
7906 // Calls are named for the function. This covers the shapes that
7907 // only LOOK like syntax — `EXTRACT(year FROM …)` reports
7908 // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
7909 // because PG resolves them to functions before naming them.
7910 Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
7911 strong(canonical_function_name(name))
7912 }
7913 Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
7914 Expr::Extract { .. } => strong("extract".to_string()),
7915 Expr::Exists { .. } => strong("exists".to_string()),
7916 Expr::Array(_) => strong("array".to_string()),
7917 // `(expr).field` is named for the field, as a column would be.
7918 Expr::FieldAccess { field, .. } => strong(field.clone()),
7919 // A cast prefers its argument's name and settles for the type:
7920 // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
7921 Expr::Cast {
7922 expr: inner,
7923 target,
7924 } => match figure_name_inner(inner) {
7925 (Some(n), NameStrength::Strong) => strong(n),
7926 _ => (Some(target.to_string()), NameStrength::Weak),
7927 },
7928 // A scalar subquery reports whatever its single output column
7929 // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
7930 Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
7931 // `CASE …` names itself, but weakly — a cast around it wins.
7932 Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
7933 // A literal that carries its own type names itself for that type:
7934 // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
7935 // reports nothing. Weak, like any other type name.
7936 Expr::Literal(Literal::Interval { .. }) => {
7937 (Some("interval".to_string()), NameStrength::Weak)
7938 }
7939 // A wrapper that adds no name of its own.
7940 Expr::Variadic(inner) => figure_name_inner(inner),
7941 Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
7942 // Everything else — operators, comparisons, IS NULL, LIKE, IN,
7943 // literals, placeholders — reports `?column?`.
7944 _ => (None, NameStrength::None),
7945 }
7946}
7947
7948/// The name a scalar subquery's single projected column reports.
7949fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
7950 match sel.items.as_slice() {
7951 [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
7952 [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
7953 _ => (None, NameStrength::None),
7954 }
7955}
7956
7957/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
7958fn pretty_prec(e: &Expr) -> u8 {
7959 match e {
7960 Expr::Binary { op, .. } => match op {
7961 // v7.39 (round 407) — this deparse ladder mirrors the parser's:
7962 // OR < XOR < AND < NOT < comparison < additive < multiplicative.
7963 // XOR (MySQL-only) sits between OR and AND, so AND and everything
7964 // above shifted +1 to open rung 2 for it.
7965 BinOp::Or => 1,
7966 BinOp::LogicalXor => 2,
7967 BinOp::And => 3,
7968 BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
7969 BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
7970 // Everything else in this enum is a comparison-shaped
7971 // operator; they share one level, as in the grammar.
7972 _ => 5,
7973 },
7974 Expr::Unary { op, .. } => match op {
7975 UnOp::Not => 4,
7976 UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
7977 },
7978 _ => u8::MAX,
7979 }
7980}
7981
7982/// Is this node an operator expression — the thing an arithmetic or
7983/// comparison parent keeps parentheses around? A cast inherits the
7984/// answer from what it casts.
7985fn pretty_is_compound(e: &Expr) -> bool {
7986 match e {
7987 Expr::Binary { .. } | Expr::Unary { .. } => true,
7988 Expr::Cast { expr, .. } => pretty_is_compound(expr),
7989 _ => false,
7990 }
7991}
7992
7993/// `parent` describes the enclosing operator: its binding power, and
7994/// whether it is a comparison (which keeps parens around any operator
7995/// operand) or a NOT (which keeps them at equal power too).
7996#[derive(Clone, Copy, PartialEq)]
7997enum PrettyParent {
7998 /// Nothing encloses this node.
7999 None,
8000 /// A comparison-shaped operator: an operator operand always keeps
8001 /// its parens, whatever precedence would allow.
8002 Comparison,
8003 /// Arithmetic / concatenation: precedence decides.
8004 Arith(u8),
8005 /// A boolean connective: precedence decides.
8006 Bool(u8),
8007 /// `NOT`: precedence decides, but equal power still needs parens so
8008 /// `NOT (NOT a > 1)` does not collapse.
8009 Not,
8010}
8011
8012fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8013 let prec = pretty_prec(e);
8014 let is_unary_sign = matches!(
8015 e,
8016 Expr::Unary {
8017 op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8018 ..
8019 }
8020 );
8021 let needs = match parent {
8022 PrettyParent::None => false,
8023 PrettyParent::Comparison => pretty_is_compound(e),
8024 // A sign always keeps its parens under an operator — PG writes
8025 // `(- a) + b` even though precedence would not require it.
8026 PrettyParent::Arith(p) => {
8027 is_unary_sign
8028 || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8029 && (prec < p || (prec == p && is_rhs)))
8030 }
8031 PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8032 PrettyParent::Not => {
8033 matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8034 }
8035 };
8036 if needs {
8037 out.push('(');
8038 }
8039 match e {
8040 Expr::Binary { lhs, op, rhs } => {
8041 let child = match op {
8042 BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8043 BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8044 PrettyParent::Arith(prec)
8045 }
8046 _ => PrettyParent::Comparison,
8047 };
8048 write_pretty(out, lhs, child, false, mysql);
8049 out.push(' ');
8050 out.push_str(&alloc::format!("{op}"));
8051 out.push(' ');
8052 // AND / OR are associative, so an explicitly right-nested
8053 // chain still prints as one chain.
8054 let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8055 write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8056 }
8057 Expr::Unary { op, expr } => match op {
8058 UnOp::Not => {
8059 out.push_str("NOT ");
8060 write_pretty(out, expr, PrettyParent::Not, false, mysql);
8061 }
8062 UnOp::Neg => {
8063 out.push_str("- ");
8064 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8065 }
8066 UnOp::Plus => {
8067 out.push_str("+ ");
8068 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8069 }
8070 UnOp::BitNot => {
8071 out.push('~');
8072 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8073 }
8074 },
8075 Expr::Cast { expr, target } => {
8076 if mysql {
8077 // MySQL's own spelling, which is what its error messages
8078 // quote back.
8079 out.push_str("cast(");
8080 write_pretty(out, expr, PrettyParent::None, false, mysql);
8081 out.push_str(&alloc::format!(
8082 " as {})",
8083 target.to_string().to_lowercase()
8084 ));
8085 } else {
8086 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8087 out.push_str(&alloc::format!("::{target}"));
8088 }
8089 }
8090 Expr::IsNull { expr, negated } => {
8091 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8092 out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8093 }
8094 other => out.push_str(&alloc::format!("{other}")),
8095 }
8096 if needs {
8097 out.push(')');
8098 }
8099}
8100
8101const fn pretty_prec_not() -> u8 {
8102 // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8103 // when the XOR insertion shifted the deparse ladder up by one).
8104 4
8105}
8106
8107impl fmt::Display for Expr {
8108 #[allow(clippy::too_many_lines)]
8109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8110 match self {
8111 Self::Literal(l) => write!(f, "{l}"),
8112 Self::Column(c) => write!(f, "{c}"),
8113 Self::Placeholder(n) => write!(f, "${n}"),
8114 // Round-trips as the spelling PG's docs lead with.
8115 Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8116 Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8117 // v7.39 (round 311) — an AND / OR chain that nests to the
8118 // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8119 // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8120 // its parentheses, because that is a different grouping as
8121 // written. Both halves measured against PG 18.4's deparse,
8122 // which flattens a same-operator left chain at parse time and
8123 // leaves `a AND (b AND c)` alone.
8124 Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8125 f.write_str("(")?;
8126 write_bool_chain(f, lhs, *op)?;
8127 write!(f, " {op} {rhs}")?;
8128 f.write_str(")")
8129 }
8130 Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8131 Self::Unary { op, expr } => match op {
8132 UnOp::Not => write!(f, "(NOT {expr})"),
8133 // A space after the sign, as PG's deparse writes it.
8134 UnOp::Neg => write!(f, "(- {expr})"),
8135 UnOp::Plus => write!(f, "(+ {expr})"),
8136 UnOp::BitNot => write!(f, "(~{expr})"),
8137 },
8138 // The OPERAND carries the parentheses, not the cast:
8139 // `(a)::text`, `((a + b))::text`. PG words it this way, and
8140 // it is what keeps `a::text = t` from reading as a cast of
8141 // the comparison.
8142 Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8143 Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8144 Self::AggregateOrdered {
8145 call,
8146 order_by,
8147 distinct,
8148 filter,
8149 } => {
8150 let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8151 for (i, o) in order_by.iter().enumerate() {
8152 if i > 0 {
8153 f.write_str(", ")?;
8154 }
8155 write!(f, "{}", o.expr)?;
8156 if o.desc {
8157 f.write_str(" DESC")?;
8158 }
8159 match o.nulls_first {
8160 Some(true) => f.write_str(" NULLS FIRST")?,
8161 Some(false) => f.write_str(" NULLS LAST")?,
8162 None => {}
8163 }
8164 }
8165 Ok(())
8166 };
8167 // Ordered-set aggregates (`percentile_cont(f) WITHIN
8168 // GROUP (ORDER BY x)`) render the in-parens args as the
8169 // direct argument and the sort spec under WITHIN GROUP —
8170 // not as an in-argument ORDER BY.
8171 let ordered_set = matches!(
8172 call.as_ref(),
8173 Expr::FunctionCall { name, .. }
8174 if matches!(
8175 name.to_ascii_lowercase().as_str(),
8176 "percentile_cont" | "percentile_disc" | "mode"
8177 )
8178 );
8179 if ordered_set {
8180 write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8181 fmt_order_by(f)?;
8182 f.write_str(")")?;
8183 } else {
8184 // `name([DISTINCT ]args [ORDER BY …])` — peel the
8185 // inner call's parens to splice modifiers.
8186 let inner = alloc::format!("{call}");
8187 let body = inner.strip_suffix(')').unwrap_or(&inner);
8188 let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8189 write!(f, "{head}(")?;
8190 if *distinct {
8191 f.write_str("DISTINCT ")?;
8192 }
8193 write!(f, "{args_part}")?;
8194 if !order_by.is_empty() {
8195 f.write_str(" ORDER BY ")?;
8196 fmt_order_by(f)?;
8197 }
8198 f.write_str(")")?;
8199 }
8200 if let Some(cond) = filter {
8201 write!(f, " FILTER (WHERE {cond})")?;
8202 }
8203 Ok(())
8204 }
8205 Self::IsNull { expr, negated } => {
8206 if *negated {
8207 write!(f, "({expr} IS NOT NULL)")
8208 } else {
8209 write!(f, "({expr} IS NULL)")
8210 }
8211 }
8212 Self::BoolTest {
8213 expr,
8214 value,
8215 negated,
8216 } => {
8217 let word = match value {
8218 Some(true) => "TRUE",
8219 Some(false) => "FALSE",
8220 None => "UNKNOWN",
8221 };
8222 if *negated {
8223 write!(f, "({expr} IS NOT {word})")
8224 } else {
8225 write!(f, "({expr} IS {word})")
8226 }
8227 }
8228 Self::FunctionCall { name, args } => {
8229 write!(f, "{name}(")?;
8230 for (i, a) in args.iter().enumerate() {
8231 if i > 0 {
8232 f.write_str(", ")?;
8233 }
8234 write!(f, "{a}")?;
8235 }
8236 f.write_str(")")
8237 }
8238 Self::Like {
8239 expr,
8240 pattern,
8241 negated,
8242 case_insensitive,
8243 } => {
8244 let op = match (negated, case_insensitive) {
8245 (false, false) => "LIKE",
8246 (true, false) => "NOT LIKE",
8247 (false, true) => "ILIKE",
8248 (true, true) => "NOT ILIKE",
8249 };
8250 write!(f, "({expr} {op} {pattern})")
8251 }
8252 Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8253 Self::WindowFunction {
8254 name,
8255 args,
8256 partition_by,
8257 order_by,
8258 frame,
8259 null_treatment,
8260 filter,
8261 } => {
8262 write!(f, "{name}(")?;
8263 for (i, a) in args.iter().enumerate() {
8264 if i > 0 {
8265 f.write_str(", ")?;
8266 }
8267 write!(f, "{a}")?;
8268 }
8269 f.write_str(")")?;
8270 // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8271 // OVER; it round-trips so a window body's Display re-parses.
8272 if let Some(cond) = filter {
8273 write!(f, " FILTER (WHERE {cond})")?;
8274 }
8275 // v7.30.1 (mailrs round-24 class audit) — IGNORE
8276 // NULLS sits between the arg list and OVER; dropping
8277 // it reverted replayed queries to RESPECT NULLS.
8278 if matches!(null_treatment, NullTreatment::Ignore) {
8279 f.write_str(" IGNORE NULLS")?;
8280 }
8281 f.write_str(" OVER (")?;
8282 if !partition_by.is_empty() {
8283 f.write_str("PARTITION BY ")?;
8284 for (i, p) in partition_by.iter().enumerate() {
8285 if i > 0 {
8286 f.write_str(", ")?;
8287 }
8288 write!(f, "{p}")?;
8289 }
8290 }
8291 if !order_by.is_empty() {
8292 if !partition_by.is_empty() {
8293 f.write_str(" ")?;
8294 }
8295 f.write_str("ORDER BY ")?;
8296 for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8297 if i > 0 {
8298 f.write_str(", ")?;
8299 }
8300 write!(f, "{e}")?;
8301 if *desc {
8302 f.write_str(" DESC")?;
8303 }
8304 match nulls_first {
8305 Some(true) => f.write_str(" NULLS FIRST")?,
8306 Some(false) => f.write_str(" NULLS LAST")?,
8307 None => {}
8308 }
8309 }
8310 }
8311 if let Some(fr) = frame {
8312 if !partition_by.is_empty() || !order_by.is_empty() {
8313 f.write_str(" ")?;
8314 }
8315 let k = match fr.kind {
8316 FrameKind::Rows => "ROWS",
8317 FrameKind::Range => "RANGE",
8318 FrameKind::Groups => "GROUPS",
8319 };
8320 if let Some(end) = &fr.end {
8321 write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8322 } else {
8323 write!(f, "{k} {}", fr.start)?;
8324 }
8325 }
8326 f.write_str(")")
8327 }
8328 Self::ScalarSubquery(s) => write!(f, "({s})"),
8329 Self::Exists { subquery, negated } => {
8330 if *negated {
8331 write!(f, "NOT EXISTS ({subquery})")
8332 } else {
8333 write!(f, "EXISTS ({subquery})")
8334 }
8335 }
8336 Self::InSubquery {
8337 expr,
8338 subquery,
8339 negated,
8340 } => {
8341 if *negated {
8342 write!(f, "({expr} NOT IN ({subquery}))")
8343 } else {
8344 write!(f, "({expr} IN ({subquery}))")
8345 }
8346 }
8347 Self::RowInSubquery {
8348 row,
8349 subquery,
8350 negated,
8351 } => {
8352 write!(f, "(")?;
8353 for (i, e) in row.iter().enumerate() {
8354 if i > 0 {
8355 write!(f, ", ")?;
8356 }
8357 write!(f, "{e}")?;
8358 }
8359 let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8360 write!(f, "{kw}{subquery})")
8361 }
8362 Self::RowCmpSubquery { row, op, subquery } => {
8363 write!(f, "(")?;
8364 for (i, e) in row.iter().enumerate() {
8365 if i > 0 {
8366 write!(f, ", ")?;
8367 }
8368 write!(f, "{e}")?;
8369 }
8370 write!(f, ") {op} ({subquery})")
8371 }
8372 Self::InList {
8373 expr,
8374 list,
8375 negated,
8376 } => {
8377 let kw = if *negated { " NOT IN (" } else { " IN (" };
8378 write!(f, "({expr}{kw}")?;
8379 for (i, e) in list.iter().enumerate() {
8380 if i > 0 {
8381 f.write_str(", ")?;
8382 }
8383 write!(f, "{e}")?;
8384 }
8385 f.write_str("))")
8386 }
8387 Self::Array(items) => {
8388 f.write_str("ARRAY[")?;
8389 for (i, e) in items.iter().enumerate() {
8390 if i > 0 {
8391 f.write_str(", ")?;
8392 }
8393 write!(f, "{e}")?;
8394 }
8395 f.write_str("]")
8396 }
8397 Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
8398 Self::ArraySlice { target, lo, hi } => {
8399 write!(f, "({target}[")?;
8400 if let Some(l) = lo {
8401 write!(f, "{l}")?;
8402 }
8403 write!(f, ":")?;
8404 if let Some(h) = hi {
8405 write!(f, "{h}")?;
8406 }
8407 write!(f, "])")
8408 }
8409 Self::AnyAll {
8410 expr,
8411 op,
8412 array,
8413 is_any,
8414 } => {
8415 let kw = if *is_any { "ANY" } else { "ALL" };
8416 write!(f, "({expr} {op} {kw}({array}))")
8417 }
8418 Self::Case {
8419 operand,
8420 branches,
8421 else_branch,
8422 } => {
8423 f.write_str("CASE")?;
8424 if let Some(op) = operand {
8425 write!(f, " {op}")?;
8426 }
8427 for (w, t) in branches {
8428 write!(f, " WHEN {w} THEN {t}")?;
8429 }
8430 if let Some(e) = else_branch {
8431 write!(f, " ELSE {e}")?;
8432 }
8433 f.write_str(" END")
8434 }
8435 }
8436 }
8437}
8438
8439/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
8440/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
8441pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
8442 use alloc::string::ToString;
8443 if scale == 0 {
8444 return alloc::format!("{unscaled}");
8445 }
8446 let neg = unscaled < 0;
8447 let digits = alloc::format!("{}", unscaled.unsigned_abs());
8448 let scale = scale as usize;
8449 let (int_part, frac_part) = if digits.len() > scale {
8450 (
8451 digits[..digits.len() - scale].to_string(),
8452 digits[digits.len() - scale..].to_string(),
8453 )
8454 } else {
8455 ("0".to_string(), alloc::format!("{digits:0>scale$}"))
8456 };
8457 alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
8458}
8459
8460impl fmt::Display for Literal {
8461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8462 match self {
8463 Self::Integer(n) => write!(f, "{n}"),
8464 Self::Float(x) => {
8465 let s = format!("{x}");
8466 // Default Display for an integral f64 (e.g. 1.0) emits "1",
8467 // which would round-trip back to Integer. Force a dot.
8468 if s.contains('.') || s.contains('e') || s.contains('E') {
8469 f.write_str(&s)
8470 } else {
8471 write!(f, "{s}.0")
8472 }
8473 }
8474 Self::Numeric { unscaled, scale } => {
8475 // Render the exact decimal `unscaled / 10^scale`, preserving
8476 // scale (trailing zeros) — round-trips to the same literal.
8477 f.write_str(&render_exact_decimal(*unscaled, *scale))
8478 }
8479 Self::NumericBig(s) => f.write_str(s),
8480 Self::String(s) => {
8481 f.write_str("'")?;
8482 for c in s.chars() {
8483 if c == '\'' {
8484 f.write_str("''")?;
8485 } else {
8486 write!(f, "{c}")?;
8487 }
8488 }
8489 f.write_str("'")
8490 }
8491 Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
8492 Self::Null => f.write_str("NULL"),
8493 // PG external array form. Display round-trip re-enters
8494 // through the column-typed text coerce, same as pgwire.
8495 Self::TextArray(items) => {
8496 f.write_str("'{")?;
8497 for (i, it) in items.iter().enumerate() {
8498 if i > 0 {
8499 f.write_str(",")?;
8500 }
8501 match it {
8502 None => f.write_str("NULL")?,
8503 Some(s) => {
8504 f.write_str("\"")?;
8505 for c in s.chars() {
8506 match c {
8507 // array-element escapes
8508 '"' | '\\' => write!(f, "\\{c}")?,
8509 // the OUTER wrapper is a SQL string
8510 // literal — embedded quotes must
8511 // double, or the rendered form
8512 // (WAL replay parses it back) is
8513 // invalid SQL
8514 '\'' => f.write_str("''")?,
8515 _ => write!(f, "{c}")?,
8516 }
8517 }
8518 f.write_str("\"")?;
8519 }
8520 }
8521 }
8522 f.write_str("}'")
8523 }
8524 Self::IntArray(items) => {
8525 f.write_str("'{")?;
8526 for (i, it) in items.iter().enumerate() {
8527 if i > 0 {
8528 f.write_str(",")?;
8529 }
8530 match it {
8531 None => f.write_str("NULL")?,
8532 Some(n) => write!(f, "{n}")?,
8533 }
8534 }
8535 f.write_str("}'")
8536 }
8537 Self::BigIntArray(items) => {
8538 f.write_str("'{")?;
8539 for (i, it) in items.iter().enumerate() {
8540 if i > 0 {
8541 f.write_str(",")?;
8542 }
8543 match it {
8544 None => f.write_str("NULL")?,
8545 Some(n) => write!(f, "{n}")?,
8546 }
8547 }
8548 f.write_str("}'")
8549 }
8550 Self::Vector(v) => {
8551 f.write_str("[")?;
8552 for (i, x) in v.iter().enumerate() {
8553 if i > 0 {
8554 f.write_str(", ")?;
8555 }
8556 let s = format!("{x}");
8557 // Mirror Float Display: force a dot so re-parse stays
8558 // numerically literal.
8559 if s.contains('.') || s.contains('e') || s.contains('E') {
8560 f.write_str(&s)?;
8561 } else {
8562 write!(f, "{s}.0")?;
8563 }
8564 }
8565 f.write_str("]")
8566 }
8567 Self::Interval { text, .. } => {
8568 f.write_str("INTERVAL '")?;
8569 for c in text.chars() {
8570 if c == '\'' {
8571 f.write_str("''")?;
8572 } else {
8573 write!(f, "{c}")?;
8574 }
8575 }
8576 f.write_str("'")
8577 }
8578 }
8579 }
8580}
8581
8582impl fmt::Display for BinOp {
8583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8584 f.write_str(match self {
8585 Self::Or => "OR",
8586 Self::And => "AND",
8587 Self::Eq => "=",
8588 Self::NotEq => "<>",
8589 Self::IsDistinctFrom => "IS DISTINCT FROM",
8590 Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
8591 Self::IntDiv => "DIV",
8592 Self::Lt => "<",
8593 Self::LtEq => "<=",
8594 Self::Gt => ">",
8595 Self::GtEq => ">=",
8596 Self::Add => "+",
8597 Self::Sub => "-",
8598 Self::Mul => "*",
8599 Self::Div => "/",
8600 Self::Mod => "%",
8601 Self::L2Distance => "<->",
8602 Self::GeomParallel => "?||",
8603 Self::OverLeft => "&<",
8604 Self::OverRight => "&>",
8605 Self::GeomPerp => "?-|",
8606 Self::GeomSameAs => "~=",
8607 Self::ClosestPoint => "##",
8608 Self::GeomHoriz => "?-",
8609 Self::InnerProduct => "<#>",
8610 Self::CosineDistance => "<=>",
8611 Self::Concat => "||",
8612 Self::BitOr => "|",
8613 Self::BitAnd => "&",
8614 Self::BitXor => "#",
8615 Self::LogicalXor => "xor",
8616 Self::JsonGet => "->",
8617 Self::JsonGetText => "->>",
8618 Self::JsonGetPath => "#>",
8619 Self::JsonGetPathText => "#>>",
8620 Self::JsonContains => "@>",
8621 Self::JsonPathExists => "@?",
8622 Self::JsonContainedBy => "<@",
8623 Self::JsonKeyExists => "?",
8624 Self::JsonKeysAny => "?|",
8625 Self::JsonKeysAll => "?&",
8626 Self::JsonDeletePath => "#-",
8627 Self::TsMatch => "@@",
8628 Self::InetContainedBy => "<<",
8629 Self::InetContainedByEq => "<<=",
8630 Self::InetContains => ">>",
8631 Self::InetContainsEq => ">>=",
8632 Self::InetOverlap => "&&",
8633 Self::Intersects => "?#",
8634 Self::IsBelow => "<^",
8635 Self::IsAbove => ">^",
8636 Self::PatternLt => "~<~",
8637 Self::PatternLtEq => "~<=~",
8638 Self::PatternGt => "~>~",
8639 Self::PatternGtEq => "~>=~",
8640 })
8641 }
8642}
8643
8644/// Quote `s` as a PG double-quoted identifier when required (keyword,
8645/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
8646/// Otherwise return it as-is. Returns an owned `String` to keep the call site
8647/// uniform.
8648pub(crate) fn quote_ident(s: &str) -> String {
8649 let needs_quote = match s.chars().next() {
8650 None => true,
8651 Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
8652 _ => {
8653 s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
8654 || s.chars().any(|c| c.is_ascii_uppercase())
8655 || is_keyword(s)
8656 }
8657 };
8658 if !needs_quote {
8659 return s.to_string();
8660 }
8661 let mut out = String::with_capacity(s.len() + 2);
8662 out.push('"');
8663 for c in s.chars() {
8664 if c == '"' {
8665 out.push_str("\"\"");
8666 } else {
8667 out.push(c);
8668 }
8669 }
8670 out.push('"');
8671 out
8672}
8673
8674fn is_keyword(s: &str) -> bool {
8675 matches!(
8676 &*s.to_ascii_lowercase(),
8677 "select"
8678 | "from"
8679 | "where"
8680 | "as"
8681 | "null"
8682 | "true"
8683 | "false"
8684 | "and"
8685 | "or"
8686 | "not"
8687 | "create"
8688 | "table"
8689 | "insert"
8690 | "into"
8691 | "values"
8692 | "index"
8693 | "on"
8694 | "begin"
8695 | "commit"
8696 | "rollback"
8697 | "is"
8698 | "between"
8699 | "in"
8700 | "like"
8701 | "group"
8702 | "distinct"
8703 | "union"
8704 | "all"
8705 | "join"
8706 | "inner"
8707 | "left"
8708 | "cross"
8709 | "outer"
8710 | "default"
8711 | "savepoint"
8712 | "release"
8713 | "to"
8714 | "having"
8715 | "show"
8716 | "extract"
8717 | "offset"
8718 | "asc"
8719 | "desc"
8720 | "interval"
8721 )
8722}
8723
8724#[cfg(test)]
8725mod tests {
8726 use super::*;
8727 use alloc::vec;
8728
8729 #[test]
8730 fn integer_literal_renders_without_dot() {
8731 assert_eq!(Literal::Integer(42).to_string(), "42");
8732 }
8733
8734 #[test]
8735 fn integral_float_keeps_dot() {
8736 assert_eq!(Literal::Float(1.0).to_string(), "1.0");
8737 assert_eq!(Literal::Float(1.5).to_string(), "1.5");
8738 assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
8739 }
8740
8741 #[test]
8742 fn string_literal_doubles_quote() {
8743 assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
8744 }
8745
8746 #[test]
8747 fn bool_and_null_render_uppercase() {
8748 assert_eq!(Literal::Bool(true).to_string(), "TRUE");
8749 assert_eq!(Literal::Bool(false).to_string(), "FALSE");
8750 assert_eq!(Literal::Null.to_string(), "NULL");
8751 }
8752
8753 #[test]
8754 fn binary_op_always_parenthesised() {
8755 let e = Expr::Binary {
8756 lhs: Box::new(Expr::Literal(Literal::Integer(1))),
8757 op: BinOp::Add,
8758 rhs: Box::new(Expr::Literal(Literal::Integer(2))),
8759 };
8760 assert_eq!(e.to_string(), "(1 + 2)");
8761 }
8762
8763 #[test]
8764 fn select_star_from_table() {
8765 let s = SelectStatement {
8766 locking: None,
8767 items: vec![SelectItem::Wildcard],
8768 from: Some(FromClause {
8769 primary: TableRef {
8770 name: "users".into(),
8771 alias: None,
8772 only: false,
8773 as_of_segment: None,
8774 unnest_expr: None,
8775 unnest_column_aliases: Vec::new(),
8776 with_ordinality: false,
8777 generate_series_args: None,
8778 lateral_subquery: None,
8779 jsonb_each_text_arg: None,
8780 table_fn_call: None,
8781 rows_from: None,
8782 json_table: None,
8783 scalar_fn_item: false,
8784 },
8785 joins: vec![],
8786 }),
8787 where_: None,
8788 group_by: None,
8789 group_by_all: false,
8790 having: None,
8791 unions: vec![],
8792 order_by: Vec::new(),
8793 limit: None,
8794 offset: None,
8795 limit_with_ties: false,
8796 window_check_exprs: Vec::new(),
8797 distinct: false,
8798 distinct_on: Vec::new(),
8799 ctes: vec![],
8800 };
8801 assert_eq!(s.to_string(), "SELECT * FROM users");
8802 }
8803
8804 #[test]
8805 fn quote_ident_for_uppercase_and_keyword() {
8806 assert_eq!(quote_ident("foo"), "foo");
8807 assert_eq!(quote_ident("Foo"), "\"Foo\"");
8808 assert_eq!(quote_ident("select"), "\"select\"");
8809 assert_eq!(quote_ident(""), "\"\"");
8810 assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
8811 }
8812}