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 /// v7.38.18 — `CREATE DATABASE … LC_COLLATE 'de_DE.utf8'` is in
228 /// every PostgreSQL bootstrap script there is, and SPG threw the
229 /// whole statement away. Being single-database makes the NAME a
230 /// no-op; it does not make the collation one, and a database
231 /// that quietly sorts by the container's `LANG` instead of the
232 /// one the script asked for is a silent difference in every
233 /// `ORDER BY` it will ever run.
234 ///
235 /// `LOCALE` and `LC_COLLATE` both land here; `LC_CTYPE` does
236 /// not, because SPG has no separate ctype.
237 collation: Option<String>,
238 /// v7.38.19 — the database's name, so `pg_database` can list one
239 /// that was created and can be connected to. It was thrown away
240 /// with the rest of the statement.
241 name: Option<String>,
242 },
243 /// v7.39 (round 696) — statements SPG performs nothing for, but whose
244 /// OPERAND PG validates before performing nothing either.
245 ///
246 /// All four used to be consumed whole by `is_dump_noise_statement`,
247 /// which meant `LOCK TABLE nosuch` and `DROP OWNED BY nosuchrole` were
248 /// ACCEPTED where PG18 errors. Accepting a statement that names
249 /// something that does not exist is the F29 shape: the caller is told
250 /// their intent was understood when the object it referred to is not
251 /// there.
252 ///
253 /// They share one variant because they share one rule — resolve the
254 /// name, refuse if absent, otherwise no-op — and four variants would be
255 /// four places for that rule to drift.
256 /// v7.39 (round 707) — `DROP AGGREGATE [IF EXISTS] name(argtypes)[, …]`.
257 /// Consumed whole by the dump-noise list before, so `DROP AGGREGATE
258 /// nosuch(int)` reported success. PG validates every named aggregate's
259 /// EXISTENCE first (measured: a list with one unknown fails on the
260 /// unknown even when an earlier entry exists), renders the signature
261 /// with canonical type names (`int` → `integer`), and refuses to drop a
262 /// built-in (`cannot drop function sum(integer) because it is required
263 /// by the database system`). Every SPG aggregate is a built-in, so the
264 /// outcome is one of those two errors — or the IF EXISTS no-op.
265 ///
266 /// `args` holds the argument type names as written; `None` is the
267 /// `(*)` spelling.
268 DropAggregate {
269 if_exists: bool,
270 items: Vec<(String, Option<Vec<String>>)>,
271 },
272 /// v7.39 (round 750) — `ALTER ROLE|USER <name> … PASSWORD 'x' |
273 /// PASSWORD NULL`. The one attribute of the no-op family with a
274 /// SECURITY consequence: it was silently dropped (ledgered r710),
275 /// so a rotated credential never rotated. `None` = PASSWORD NULL
276 /// (the role keeps existing but can no longer password-auth).
277 AlterRolePassword {
278 name: String,
279 password: Option<String>,
280 },
281 ValidateOnly {
282 kind: ValidateOnlyKind,
283 /// The names the statement referred to. Empty means the form names
284 /// nothing (`SECURITY LABEL`, whose refusal is unconditional).
285 names: Vec<String>,
286 },
287
288 /// v7.39 (round 547) — `ALTER ROLE … SET/RESET` and
289 /// `ALTER DATABASE … SET/RESET`: the GUC defaults a session picks up
290 /// when it starts. Both used to land in the pg_dump no-op tail, so
291 /// the statement reported success and changed nothing.
292 ///
293 /// `database` / `role` are `None` for PG's oid 0 — `ALTER ROLE ALL`
294 /// sets both to None. `param` is `None` for RESET ALL. `value` is
295 /// `None` for RESET of one parameter.
296 SetDbRoleSetting(Box<SetDbRoleSettingStatement>),
297 /// v7.39 (round 288) — `SET CONSTRAINTS { ALL | <name>… }
298 /// { DEFERRED | IMMEDIATE }`. `deferred` carries the timing; the
299 /// name list is not yet honoured (ALL is what pg_dump emits and
300 /// what a circular-FK restore needs), so a named form applies to
301 /// all deferrable constraints too rather than silently doing
302 /// nothing.
303 /// v7.39 (round 308) — `SET CONSTRAINTS { ALL | name [, …] }
304 /// { DEFERRED | IMMEDIATE }`. An empty `names` is the ALL form;
305 /// otherwise the timing applies only to the constraints listed.
306 SetConstraints {
307 names: Vec<String>,
308 deferred: bool,
309 },
310
311 /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
312 /// [CASCADE | RESTRICT]`. Engine removes the matching tables
313 /// (each one) from the catalog; IF EXISTS makes the drop
314 /// idempotent. CASCADE / RESTRICT trailers parsed silently
315 /// (SPG always cascades index drops on table drop).
316 DropTable {
317 names: Vec<String>,
318 if_exists: bool,
319 },
320 /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
321 /// matching index across whichever table holds it.
322 DropIndex {
323 name: String,
324 if_exists: bool,
325 /// v7.39.7 — the table named by MySQL's `DROP INDEX i ON t`.
326 ///
327 /// MySQL keys an index name inside its table and its statement
328 /// says so; PostgreSQL keys it in the schema and has no `ON`
329 /// clause at all. `None` is the PostgreSQL form, which searches
330 /// every table for the name, and is what the MySQL dialect
331 /// refuses — as MySQL does.
332 table: Option<String>,
333 },
334 /// v7.14.0 — empty / comment-only statement. The lexer strips
335 /// `--` line comments and `/* … */` block comments (including
336 /// the MySQL conditional `/*!NNNNN … */` form) before the
337 /// parser ever sees them; a SQL chunk that contains nothing
338 /// else lands here. Engine returns CommandOk no-op so
339 /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
340 /// wrapped in conditional comments, etc.) load cleanly.
341 /// v7.39 (round 277) — SQL-level `PREPARE <name> [(type, …)] AS
342 /// <stmt>`. Session-scoped; the body keeps its `$N` placeholders
343 /// and is substituted at EXECUTE time.
344 Prepare {
345 name: String,
346 /// Declared parameter type names, in order. Empty when the
347 /// `(type, …)` list was omitted (PG infers them).
348 param_types: Vec<String>,
349 body: alloc::boxed::Box<Statement>,
350 /// The statement's own source text, which
351 /// `pg_prepared_statements.statement` reports verbatim.
352 source: String,
353 },
354 /// v7.39 (round 277) — `EXECUTE <name> [(arg, …)]`.
355 Execute {
356 name: String,
357 args: Vec<Expr>,
358 },
359 /// v7.39 (round 277) — `DEALLOCATE {<name> | ALL}`. `None` = ALL.
360 Deallocate(Option<String>),
361 /// v7.39 (round 280) — `CREATE STATISTICS [IF NOT EXISTS] <name>
362 /// [(kind, …)] ON <col>, … FROM <table>`. SPG records the object so
363 /// dumps restore and reflection is honest; the planner does not
364 /// consult it yet.
365 CreateStatistics {
366 name: String,
367 if_not_exists: bool,
368 /// Requested kinds as PG's single letters (`d` ndistinct,
369 /// `f` dependencies, `m` mcv). Empty = PG's default set.
370 kinds: Vec<String>,
371 columns: Vec<String>,
372 table: String,
373 },
374 /// v7.39 (round 280) — `DROP STATISTICS [IF EXISTS] <name>`.
375 DropStatistics {
376 name: String,
377 if_exists: bool,
378 },
379 /// v7.39 (round 278) — `CALL <proc>(…)`. Parses; the engine
380 /// reports that the procedure does not exist, because SPG has no
381 /// procedure catalog. Carried as a statement rather than raised at
382 /// parse time so the failure is a missing OBJECT (42883), not a
383 /// syntax error.
384 Call(String),
385 /// v7.39 (round 278) — `PREPARE TRANSACTION '<gid>'`. Same shape:
386 /// 2PC is unavailable, which PG itself reports when
387 /// `max_prepared_transactions` is 0.
388 PrepareTransaction(String),
389 Empty,
390 /// v7.39 (round 218) — `DECLARE <name> [BINARY] [INSENSITIVE]
391 /// [[NO] SCROLL] CURSOR [{WITH|WITHOUT} HOLD] FOR <select>`. The
392 /// canonical driver path for streaming large result sets (psycopg2
393 /// named cursors, JDBC setFetchSize).
394 DeclareCursor {
395 name: String,
396 /// `None` = neither keyword (PG default: backward allowed when the
397 /// plan supports it — always, for SPG's materialized cursors);
398 /// `Some(true)` = SCROLL; `Some(false)` = NO SCROLL (backward
399 /// fetch errors 55000).
400 scroll: Option<bool>,
401 /// `WITH HOLD` — survives the creating transaction's COMMIT.
402 hold: bool,
403 query: Box<Statement>,
404 },
405 /// v7.39 (round 218) — `FETCH [<direction>] [FROM|IN] <name>`.
406 FetchCursor {
407 name: String,
408 direction: CursorDirection,
409 },
410 /// v7.39 (round 218) — `MOVE [<direction>] [FROM|IN] <name>`: FETCH
411 /// without returning rows; the command tag carries the move count.
412 MoveCursor {
413 name: String,
414 direction: CursorDirection,
415 },
416 /// v7.39 (round 218) — `CLOSE <name>` / `CLOSE ALL` (`None` = ALL).
417 CloseCursor {
418 name: Option<String>,
419 },
420 /// v7.39 (round 222) — `LISTEN <channel>`: subscribe this session to
421 /// async notifications on the channel.
422 Listen(String),
423 /// v7.39 (round 222) — `NOTIFY <channel> [, '<payload>']`. Delivered at
424 /// COMMIT (PG semantics: transactional, deduplicated within the tx);
425 /// immediately under autocommit.
426 Notify {
427 channel: String,
428 payload: Option<String>,
429 },
430 /// v7.39 (round 222) — `UNLISTEN <channel>` / `UNLISTEN *` (`None` = *).
431 Unlisten(Option<String>),
432 /// `COPY table [(cols)] TO STDOUT` — the engine renders the
433 /// visible rows in COPY text format (tab-separated, `\N`
434 /// nulls, backslash escapes) as a single-text-column result
435 /// set; the wire layer streams CopyData from it.
436 CopyTo {
437 table: String,
438 columns: Option<Vec<String>>,
439 /// v7.39 (read01 round 94) — `COPY (<query>) TO STDOUT`: an
440 /// arbitrary SELECT/VALUES/CTE (a whole [`Statement`], so set-ops and
441 /// VALUES ride through unchanged) whose result set is streamed in COPY
442 /// format. `Some` overrides `table`/`columns` (which are empty then);
443 /// `None` is the classic `COPY <table> …` shape.
444 query: Option<Box<Statement>>,
445 /// v7.37.x — `WITH (FORMAT csv, HEADER, DELIMITER, NULL, QUOTE)`
446 /// and the legacy `WITH CSV HEADER …` spelling. Default =
447 /// text format, no header (bare `COPY … TO STDOUT`).
448 options: CopyOptions,
449 },
450 /// v7.39 (round 249) — `COPY table [(cols)] FROM '<path>' [(opts)]`.
451 /// The engine is no_std and cannot read the file itself: the host
452 /// (embedded / server / tooling) reads the path and hands the bytes to
453 /// `Engine::copy_from_buffer`. Dispatching this statement straight to
454 /// the engine reports that contract.
455 CopyFromFile {
456 table: String,
457 columns: Option<Vec<String>>,
458 path: String,
459 options: CopyOptions,
460 },
461 /// v7.39 (round 249/252) — `COPY <table> [(cols)] TO '<file>'` (and
462 /// the `COPY (<query>) TO '<file>'` form). The engine is no_std and
463 /// cannot write the file itself: the host renders the payload via
464 /// `Engine::copy_to_buffer` and writes the path.
465 CopyToFile {
466 table: String,
467 columns: Option<Vec<String>>,
468 query: Option<Box<Statement>>,
469 path: String,
470 options: CopyOptions,
471 },
472 Select(SelectStatement),
473 CreateTable(CreateTableStatement),
474 /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
475 /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
476 /// no-op so PG dumps that include extension declarations
477 /// (notably `pgvector`) load against SPG without splitting
478 /// init scripts. mailrs migration follow-up F3.
479 CreateExtension(String),
480 /// v7.9.27 → v7.16.2 — PG `DO $$ … $$ [LANGUAGE plpgsql];`
481 /// block. The body is now CAPTURED as a [`PlPgSqlBlock`] and
482 /// the engine executes it at top level (mailrs round-10
483 /// A.2). Pre-v7.16.2 the parser discarded the body and the
484 /// engine returned CommandOk — a SEV-1 silent no-op that
485 /// turned mailrs's `DO BEGIN IF EXISTS … THEN ALTER … END
486 /// $$` idempotent migrations into invisible no-ops.
487 DoBlock(PlPgSqlBlock),
488 CreateIndex(CreateIndexStatement),
489 Insert(InsertStatement),
490 /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
491 Update(UpdateStatement),
492 /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
493 Delete(DeleteStatement),
494 /// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ `MERGE` statement.
495 /// `MERGE INTO target [alias] USING source [alias] ON cond
496 /// WHEN MATCHED [AND cond] THEN { UPDATE SET … | DELETE | DO NOTHING }
497 /// WHEN NOT MATCHED [AND cond] THEN { INSERT (cols) VALUES (vals) | DO NOTHING }
498 /// [WHEN …]`. SPG v7.17 supports table-based source (subquery
499 /// source is a follow-up); BY SOURCE / BY TARGET and RETURNING
500 /// are also follow-ups.
501 Merge(MergeStatement),
502 /// v7.39 (round 169) — `VACUUM [(opts)] [FULL|FREEZE|VERBOSE|ANALYZE]
503 /// [<table>]`. Was a parse-time no-op from the pre-MVCC era; with the
504 /// in-place MVCC gate ON, tombstoned versions are REAL bloat and a
505 /// customer's manual VACUUM must actually reclaim. `analyze` mirrors
506 /// the `VACUUM ANALYZE` spelling.
507 Vacuum {
508 table: Option<String>,
509 analyze: bool,
510 },
511 /// `BEGIN` / `START TRANSACTION` — with an optional explicit
512 /// `ISOLATION LEVEL …` mode (`None` = use the session default). PG
513 /// applies the level for the duration of this transaction only.
514 Begin(TransactionModes),
515 Commit,
516 Rollback,
517 /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
518 /// stack so a later `ROLLBACK TO <name>` can undo just the work
519 /// since this point.
520 Savepoint(String),
521 /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
522 /// named savepoint and discard later savepoints. Does not end the
523 /// transaction.
524 RollbackToSavepoint(String),
525 /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
526 /// rolling back. Keeps the work done since then.
527 ReleaseSavepoint(String),
528 /// `SHOW TABLES` — return the list of tables in the catalog.
529 ShowTables,
530 /// v7.17.0 Phase 3.P0-58 — MySQL `SHOW DATABASES` /
531 /// `SHOW SCHEMAS`. SPG is single-database; the executor
532 /// returns the canonical MySQL set so the mysql / MariaDB
533 /// client populates its database selector.
534 ShowDatabases,
535 /// v7.39.2 — MySQL `USE <db>`.
536 ///
537 /// It parsed as `Empty` and did nothing at all, so `USE myapp;
538 /// SELECT DATABASE()` answered the same constant it answered before
539 /// — measured against MySQL 9.7.2, which answers `myapp`. SPG serves
540 /// ONE database and answers to any name (see `CREATE DATABASE`), so
541 /// this does not switch catalogs; it records the NAME, which is the
542 /// half a client can observe and the half the PostgreSQL wire has
543 /// tracked since v7.39 (`current_database()` names what the startup
544 /// message asked for).
545 UseDatabase(String),
546 /// v7.17.0 Phase 3.P0-59 — MySQL `SHOW CREATE TABLE <t>`
547 /// returns a 2-column row `(Table, "Create Table")` carrying
548 /// the synthesized DDL. mysqldump emits this for every
549 /// table at scrape time.
550 ShowCreateTable(String),
551 /// v7.17.0 Phase 3.P0-60 — MySQL `SHOW INDEXES FROM <t>`
552 /// (also `SHOW INDEX`, `SHOW KEYS`).
553 ShowIndexes(String),
554 /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW STATUS`.
555 ShowStatus,
556 /// v7.17.0 Phase 3.P0-61 — MySQL `SHOW VARIABLES`.
557 ShowVariables,
558 /// r1067 — MySQL `SHOW VARIABLES LIKE 'pattern'` (sysbench-tpcc
559 /// probes isolation with it at connect).
560 ShowVariablesLike(String),
561 /// v7.17.0 Phase 3.P0-62 — MySQL `SHOW PROCESSLIST`.
562 ShowProcesslist,
563 /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
564 /// pgbouncer sends `DISCARD ALL` between pooled client sessions to make
565 /// the connection look brand new to the next client; it used to be
566 /// swallowed as dump noise, so nothing was discarded.
567 Discard(DiscardTarget),
568 /// v7.39 (round 318, V51) — MySQL `KILL [CONNECTION | QUERY] <expr>`.
569 /// The id is an expression because MariaDB accepts one
570 /// (`KILL connection_id()` is the documented way to drop your own
571 /// connection). `query_only` is the `QUERY` form: stop the target's
572 /// running statement but leave it connected.
573 Kill {
574 query_only: bool,
575 id: Box<Expr>,
576 },
577 /// `SHOW COLUMNS FROM <table>` — return one row per column with
578 /// its declared name / type / nullability.
579 ShowColumns(String),
580 /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
581 /// Role is optional; defaults to `readonly` when omitted.
582 CreateUser(CreateUserStatement),
583 /// `DROP USER 'name'` (v4.1). v7.39 (read01 round 58) — `IF EXISTS` is
584 /// carried through: PG skips with a NOTICE rather than erroring.
585 DropUser {
586 name: String,
587 if_exists: bool,
588 },
589 /// v7.39 (RLS) — `SET ROLE { name | NONE | DEFAULT }` / `RESET ROLE`.
590 /// `Some(name)` switches the session's effective role (drives
591 /// `current_user` and RLS enforcement); `None` resets to the login
592 /// identity (the Admin superuser).
593 SetRole(Option<String>),
594 /// v7.39 (read01 round 57) — `GRANT <privs> ON <object> TO <roles>`.
595 Grant(GrantStatement),
596 /// v7.39 (read01 round 57) — `REVOKE [GRANT OPTION FOR] <privs> ON
597 /// <object> FROM <roles>`.
598 Revoke(GrantStatement),
599 /// v7.39 (RLS) — `CREATE POLICY name ON table …`.
600 CreatePolicy(CreatePolicyStatement),
601 /// v7.39 (RLS) — `ALTER POLICY name ON table …`.
602 AlterPolicy(AlterPolicyStatement),
603 /// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
604 DropPolicy(DropPolicyStatement),
605 /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
606 ShowUsers,
607 /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
608 /// single-column text table describing the rewritten plan tree
609 /// for `inner`. `analyze` triggers an actual exec to attach
610 /// observed row counts and elapsed micros to each node.
611 Explain(ExplainStatement),
612 /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
613 /// Synchronous rebuild of an NSW index. With the optional
614 /// encoding clause, every stored cell at the indexed column is
615 /// also re-encoded through `coerce_value` before the new graph
616 /// builds.
617 AlterIndex(AlterIndexStatement),
618 /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
619 /// The only setting in v6.7.2 is `hot_tier_bytes`, which
620 /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
621 /// for the named table.
622 AlterTable(AlterTableStatement),
623 /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
624 /// The catalog row lives in `spg_publications`. Publisher-side
625 /// WAL filtering arrives in v6.1.5.
626 CreatePublication(CreatePublicationStatement),
627 /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
628 /// no-op when the publication does not exist.
629 DropPublication {
630 name: String,
631 /// v7.39 (round 754, F31-B4) — `IF EXISTS` quietly skips a
632 /// missing publication; the bare form refuses with PG's
633 /// sentence (PG18-measured — the old "silent no-op" note on
634 /// the executor was wrong).
635 if_exists: bool,
636 },
637 /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
638 /// publication ordered by name with `(name, scope_summary,
639 /// table_count)` columns. The scope summary is the human-
640 /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
641 /// TABLES EXCEPT …`; `table_count` is `NULL` for the
642 /// `AllTables` scope and the table-list length otherwise.
643 ShowPublications,
644 /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
645 /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
646 /// in `spg_subscriptions`; when the subscription is
647 /// `enabled = true` (default) the server spawns a
648 /// background worker that connects to `conn` and drains the
649 /// requested publication(s) into the local engine.
650 CreateSubscription(CreateSubscriptionStatement),
651 /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
652 /// PUBLICATION, silent no-op when absent. Stops the
653 /// associated worker thread before removing the row.
654 DropSubscription {
655 name: String,
656 /// v7.39 (round 754, F31-B4) — same contract as
657 /// [`Statement::DropPublication`].
658 if_exists: bool,
659 },
660 /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
661 /// subscription ordered by name with `(name, conn_str,
662 /// publications, enabled, last_received_pos)`.
663 ShowSubscriptions,
664 /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
665 /// Blocks until the local server's apply position reaches
666 /// `<pos>` or `<ms>` elapses. Server-layer command: the
667 /// engine refuses it (`EngineError::Unsupported`) since
668 /// `lag_state` lives in `spg-server`'s `ServerState`.
669 WaitForWalPosition {
670 pos: u64,
671 /// `None` → wait forever; `Some(ms)` → return after `ms`
672 /// milliseconds even if the target isn't reached.
673 timeout_ms: Option<u64>,
674 },
675 /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
676 /// table; `ANALYZE <name>` re-stats just one. Populates
677 /// `spg_statistic` with per-column null_frac + n_distinct +
678 /// 100-bucket equi-depth histogram.
679 Analyze(Option<String>),
680 /// v7.39.9 — MySQL's top-level `RENAME TABLE a TO b [, c TO d]`.
681 /// PostgreSQL has only `ALTER TABLE … RENAME TO`, so this spelling
682 /// had nowhere to go; it is what a MySQL migration writes.
683 RenameTables(Vec<(String, String)>),
684 /// v7.39 (round 535) — `REINDEX { INDEX | TABLE | SCHEMA | DATABASE
685 /// | SYSTEM } [CONCURRENTLY] <name>` and `CLUSTER [VERBOSE]
686 /// [<table> [USING <index>]]`.
687 ///
688 /// SPG has neither index bloat nor a clustering order to rebuild, so
689 /// the work is a no-op — but PG VALIDATES the target, and both were
690 /// swallowed at parse time, so `REINDEX TABLE typo` reported success.
691 /// The name is carried now so the engine can say what PG says.
692 Maintain {
693 kind: MaintainKind,
694 /// `REINDEX … CONCURRENTLY`. Carried for the same reason as
695 /// [`CreateIndexStatement::concurrently`]: PG bars the
696 /// CONCURRENTLY form inside a transaction block and allows the
697 /// plain one.
698 concurrently: bool,
699 /// `None` for the whole-database forms, which name nothing.
700 target: Option<String>,
701 },
702 /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] [ONLY] <name>
703 /// [, ...] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE |
704 /// RESTRICT]`. Clears every row from each named table. SPG's
705 /// SEQUENCE identity is per-table; RESTART IDENTITY reinitializes
706 /// the associated sequence to its starting value. CASCADE
707 /// currently walks direct FK-referring tables and truncates
708 /// them too (PG's semantics). The ONLY modifier (skip partitions)
709 /// and RESTRICT (default) are accepted with no effect since
710 /// SPG's declarative partitions are always truncated together.
711 Truncate {
712 tables: Vec<String>,
713 restart_identity: bool,
714 cascade: bool,
715 /// v7.39 (round 647) — `TRUNCATE ONLY t`. Absorbed as a no-op
716 /// since v7.14 on the reasoning that SPG's children are separate
717 /// relations a truncate does not descend into. Same reasoning
718 /// round 621 applied to `FROM ONLY`, and it stopped being true
719 /// for the same reason: measured, `TRUNCATE <inheritance parent>`
720 /// leaves the children's rows where PG empties them, and
721 /// `TRUNCATE ONLY <partitioned parent>` is silently accepted
722 /// where PG refuses it outright.
723 only: bool,
724 },
725 /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
726 /// BTree-cold indices and merges small cold-tier segments
727 /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
728 /// 4 MiB) into a single larger segment per (table, index).
729 /// `WHERE` predicate filtering on which tables to compact is
730 /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
731 /// v6.7.3 only supports the bare form.
732 CompactColdSegments,
733 /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
734 /// parameter on the engine; v7.12.1 honours
735 /// `default_text_search_config` (consumed by `to_tsvector` /
736 /// `plainto_tsquery` family when called without an explicit
737 /// config arg). All other names are accepted as a no-op so PG
738 /// dumps with `SET client_encoding`, `SET search_path` etc.
739 /// load cleanly.
740 SetParameter {
741 name: String,
742 value: SetValue,
743 /// v7.38 (read01 P3.19) — `SET LOCAL` scopes the change to the
744 /// current transaction; the engine saves the prior value and
745 /// restores it at COMMIT / ROLLBACK. Plain `SET` (and `SET
746 /// SESSION`) leave this false and persist for the session.
747 local: bool,
748 },
749 /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
750 /// multi-assignment (mysqldump preamble uses
751 /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
752 /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
753 /// source order. Pairs whose LHS is a MySQL session/user
754 /// variable (`@VAR` / `@@VAR`) are recorded with the raw
755 /// name so the engine can ignore them; pairs whose LHS is
756 /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
757 /// go through the regular `set_session_param` path.
758 SetParameterList(Vec<(String, SetValue)>),
759 /// v7.39 (round 430) — MySQL's USER-defined variables:
760 /// `SET @x = 5, @s := CONCAT('a','b')`. Distinct from
761 /// [`Self::SetParameter`] (a `@@`-style engine/session setting) in
762 /// every way that matters: the value is an arbitrary EXPRESSION, the
763 /// name lives in its own per-session namespace, and reading an unset
764 /// one answers NULL rather than raising. `:=` and `=` are the same
765 /// assignment here.
766 ///
767 /// Before this the parser stripped every `@`, so `@x` and `@@x` were
768 /// the same node: `SET @x = 5` silently landed in the session-parameter
769 /// store where nothing could read it back, and `SELECT @x` failed with
770 /// "Unknown system variable".
771 /// v7.39 (round 554) — `SET @a = …, SETTING = …`.
772 ///
773 /// `settings` is the trailing half a mysqldump preamble writes:
774 /// `SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'`
775 /// saves a value and changes it in one statement. The parser used
776 /// to refuse the mixture outright, so no mysqldump could be
777 /// restored past its preamble.
778 SetUserVars(Vec<(String, Expr)>, Vec<(String, Expr)>),
779 /// v7.38 轴 4 — `SET [SESSION] TRANSACTION ISOLATION LEVEL …`
780 /// (plus optional READ ONLY / READ WRITE / DEFERRABLE clauses
781 /// silently accepted). PG-standard surface for picking an
782 /// isolation level. Engine tracks the value on
783 /// `Engine::current_isolation_level()`; actual MVCC / SSI
784 /// semantics implementation lands separately. PG itself maps
785 /// READ UNCOMMITTED to READ COMMITTED; SPG mirrors that —
786 /// effectively every level reads as READ COMMITTED in v7.37.8.
787 SetTransaction {
788 modes: TransactionModes,
789 },
790 /// v7.38 轴 4 — `SHOW <param>` returns a 1-column 1-row result
791 /// with the parameter's current value as TEXT. Today the only
792 /// recognised param is `transaction_isolation`; further
793 /// surfaces (`search_path`, `application_name`, …) land as the
794 /// session-parameter inventory grows.
795 ShowParameter(String),
796 /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
797 /// to its default. No-op for parameters SPG does not track.
798 ResetParameter(Option<String>),
799 /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
800 /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
801 /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
802 /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
803 /// languages parse but error at exec time with a clear
804 /// unsupported message.
805 CreateFunction(CreateFunctionStatement),
806 /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
807 /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
808 /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
809 /// triggers and column-list / WHEN clauses are out of scope
810 /// for v7.12.4.
811 CreateTrigger(CreateTriggerStatement),
812 /// v7.39 (round 139) — `CREATE RULE name AS ON event TO table [WHERE cond]
813 /// DO [ALSO|INSTEAD] { NOTHING | command }` query-rewrite rule.
814 CreateRule(CreateRuleStatement),
815 /// v7.39 (round 139) — `DROP RULE [IF EXISTS] name ON table`.
816 DropRule {
817 name: String,
818 table: String,
819 if_exists: bool,
820 },
821 /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
822 /// no-op when missing if `IF EXISTS` is set.
823 DropTrigger {
824 name: String,
825 table: String,
826 if_exists: bool,
827 },
828 /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
829 /// DROP TRIGGER but global (no table scope).
830 DropFunction {
831 name: String,
832 /// v7.39 (read01 round 62) — the argument TYPES, when the statement gave
833 /// them: `DROP FUNCTION f(int)` drops that overload only. `None` = no
834 /// argument list, which PG accepts only when the name is unambiguous.
835 args: Option<Vec<String>>,
836 if_exists: bool,
837 },
838 /// v7.17.0 — `CREATE [TEMPORARY] SEQUENCE [IF NOT EXISTS] name
839 /// [AS data_type]
840 /// [INCREMENT [BY] n]
841 /// [MINVALUE n | NO MINVALUE]
842 /// [MAXVALUE n | NO MAXVALUE]
843 /// [START [WITH] n]
844 /// [CACHE n]
845 /// [[NO] CYCLE]
846 /// [OWNED BY {table.col | NONE}]`.
847 /// Closes the round-7+ silent-no-op SEQUENCE story so pg_dump
848 /// emits + nextval/currval/setval downstream all work.
849 CreateSequence(CreateSequenceStatement),
850 /// v7.17.0 — `ALTER SEQUENCE [IF EXISTS] name <options>` with
851 /// the same option grammar as CREATE SEQUENCE, plus
852 /// `RESTART [WITH n]` and `OWNED BY ...` re-attach.
853 AlterSequence(AlterSequenceStatement),
854 /// v7.17.0 — `DROP SEQUENCE [IF EXISTS] name [, name…]
855 /// [CASCADE | RESTRICT]`. CASCADE / RESTRICT trailers parsed
856 /// silently (no FK on sequences).
857 DropSequence {
858 names: Vec<String>,
859 if_exists: bool,
860 },
861 /// v7.17.0 Phase 1.2 — `CREATE [OR REPLACE] [TEMPORARY] VIEW
862 /// [IF NOT EXISTS] name [(col, …)] AS <SELECT …>`. Closes the
863 /// silent-no-op VIEW story from the v7.17 customer-readiness
864 /// audit: pre-v7.17 SPG parsed CREATE VIEW as Statement::Empty
865 /// so any downstream `SELECT FROM v` errored with table-not-
866 /// found. The view body is stored verbatim; SELECT FROM <v>
867 /// rewrites at exec-time by prepending the view body as a
868 /// synthetic CTE.
869 CreateView(CreateViewStatement),
870 /// v7.17.0 Phase 1.2 — `DROP VIEW [IF EXISTS] name [, name…]
871 /// [CASCADE | RESTRICT]`. Removes the matching view from the
872 /// catalog; CASCADE/RESTRICT parsed silently.
873 DropView {
874 names: Vec<String>,
875 if_exists: bool,
876 },
877 /// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW [IF NOT
878 /// EXISTS] name [(col, …)] AS <SELECT …> [WITH [NO] DATA]`.
879 /// Closes the silent-no-op MATERIALIZED VIEW story. Storage
880 /// model: the materialised result lives as a regular table
881 /// with the matching name + a parallel
882 /// `materialized_views` registry mapping name → body source
883 /// (used by REFRESH).
884 CreateMaterializedView(CreateMaterializedViewStatement),
885 /// v7.17.0 Phase 1.3 — `REFRESH MATERIALIZED VIEW name [WITH
886 /// [NO] DATA]`. Re-runs the stored body and replaces the
887 /// cached rows. `WITH NO DATA` truncates without re-running.
888 RefreshMaterializedView {
889 name: String,
890 with_data: bool,
891 },
892 /// v7.17.0 Phase 1.3 — `DROP MATERIALIZED VIEW [IF EXISTS]
893 /// name [, name…] [CASCADE | RESTRICT]`. Drops both the
894 /// backing table and the source registry entry.
895 DropMaterializedView {
896 names: Vec<String>,
897 if_exists: bool,
898 },
899 /// v7.17.0 Phase 1.4 — `CREATE TYPE name AS ENUM ('a', 'b',
900 /// …)`. Closes the silent-no-op CREATE TYPE story so PG
901 /// dumps that declare enum types load with real constraints
902 /// instead of becoming free-form TEXT. Future kinds
903 /// (composite / range / domain) extend the inner `kind`
904 /// enum.
905 CreateType(CreateTypeStatement),
906 /// v7.37 D.55 — `ALTER TYPE name ADD VALUE [IF NOT EXISTS] 'label'
907 /// [{BEFORE | AFTER} 'existing']`. Extends an enum's label list so
908 /// enum evolution stops being a silent no-op. `position` is
909 /// `Some((is_before, anchor))`.
910 /// v7.39 (read01 round 49) — `ALTER TYPE t RENAME VALUE 'old' TO 'new'`.
911 /// Used to be swallowed by the ALTER TYPE no-op tail, so the rename was
912 /// accepted and silently ignored.
913 /// v7.39 (read01 round 50) — `COMMENT ON <kind> <name> IS { 'text' | NULL }`.
914 /// Used to be swallowed as dump noise, so a comment was accepted and lost
915 /// (and obj_description / col_description always returned NULL).
916 /// `kind` is lowercase ("table" / "column" / "index" / …); for a column
917 /// `name` is the dotted `table.column`. `comment: None` = `IS NULL` = remove.
918 CommentOn {
919 kind: String,
920 name: String,
921 comment: Option<String>,
922 },
923 AlterTypeRenameValue {
924 type_name: String,
925 old: String,
926 new: String,
927 },
928 AlterTypeAddValue {
929 type_name: String,
930 label: String,
931 if_not_exists: bool,
932 position: Option<(bool, String)>,
933 },
934 /// v7.17.0 Phase 1.4 — `DROP TYPE [IF EXISTS] name [, name…]
935 /// [CASCADE | RESTRICT]`. Removes the matching enum/domain
936 /// from the catalog.
937 DropType {
938 names: Vec<String>,
939 if_exists: bool,
940 },
941 /// v7.17.0 Phase 1.5 — `CREATE DOMAIN name AS base_type
942 /// [DEFAULT expr] [NOT NULL | NULL] [CHECK (expr)]*`.
943 /// A DOMAIN is a named CHECK-constrained alias over a built-
944 /// in type. The CHECK + NOT NULL + DEFAULT clauses apply to
945 /// every column declared with the domain. Closes the
946 /// silent-no-op CREATE DOMAIN story so PG dumps that ship
947 /// validated identifier types (email, positive_int, …) keep
948 /// their guarantees.
949 CreateDomain(CreateDomainStatement),
950 /// v7.39 (round 260) — `ALTER DOMAIN name <action>`. Every form was
951 /// previously swallowed by the catch-all DDL arm: the statement
952 /// reported success and did nothing, so a migration that dropped a
953 /// constraint kept rejecting the data it had just been told to
954 /// accept.
955 AlterDomain {
956 name: String,
957 action: AlterDomainAction,
958 },
959 /// v7.17.0 Phase 1.5 — `DROP DOMAIN [IF EXISTS] name
960 /// [, name…] [CASCADE | RESTRICT]`. Removes the matching
961 /// domain from the catalog.
962 DropDomain {
963 names: Vec<String>,
964 if_exists: bool,
965 },
966 /// v7.17.0 Phase 1.6 — `CREATE SCHEMA [IF NOT EXISTS]
967 /// name [AUTHORIZATION user]`. SPG is single-database;
968 /// schemas are tracked as a namespace registry so pg_dump
969 /// multi-schema declarations land cleanly and `SELECT *
970 /// FROM information_schema.schemata` returns real entries.
971 /// Schema-qualified `schema.table` references still strip
972 /// the prefix at lookup time per PG (schemas are not
973 /// isolation boundaries in v7.17 — see project-next-docket
974 /// for the v7.18+ isolation tracking).
975 CreateSchema {
976 name: String,
977 if_not_exists: bool,
978 },
979 /// v7.17.0 Phase 1.6 — `DROP SCHEMA [IF EXISTS] name
980 /// [, name…] [CASCADE | RESTRICT]`. Removes the schema
981 /// from the registry; built-in `public` / `pg_catalog` /
982 /// `information_schema` cannot be dropped.
983 DropSchema {
984 names: Vec<String>,
985 if_exists: bool,
986 },
987}
988
989/// v7.39 (round 260) — the `ALTER DOMAIN` actions SPG implements.
990#[derive(Debug, Clone, PartialEq)]
991pub enum AlterDomainAction {
992 AddConstraint { name: Option<String>, check: Expr },
993 DropConstraint { name: String, if_exists: bool },
994 SetDefault(Expr),
995 DropDefault,
996 SetNotNull,
997 DropNotNull,
998 RenameTo(String),
999}
1000
1001/// v7.17.0 Phase 1.5 — `CREATE DOMAIN` AST.
1002#[derive(Debug, Clone, PartialEq)]
1003pub struct CreateDomainStatement {
1004 pub name: String,
1005 /// Base type for the domain (one of the built-in
1006 /// `ColumnTypeName` variants).
1007 pub base_type: ColumnTypeName,
1008 /// v7.39 (round 259) — `CREATE DOMAIN child AS parent …` where
1009 /// `parent` is itself a DOMAIN. The parser already captured the
1010 /// unknown type name; it just was not carried here, so the parent's
1011 /// CHECK constraints were invisible and a value violating them was
1012 /// silently accepted. `base_type` still holds the ultimate scalar
1013 /// type, which is what the storage tier stores.
1014 pub base_domain: Option<String>,
1015 /// Optional `DEFAULT <expr>`. Resolved at engine-side
1016 /// CREATE TABLE time when a column is bound to this domain.
1017 pub default: Option<Expr>,
1018 /// `NOT NULL` from the domain definition. Engine ORs this
1019 /// with the column-level nullability so the strictest of the
1020 /// two wins (i.e. the column is non-nullable if either side
1021 /// says so).
1022 pub not_null: bool,
1023 /// Zero-or-more `CHECK (expr)` predicates. Each one is
1024 /// enforced as part of the column's CHECK list at INSERT /
1025 /// UPDATE time, with `VALUE` substituted for the column's
1026 /// current cell value.
1027 pub checks: Vec<Expr>,
1028}
1029
1030/// v7.17.0 Phase 1.4 — `CREATE TYPE` AST.
1031#[derive(Debug, Clone, PartialEq, Eq)]
1032pub struct CreateTypeStatement {
1033 pub name: String,
1034 pub kind: TypeKind,
1035}
1036
1037/// v7.17.0 Phase 1.4 — flavour of the new type. Only ENUM is
1038/// implemented; the variant set is open so Phase 1.5 (DOMAIN)
1039/// and later (COMPOSITE, RANGE) can land without an AST shape
1040/// migration.
1041///
1042/// v7.37.x (ζ-B Phase 1 composite accept) — added Composite for
1043/// `CREATE TYPE name AS (field_name field_type, …)`. Phase 1
1044/// stores the field list in the catalog so PG dumps that emit
1045/// `CREATE TYPE … AS (…)` don't error out; using a composite type
1046/// as a column type lands in Phase 2 (Value::Composite encoding +
1047/// ROW() literal + field-access syntax).
1048#[derive(Debug, Clone, PartialEq, Eq)]
1049pub enum TypeKind {
1050 /// `AS ENUM ('a', 'b', …)`. Order is preserved (PG enum
1051 /// labels are ordered).
1052 Enum { labels: Vec<String> },
1053 /// `AS (field_name field_type, …)`. Order matters; PG
1054 /// composite literals are positional.
1055 Composite {
1056 fields: Vec<(String, ColumnTypeName)>,
1057 /// v7.39 (round 264) — parallel to `fields`: the raw type NAME
1058 /// when a field's type is not a builtin (i.e. another composite).
1059 /// The parser already captures it; without carrying it here a
1060 /// nested composite field resolved to the Text placeholder and
1061 /// the inner record never became a record.
1062 field_user_types: Vec<Option<String>>,
1063 },
1064}
1065
1066/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
1067/// a string literal, an identifier (often a config name), an
1068/// integer/float, or the bare `DEFAULT` keyword.
1069#[derive(Debug, Clone, PartialEq)]
1070pub enum SetValue {
1071 String(String),
1072 Ident(String),
1073 Number(String),
1074 Default,
1075}
1076
1077/// v7.38 轴 4 — PG-standard isolation levels. SPG accepts all four
1078/// at parse time and tracks the selected value on the engine. The
1079/// actual semantic differentiation (REPEATABLE READ snapshot,
1080/// SERIALIZABLE SSI) lands in the v7.38 isolation framework train;
1081/// today every level reads as effective READ COMMITTED (which is
1082/// also how PG treats READ UNCOMMITTED — it silently upgrades to
1083/// READ COMMITTED). Default = `ReadCommitted`.
1084#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1085pub enum IsolationLevel {
1086 ReadUncommitted,
1087 #[default]
1088 ReadCommitted,
1089 RepeatableRead,
1090 Serializable,
1091}
1092
1093impl IsolationLevel {
1094 /// Canonical PG-style display name, as `SHOW transaction_isolation`
1095 /// would return it. v7.39 (round 770, F31 tranche 6 #154) — PG
1096 /// KEEPS the "read uncommitted" label (measured: `BEGIN ISOLATION
1097 /// LEVEL READ UNCOMMITTED; SHOW transaction_isolation` answers
1098 /// `read uncommitted`) and only BEHAVES as read committed; the old
1099 /// fold renamed the label too.
1100 /// v7.39 — the MySQL display name, which is NOT the PG one: MySQL
1101 /// hyphenates and upper-cases. Measured on MySQL 9.7.2 by setting
1102 /// each level and reading `@@transaction_isolation` back:
1103 /// `READ-UNCOMMITTED` / `READ-COMMITTED` / `REPEATABLE-READ` /
1104 /// `SERIALIZABLE` (the last has no hyphen because it is one word).
1105 ///
1106 /// This exists so the two MySQL surfaces cannot drift: both
1107 /// `SHOW VARIABLES` and `@@transaction_isolation` used to carry
1108 /// their own hard-coded literal, and the literals disagreed —
1109 /// one said `REPEATABLE-READ` while the engine ran read committed.
1110 /// v7.39 — parse what `default_transaction_isolation` holds. PG
1111 /// accepts the SQL spellings and stores them lower-cased with a
1112 /// space; anything else is not a level this understands and the
1113 /// caller keeps its own default rather than guessing.
1114 #[must_use]
1115 pub fn from_pg_name(name: &str) -> Option<Self> {
1116 match name.trim().to_ascii_lowercase().as_str() {
1117 "read uncommitted" => Some(Self::ReadUncommitted),
1118 "read committed" => Some(Self::ReadCommitted),
1119 "repeatable read" => Some(Self::RepeatableRead),
1120 "serializable" => Some(Self::Serializable),
1121 _ => None,
1122 }
1123 }
1124
1125 #[must_use]
1126 pub fn as_mysql_str(self) -> &'static str {
1127 match self {
1128 Self::ReadUncommitted => "READ-UNCOMMITTED",
1129 Self::ReadCommitted => "READ-COMMITTED",
1130 Self::RepeatableRead => "REPEATABLE-READ",
1131 Self::Serializable => "SERIALIZABLE",
1132 }
1133 }
1134
1135 pub fn as_pg_str(self) -> &'static str {
1136 match self {
1137 Self::ReadUncommitted => "read uncommitted",
1138 Self::ReadCommitted => "read committed",
1139 Self::RepeatableRead => "repeatable read",
1140 Self::Serializable => "serializable",
1141 }
1142 }
1143}
1144
1145impl core::fmt::Display for IsolationLevel {
1146 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1147 f.write_str(self.as_pg_str())
1148 }
1149}
1150
1151/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
1152/// single fixed-shape DDL; the WITH-clause options PG supports
1153/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
1154/// scope for v6.1.4 — `enabled` defaults to true and there are
1155/// no other knobs to set in v6.1.x.
1156#[derive(Debug, Clone, PartialEq, Eq)]
1157pub struct CreateSubscriptionStatement {
1158 pub name: String,
1159 /// Connection string in PG keyword=value form (e.g.
1160 /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
1161 /// `host` and `port` fields; the rest is reserved for
1162 /// future v6.1.x options.
1163 pub conn_str: String,
1164 /// One or more publications on the remote side. Order is
1165 /// preserved verbatim from the DDL; the worker requests them
1166 /// in this order. v6.1.4 records the list; v6.1.5
1167 /// publisher-side filtering enforces it.
1168 pub publications: Vec<String>,
1169}
1170
1171/// v7.17.0 — `CREATE SEQUENCE` AST node. See [`Statement::CreateSequence`].
1172#[derive(Debug, Clone, PartialEq, Eq)]
1173pub struct CreateSequenceStatement {
1174 pub name: String,
1175 pub if_not_exists: bool,
1176 pub temporary: bool,
1177 /// Optional `AS data_type`. Default in PG is BIGINT; SPG matches.
1178 pub data_type: Option<SequenceDataType>,
1179 pub options: SequenceOptions,
1180}
1181
1182/// v7.17.0 — narrow type for `AS` clause of CREATE SEQUENCE.
1183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1184pub enum SequenceDataType {
1185 SmallInt,
1186 Int,
1187 BigInt,
1188}
1189
1190/// v7.17.0 — option grammar shared by CREATE / ALTER SEQUENCE.
1191/// All fields are optional. `min_value`/`max_value` carry
1192/// `Some(SeqBound::NoBound)` for `NO MINVALUE` / `NO MAXVALUE`.
1193#[derive(Debug, Clone, Default, PartialEq, Eq)]
1194pub struct SequenceOptions {
1195 pub increment: Option<i64>,
1196 pub min_value: Option<SeqBound>,
1197 pub max_value: Option<SeqBound>,
1198 pub start: Option<i64>,
1199 /// `RESTART [WITH n]` — ALTER-only. `Some(None)` = bare
1200 /// RESTART, `Some(Some(n))` = RESTART WITH n.
1201 pub restart: Option<Option<i64>>,
1202 pub cache: Option<i64>,
1203 pub cycle: Option<bool>,
1204 pub owned_by: Option<SequenceOwnedBy>,
1205}
1206
1207/// v7.17.0 — `MINVALUE n` / `NO MINVALUE`.
1208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1209pub enum SeqBound {
1210 Value(i64),
1211 NoBound,
1212}
1213
1214/// v7.17.0 — `OWNED BY {table.col | NONE}`.
1215#[derive(Debug, Clone, PartialEq, Eq)]
1216pub enum SequenceOwnedBy {
1217 None,
1218 Column { table: String, column: String },
1219}
1220
1221/// v7.17.0 Phase 1.3 — `CREATE MATERIALIZED VIEW` AST node.
1222#[derive(Debug, Clone, PartialEq)]
1223pub struct CreateMaterializedViewStatement {
1224 pub name: String,
1225 pub if_not_exists: bool,
1226 /// Optional `(col, col, …)` rename list. Applies to the
1227 /// backing table at CREATE / REFRESH time.
1228 pub columns: Vec<String>,
1229 /// Underlying SELECT. Re-parsed at REFRESH time to rebuild
1230 /// the cached rows.
1231 pub body: SelectStatement,
1232 /// `WITH DATA` (default) = materialise the rows at CREATE
1233 /// time. `WITH NO DATA` = create an empty backing table;
1234 /// callers must REFRESH before SELECT returns rows.
1235 pub with_data: bool,
1236 /// v7.38 (read01 P6.49) — when true this node came from
1237 /// `CREATE TABLE … AS <select>` (CTAS) / `SELECT … INTO`, so the
1238 /// executor creates a plain table and does NOT register it in the
1239 /// materialized-view registry (no REFRESH semantics).
1240 pub as_plain_table: bool,
1241 /// v7.39 (round 436) — `CREATE TEMPORARY TABLE … AS <select>`. Only
1242 /// meaningful together with `as_plain_table`; the executor puts the
1243 /// resulting table in the creating session's namespace.
1244 pub temporary: bool,
1245}
1246
1247/// v7.39 (read01 round 132) — `WITH [LOCAL | CASCADED] CHECK OPTION` on an
1248/// auto-updatable view. `Cascaded` is PG's default when the bare
1249/// `WITH CHECK OPTION` is written.
1250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1251pub enum ViewCheckOption {
1252 Local,
1253 Cascaded,
1254}
1255
1256/// v7.17.0 Phase 1.2 — `CREATE VIEW` AST node.
1257#[derive(Debug, Clone, PartialEq)]
1258pub struct CreateViewStatement {
1259 pub name: String,
1260 pub or_replace: bool,
1261 pub if_not_exists: bool,
1262 pub temporary: bool,
1263 /// Optional `(col, col, …)` rename list. When non-empty,
1264 /// these override the body's projected column names per-
1265 /// position at SELECT-from-view time.
1266 pub columns: Vec<String>,
1267 /// Underlying SELECT. Re-parsed lazily at SELECT-from-view
1268 /// time to materialise the view as a synthetic CTE.
1269 pub body: SelectStatement,
1270 /// v7.39 (round 132) — `WITH CHECK OPTION`. When set, a write through this
1271 /// view whose resulting row fails the view's WHERE is rejected (SQLSTATE
1272 /// 44000). `None` = no check option.
1273 pub check_option: Option<ViewCheckOption>,
1274}
1275
1276/// v7.17.0 — `ALTER SEQUENCE` AST node.
1277#[derive(Debug, Clone, PartialEq, Eq)]
1278pub struct AlterSequenceStatement {
1279 pub name: String,
1280 pub if_exists: bool,
1281 pub options: SequenceOptions,
1282 /// v7.39 (read01 round 49) — `ALTER SEQUENCE old RENAME TO new`. Set
1283 /// instead of `options`; the two forms are mutually exclusive in PG.
1284 pub rename_to: Option<String>,
1285}
1286
1287/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
1288/// the [`PublicationScope`] shape. v6.1.2 only accepted
1289/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
1290/// variants by flipping the parser gate (no AST migration).
1291#[derive(Debug, Clone, PartialEq, Eq)]
1292pub struct CreatePublicationStatement {
1293 pub name: String,
1294 pub scope: PublicationScope,
1295}
1296
1297/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
1298/// flips the parser gate for the `ForTables` / `AllTablesExcept`
1299/// variants — the on-disk shape, snapshot serialisation, and the
1300/// AST round-trip Display path were already in place in v6.1.2
1301/// so this is a parser-only widening.
1302#[derive(Debug, Clone, PartialEq, Eq)]
1303pub enum PublicationScope {
1304 AllTables,
1305 ForTables(Vec<String>),
1306 AllTablesExcept(Vec<String>),
1307 /// v7.39 (round 754, F31-B5) — `FOR TABLES IN SCHEMA <name>`
1308 /// (PG 15+). AST-only: the executor folds `public` to
1309 /// [`PublicationScope::AllTables`] (SPG's single-schema world)
1310 /// and refuses any other schema with PG's sentence, so the
1311 /// catalog / serializer / replication filter never see it.
1312 TablesInSchema(String),
1313}
1314
1315#[derive(Debug, Clone, PartialEq, Eq)]
1316pub struct AlterIndexStatement {
1317 pub name: String,
1318 pub target: AlterIndexTarget,
1319}
1320
1321#[derive(Debug, Clone, PartialEq, Eq)]
1322pub enum AlterIndexTarget {
1323 /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
1324 /// rebuilds the existing graph in place without touching the
1325 /// column encoding; `Some(enc)` re-encodes every cell first.
1326 Rebuild { encoding: Option<VecEncoding> },
1327 /// v7.16.2 — `[IF EXISTS] RENAME TO <new>`. mailrs migrate-042
1328 /// uses this; PG drops the IF EXISTS noisily as ERROR, mailrs
1329 /// uses it to make the migration idempotent (re-running on a
1330 /// DB where the rename already happened is a no-op rather
1331 /// than an error).
1332 Rename { new: String, if_exists: bool },
1333 /// v7.39 (round 710) — `SET ( option = value, … )` / `RESET ( … )`.
1334 /// Was a SYNTAX ERROR; PG resolves the INDEX first (`relation "x"
1335 /// does not exist`), so the index is validated and the storage
1336 /// parameters no-op (SPG engine-manages them, as ALTER TABLE's
1337 /// SET/RESET arms already record).
1338 StorageParams,
1339}
1340
1341/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
1342/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
1343/// can add more SET subjects without changing the dispatch shape.
1344#[derive(Debug, Clone, PartialEq)]
1345pub struct AlterTableStatement {
1346 pub name: String,
1347 /// v7.13.2 — mailrs round-6 S1. One or more subactions
1348 /// separated by commas in the source SQL. PG-semantic apply
1349 /// is sequential; engine bails on first error (no
1350 /// transactional rollback of completed subactions in v7.13).
1351 /// Single-subaction shape stays a 1-element vec.
1352 pub targets: Vec<AlterTableTarget>,
1353}
1354/// v7.39.9 — the `FIRST` / `AFTER c` trailer, written back the way it
1355/// was read.
1356fn write_column_position(
1357 f: &mut core::fmt::Formatter<'_>,
1358 pos: Option<&ColumnPosition>,
1359) -> core::fmt::Result {
1360 match pos {
1361 Some(ColumnPosition::First) => f.write_str(" FIRST"),
1362 Some(ColumnPosition::After(c)) => write!(f, " AFTER {}", quote_ident(c)),
1363 None => Ok(()),
1364 }
1365}
1366
1367/// v7.39.9 — where MySQL's `ADD` / `MODIFY` / `CHANGE` puts a column.
1368///
1369/// The row encoding is positional and `SELECT *` reads it in order, so
1370/// this is an answer, not a formatting preference.
1371#[derive(Debug, Clone, PartialEq, Eq)]
1372pub enum ColumnPosition {
1373 First,
1374 After(String),
1375}
1376
1377#[derive(Debug, Clone, PartialEq)]
1378#[allow(clippy::large_enum_variant)]
1379pub enum AlterTableTarget {
1380 /// v7.39 (round 647) — `ALTER TABLE c INHERIT p` / `NO INHERIT p`.
1381 ///
1382 /// Both were accepted-and-ignored since v7.37.18, on the reasoning
1383 /// that SPG has no PG-style inheritance. Round 645 gave it one, and
1384 /// the reasoning went stale: `NO INHERIT` reported success while the
1385 /// child stayed attached, which is the worst kind of answer — the
1386 /// statement says it worked and the catalog disagrees.
1387 Inherit { parent: String, detach: bool },
1388 /// Per-table hot-tier byte budget override. The freezer
1389 /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
1390 SetHotTierBytes(u64),
1391 /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
1392 /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
1393 /// Engine validates existing rows against the new constraint
1394 /// before installing it.
1395 AddForeignKey(ForeignKeyConstraint),
1396 /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
1397 /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
1398 /// no-op when no FK with that name exists; otherwise raises.
1399 DropForeignKey { name: String, if_exists: bool },
1400 /// v7.39 (round 431) — MySQL's `ALTER TABLE t DROP {INDEX|KEY} name`,
1401 /// the counterpart of `ADD INDEX`. Lowers to the same catalog action
1402 /// as the standalone `DROP INDEX` statement.
1403 DropIndex { name: String, if_exists: bool },
1404 /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
1405 /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
1406 /// (20 migrate-*.sql hits). Engine appends the column to the
1407 /// schema and back-fills every existing row with the DEFAULT
1408 /// (or NULL when no DEFAULT and the column is nullable).
1409 AddColumn {
1410 column: ColumnDef,
1411 if_not_exists: bool,
1412 /// v7.39.9 — MySQL's `FIRST` / `AFTER <col>`, which say where
1413 /// the column goes. `None` is the PostgreSQL form and appends.
1414 position: Option<ColumnPosition>,
1415 },
1416 /// v7.39.9 — MySQL's `MODIFY COLUMN c <definition>` and
1417 /// `CHANGE COLUMN old new <definition>`.
1418 ///
1419 /// Both REPLACE the column's definition rather than amending it,
1420 /// which is the part that cannot be expressed by the PostgreSQL
1421 /// spellings SPG already had. Measured on MySQL 9.7.2: a column
1422 /// declared `INT NOT NULL DEFAULT 5`, after `MODIFY COLUMN b
1423 /// BIGINT`, is `bigint` NULLABLE with NO default — restating them
1424 /// keeps them, omitting them drops them. `CHANGE` is the same and
1425 /// also renames.
1426 ModifyColumn {
1427 /// The column as it is named now.
1428 column: String,
1429 /// `CHANGE`'s new name; `None` for `MODIFY`, which keeps it.
1430 rename_to: Option<String>,
1431 /// The whole new definition, exactly as written.
1432 definition: ColumnDef,
1433 position: Option<ColumnPosition>,
1434 },
1435 /// v7.39.9 — MySQL's `RENAME {INDEX|KEY} old TO new`.
1436 RenameIndex { old: String, new: String },
1437 /// v7.39.9 — MySQL's `ALTER TABLE t AUTO_INCREMENT = n`, which sets
1438 /// the value the NEXT insert takes. Measured on 9.7.2: after
1439 /// `= 100`, the next row's id is 100.
1440 SetTableAutoIncrement(i64),
1441 /// v7.39.9 — MySQL's `ENGINE = <name>`. SPG has one storage engine
1442 /// and substitutes for every name MySQL knows, exactly as
1443 /// `CREATE TABLE` already does; a name MySQL does not know is
1444 /// refused with its 1286, because a typo in a migration must not
1445 /// quietly become SPG's storage.
1446 SetEngine(String),
1447 /// v7.39.9 — MySQL's `CONVERT TO CHARACTER SET <cs> [COLLATE <c>]`.
1448 /// SPG stores UTF-8 throughout, so a charset it can represent is
1449 /// accepted and one it cannot is refused with MySQL's 1115.
1450 ConvertToCharacterSet {
1451 charset: String,
1452 collate: Option<String>,
1453 },
1454 /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
1455 /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
1456 /// existing row's column value by evaluating the optional
1457 /// USING expression (default `col::<ty>`) and re-coercing
1458 /// against the new column type.
1459 AlterColumnType {
1460 column: String,
1461 new_type: ColumnTypeName,
1462 using: Option<Expr>,
1463 /// v7.39 (round 713) — `COLLATE <name>` between the type and
1464 /// USING. PG re-collates the column, and an ABSENT clause RESETS
1465 /// the collation to the type default (measured round 713) — so
1466 /// `None` is not "leave it alone". The type parser consumed the
1467 /// clause all along and this surface dropped it on the floor:
1468 /// the statement succeeded and the ordering did not change, the
1469 /// silent-divergence shape. Folded variant + the name as written.
1470 collation: Option<(Collation, String)>,
1471 },
1472 /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
1473 /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
1474 /// every row's value at that position is removed; any index
1475 /// on the column is dropped. `if_exists` makes the drop a
1476 /// no-op when the column is missing. `cascade` removes
1477 /// dependents (FKs referencing the column, partial indexes
1478 /// whose predicate names the column); without it, the engine
1479 /// rejects when dependents exist.
1480 DropColumn {
1481 column: String,
1482 if_exists: bool,
1483 cascade: bool,
1484 },
1485 /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
1486 /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
1487 /// CONSTRAINT name CHECK (expr)` — table-level constraints
1488 /// installed post-CREATE-TABLE. pg_dump emits PKs as a
1489 /// separate ALTER TABLE statement, so this surface lets the
1490 /// dump load straight through.
1491 AddTableConstraint(TableConstraint),
1492 /// v7.39 (round 652) — `OWNER TO <role>`. SPG is single-owner, so
1493 /// there is nothing to record; what PG does that SPG did not is
1494 /// REFUSE a role that does not exist. The name has to reach the
1495 /// engine for that, because only the engine knows the roles.
1496 OwnerTo { role: String },
1497 /// v7.39 (round 652) — `CLUSTER ON <index>` and `SET WITHOUT
1498 /// CLUSTER` (the latter as `None`). SPG has no clustered storage, so
1499 /// the hint is still a no-op; naming an index that does not exist is
1500 /// not.
1501 ClusterOn { index: Option<String> },
1502 /// v7.39 (round 652) — `VALIDATE CONSTRAINT <name>`: scan the rows
1503 /// already in the table against a constraint added `NOT VALID` and,
1504 /// if they all pass, mark it validated. It used to be swallowed as a
1505 /// no-op on the theory that SPG validated at ADD time; SPG did not.
1506 ValidateConstraint { name: String },
1507 /// v7.15.0 — `ALTER TABLE t RENAME [COLUMN] old TO new`.
1508 /// Renames the column in the schema and propagates the rename
1509 /// to every stored source string that references it as a
1510 /// (potentially-qualified) column identifier: CHECK predicates,
1511 /// partial-index predicates, runtime DEFAULT expressions, and
1512 /// triggers' `UPDATE OF` column lists. Function bodies and
1513 /// trigger bodies are NOT auto-rewritten — they're loose
1514 /// source text and may contain references SPG can't statically
1515 /// resolve to this column (NEW./OLD. + dynamic SQL). Renames
1516 /// the column even if dependents exist; users renaming a
1517 /// column referenced by a function body update the function
1518 /// body separately.
1519 RenameColumn { old: String, new: String },
1520 /// v7.39 (read01 round 48) — `ALTER TABLE t RENAME CONSTRAINT old TO new`.
1521 /// Reachable now that the schema stores user-supplied constraint names.
1522 RenameConstraint { old: String, new: String },
1523 /// v7.22 (round-13 T2) — mark a column auto-incrementing.
1524 /// pg_dump splits SERIAL/IDENTITY columns into a plain integer
1525 /// column plus either `ALTER COLUMN c SET DEFAULT nextval(…)`
1526 /// (serial) or `ALTER COLUMN c ADD GENERATED … AS IDENTITY (…)`
1527 /// (identity); both lower to this. SPG's auto-increment is
1528 /// max+1-scan based, so the dump's `setval(…)` calls stay
1529 /// no-ops without losing the sequence position.
1530 SetColumnAutoIncrement {
1531 column: String,
1532 /// The implicit sequence pg_dump names for an identity
1533 /// column (`ADD GENERATED … ( SEQUENCE NAME s … )`) or the
1534 /// nextval target for a serial default. The engine creates
1535 /// it if absent so the dump's later `setval(s, …)` lands.
1536 seq_name: Option<String>,
1537 },
1538 /// v7.16.2 — `ALTER TABLE old RENAME TO new`. Renames the
1539 /// table itself (mailrs round-10 A.5 carve-out — mailrs's
1540 /// migrate-042 uses it). The engine moves the table entry
1541 /// in the catalog under the new name; child catalog state
1542 /// (FKs pointing at this table, triggers watching this
1543 /// table) tracks the rename through the storage layer.
1544 RenameTable { new: String },
1545 /// v7.16.1 — `ALTER TABLE t { ENABLE | DISABLE } TRIGGER
1546 /// { ALL | <name> }`. Toggles whether row-level triggers
1547 /// fire on subsequent INSERT/UPDATE/DELETE on the table.
1548 /// `pg_dump --disable-triggers` emits a DISABLE wrapper +
1549 /// ENABLE epilogue around every table's data block so the
1550 /// rows already-computed in prod don't get re-rewritten
1551 /// (and so trigger-driven side effects like
1552 /// audit/queueing don't re-fire during a bulk reload).
1553 /// `which == TriggerSelector::All` toggles every trigger
1554 /// on the table; `Named(name)` toggles one trigger. The
1555 /// engine persists the disabled state on `TriggerDef.enabled`
1556 /// (catalog FILE_VERSION 25+) and the row-write paths skip
1557 /// the trigger when `!enabled`.
1558 SetTriggerEnabled {
1559 which: TriggerSelector,
1560 enabled: bool,
1561 },
1562 /// v7.39 (RLS) — `ALTER TABLE t { ENABLE | DISABLE | FORCE | NO FORCE }
1563 /// ROW LEVEL SECURITY`. `enabled` = Some for ENABLE/DISABLE (sets
1564 /// `relrowsecurity`); `force` = Some for FORCE/NO FORCE (sets
1565 /// `relforcerowsecurity`). Exactly one is `Some` per statement.
1566 SetRowSecurity {
1567 enabled: Option<bool>,
1568 force: Option<bool>,
1569 },
1570 /// v7.37.16 (16.3) — `ALTER TABLE parent ATTACH PARTITION child
1571 /// <bounds>`. Promotes an existing table `child` to a partition
1572 /// of `parent` using PG-style `FOR VALUES …` / `DEFAULT` bounds.
1573 /// Engine validates that `child`'s columns are layout-compatible
1574 /// with `parent` and that every row in `child` satisfies the
1575 /// bound before installing the role.
1576 AttachPartition {
1577 child: String,
1578 bounds: PartitionOfBoundsAst,
1579 },
1580 /// v7.37.16 (16.4 + 16.5) — `ALTER TABLE parent DETACH PARTITION
1581 /// child [CONCURRENTLY] [FINALIZE]`. Demotes a partition back
1582 /// to a standalone table (clears `partition_role`) and removes
1583 /// it from the parent's child set. v7.37.16.5: `CONCURRENTLY`
1584 /// is parser-accepted; engine performs the same atomic detach
1585 /// (single-engine, no replication lag — the PG semantics that
1586 /// require the two-phase split don't apply).
1587 DetachPartition {
1588 child: String,
1589 concurrently: bool,
1590 finalize: bool,
1591 },
1592 /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col SET DEFAULT
1593 /// <expr>`. Engine re-parses + freezes the literal at this point,
1594 /// matching CREATE TABLE-side default semantics. Volatile shapes
1595 /// (`now()` / `nextval`) take the runtime-default path.
1596 AlterColumnSetDefault { column: String, default_expr: Expr },
1597 /// v7.37.18 (18.1) — `ALTER TABLE … ALTER COLUMN col DROP DEFAULT`.
1598 AlterColumnDropDefault { column: String },
1599 /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col SET NOT NULL`.
1600 /// Engine validates that no existing row has NULL in that column
1601 /// before flipping the flag (PG semantics — partial NOT NULL
1602 /// would surface inconsistently).
1603 AlterColumnSetNotNull { column: String },
1604 /// v7.37.18 (18.2) — `ALTER TABLE … ALTER COLUMN col DROP NOT NULL`.
1605 AlterColumnDropNotNull { column: String },
1606 /// v7.39 (round 220) — `ALTER TABLE … ALTER COLUMN col RESTART
1607 /// [WITH n]` on an identity column (`None` = bare RESTART, from the
1608 /// column's start value = 1). Engine records a next-value floor over
1609 /// SPG's max+1 identity allocation.
1610 AlterColumnRestart { column: String, with: Option<i64> },
1611 /// v7.38 (read01 U10) — `ALTER TABLE … ALTER COLUMN col DROP
1612 /// EXPRESSION` turns a stored generated column into a plain column
1613 /// (its generation expression is removed; existing values are kept).
1614 AlterColumnDropExpression { column: String, if_exists: bool },
1615 /// v7.38 (read01, T28) — `ALTER COLUMN col DROP IDENTITY [IF EXISTS]`:
1616 /// de-generate an identity column into a plain column.
1617 AlterColumnDropIdentity { column: String, if_exists: bool },
1618 /// v7.38 (read01 U12) — `ALTER TABLE … ALTER COLUMN col SET
1619 /// EXPRESSION AS (expr)` (PG 17) changes a stored generated column's
1620 /// expression and recomputes every existing row.
1621 AlterColumnSetExpression { column: String, expr: Expr },
1622 /// v7.39 (round 710) — `OF <type>` / the type half of the typed-table
1623 /// binding. The BINDING stays a no-op (recorded); the TYPE must exist
1624 /// (PG: `type "x" does not exist`).
1625 OfType { type_name: String },
1626 /// v7.39 (round 710) — `REPLICA IDENTITY USING INDEX <i>`. The
1627 /// identity setting no-ops (SPG has no logical replication consumer);
1628 /// the INDEX must exist on this table (PG: `index "i" for table "t"
1629 /// does not exist`).
1630 ReplicaIdentityUsingIndex { index: String },
1631}
1632
1633/// v7.16.1 — target of `ALTER TABLE … { ENABLE | DISABLE }
1634/// TRIGGER …`. PG also accepts `USER`, `REPLICA`, `ALWAYS`
1635/// modifiers; v7.16.1 ships the two shapes pg_dump actually
1636/// emits (`ALL` + per-name) — the rest parse-accept as `Named`
1637/// shouldn't surface from a dump.
1638#[derive(Debug, Clone, PartialEq, Eq)]
1639pub enum TriggerSelector {
1640 /// Every trigger on the table.
1641 All,
1642 /// A specific trigger by name.
1643 Named(String),
1644}
1645
1646/// Each bool mirrors one independent PG `EXPLAIN (…)` option (ANALYZE,
1647/// SUGGEST, COSTS OFF, BUFFERS, TIMING OFF, …); they compose freely, so a
1648/// bitflags word or a nested options struct would only relocate the lint
1649/// while making the option each caller sets harder to read.
1650#[allow(clippy::struct_excessive_bools)]
1651#[derive(Debug, Clone, PartialEq)]
1652pub struct ExplainStatement {
1653 pub analyze: bool,
1654 /// v7.39 (round 225) — widened from SelectStatement so EXPLAIN
1655 /// INSERT/UPDATE/DELETE parses (PG explains DML); the engine renders
1656 /// `Insert on / Update on / Delete on` trees for them.
1657 pub inner: Box<Statement>,
1658 /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
1659 /// advisor pass: after the regular plan tree, the engine
1660 /// emits one suggestion line per column referenced in the
1661 /// query's WHERE / JOIN that has no covering index on the
1662 /// owning table.
1663 pub suggest: bool,
1664 /// v7.37.7 — `EXPLAIN (COSTS OFF) <SELECT>` strips wall-clock
1665 /// `elapsed=…us` annotations from the Total line (and any
1666 /// future cost-bearing lines). PG-standard option used by
1667 /// regression suites and diff-friendly EXPLAIN output. When
1668 /// `true`, takes precedence over the per-session
1669 /// `SPG_TEST_EXPLAIN_NO_COSTS` GUC.
1670 pub costs_off: bool,
1671 /// v7.37.22 (22.7) — `EXPLAIN (BUFFERS) <SELECT>`. PG-standard
1672 /// option that surfaces hot/cold/shared block counters. SPG's
1673 /// hot-tier scan path counts examined rows; the BUFFERS option
1674 /// makes that an explicit per-operator annotation.
1675 pub buffers: bool,
1676 /// v7.37.22 (22.7) — `EXPLAIN (TIMING [ON|OFF]) <SELECT>`. PG
1677 /// uses this to disable per-operator timing while still
1678 /// emitting actual-row counts (cheaper than ANALYZE). Default
1679 /// when EXPLAIN ANALYZE is set: TIMING ON. `false` strips the
1680 /// timing portion of the Total line. Decoupled from `costs_off`:
1681 /// PG's COSTS OFF strips estimated cost; TIMING OFF strips
1682 /// measured wall-clock.
1683 pub timing_off: bool,
1684 /// v7.37.22 (22.7) — `EXPLAIN (SETTINGS) <SELECT>`. PG appends
1685 /// modified GUC values to the plan output. SPG emits the
1686 /// session params that diverge from default after the main
1687 /// plan body.
1688 pub settings: bool,
1689 /// v7.37.22 (22.7) — `EXPLAIN (WAL) <SELECT>`. PG counts WAL
1690 /// bytes / records / FPI emitted by the query. SPG's
1691 /// write-side queries (INSERT/UPDATE/DELETE wrapped in EXPLAIN
1692 /// ANALYZE) report against the engine WAL counter delta.
1693 pub wal: bool,
1694 /// v7.39 (round 227) — `EXPLAIN (SUMMARY OFF)` suppresses the trailing
1695 /// `Planning Time:` / `Execution Time:` lines. PG defaults SUMMARY on
1696 /// for ANALYZE and off otherwise; SPG emits them for ANALYZE unless
1697 /// this is set.
1698 pub summary_off: bool,
1699 /// v7.37.23 (23.5) — `EXPLAIN (FORMAT text|json|xml|yaml)`.
1700 /// PG's standard format selector. Default is text. JSON / XML
1701 /// / YAML emit a single-row TEXT result whose body wraps the
1702 /// existing line-per-operator text in the chosen container —
1703 /// PG-compatible just enough for dashboards that parse those
1704 /// container shapes (pgAdmin's JSON path picker, etc.).
1705 pub format: ExplainFormat,
1706}
1707
1708#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1709pub enum ExplainFormat {
1710 #[default]
1711 Text,
1712 Json,
1713 Xml,
1714 Yaml,
1715}
1716
1717/// v7.39 (RLS) — the command a `CREATE POLICY` scopes to. `All` is the default.
1718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1719pub enum PolicyCmd {
1720 All,
1721 Select,
1722 Insert,
1723 Update,
1724 Delete,
1725}
1726
1727/// v7.39 (RLS) — `CREATE POLICY name ON table [AS {PERMISSIVE|RESTRICTIVE}]
1728/// [FOR cmd] [TO roles] [USING (expr)] [WITH CHECK (expr)]`.
1729#[derive(Debug, Clone, PartialEq)]
1730pub struct CreatePolicyStatement {
1731 pub name: String,
1732 pub table: String,
1733 /// `true` = PERMISSIVE (default), `false` = RESTRICTIVE.
1734 pub permissive: bool,
1735 pub cmd: PolicyCmd,
1736 /// Empty = PUBLIC.
1737 pub roles: Vec<String>,
1738 pub using: Option<Expr>,
1739 pub with_check: Option<Expr>,
1740}
1741
1742/// v7.39 (RLS) — `ALTER POLICY name ON table { RENAME TO new | [TO roles]
1743/// [USING (expr)] [WITH CHECK (expr)] }`. Cannot change PERMISSIVE/RESTRICTIVE
1744/// or the command (matches PG).
1745#[derive(Debug, Clone, PartialEq)]
1746pub struct AlterPolicyStatement {
1747 pub name: String,
1748 pub table: String,
1749 pub rename_to: Option<String>,
1750 pub roles: Option<Vec<String>>,
1751 pub using: Option<Expr>,
1752 pub with_check: Option<Expr>,
1753}
1754
1755/// v7.39 (RLS) — `DROP POLICY [IF EXISTS] name ON table`.
1756#[derive(Debug, Clone, PartialEq, Eq)]
1757pub struct DropPolicyStatement {
1758 pub name: String,
1759 pub table: String,
1760 pub if_exists: bool,
1761}
1762
1763#[derive(Debug, Clone, PartialEq, Eq)]
1764pub struct CreateUserStatement {
1765 pub name: String,
1766 /// Empty when the statement carried no PASSWORD — legal for a bare
1767 /// `CREATE ROLE`, which cannot log in anyway.
1768 pub password: String,
1769 /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
1770 /// the parser; the engine validates against `Role::parse` so a
1771 /// typo lands as a runtime error with a clear message rather than
1772 /// a parse failure.
1773 pub role: String,
1774 /// v7.39 (read01 round 58) — the PG role attributes. `None` = the
1775 /// statement did not say, so the default for its spelling applies:
1776 /// `CREATE USER` is `CREATE ROLE … LOGIN`, `CREATE ROLE` is NOLOGIN;
1777 /// both default to INHERIT and NOSUPERUSER.
1778 pub login: Option<bool>,
1779 pub inherit: Option<bool>,
1780 pub superuser: Option<bool>,
1781 /// `true` when spelled `CREATE USER` (LOGIN by default).
1782 pub is_user: bool,
1783}
1784
1785/// v7.39 (round 322, V46) — PG's function volatility class. Declarative:
1786/// it tells the planner how far a call may be moved or folded. SPG records
1787/// it faithfully (`pg_proc.provolatile`, `pg_get_functiondef`) and does not
1788/// yet exploit it for constant folding.
1789#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1790pub enum FunctionVolatility {
1791 Immutable,
1792 Stable,
1793 #[default]
1794 Volatile,
1795}
1796
1797impl FunctionVolatility {
1798 /// PG's one-character `pg_proc.provolatile` code.
1799 #[must_use]
1800 pub const fn as_pg_char(self) -> &'static str {
1801 match self {
1802 Self::Immutable => "i",
1803 Self::Stable => "s",
1804 Self::Volatile => "v",
1805 }
1806 }
1807
1808 #[must_use]
1809 pub const fn as_sql(self) -> &'static str {
1810 match self {
1811 Self::Immutable => "IMMUTABLE",
1812 Self::Stable => "STABLE",
1813 Self::Volatile => "VOLATILE",
1814 }
1815 }
1816}
1817
1818/// v7.39 (round 322, V46) — PG's parallel-safety class.
1819#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1820pub enum FunctionParallel {
1821 #[default]
1822 Unsafe,
1823 Restricted,
1824 Safe,
1825}
1826
1827impl FunctionParallel {
1828 /// PG's one-character `pg_proc.proparallel` code.
1829 #[must_use]
1830 pub const fn as_pg_char(self) -> &'static str {
1831 match self {
1832 Self::Unsafe => "u",
1833 Self::Restricted => "r",
1834 Self::Safe => "s",
1835 }
1836 }
1837
1838 #[must_use]
1839 pub const fn as_sql(self) -> &'static str {
1840 match self {
1841 Self::Unsafe => "PARALLEL UNSAFE",
1842 Self::Restricted => "PARALLEL RESTRICTED",
1843 Self::Safe => "PARALLEL SAFE",
1844 }
1845 }
1846}
1847
1848/// v7.39 (round 322, V46) — the attribute clauses `CREATE FUNCTION` accepts
1849/// on either side of its body. Defaults are PG's: VOLATILE, called on null
1850/// input, SECURITY INVOKER, not leakproof, PARALLEL UNSAFE, and the
1851/// language's default cost / rows.
1852#[derive(Debug, Clone, Copy, PartialEq, Default)]
1853pub struct FunctionAttrs {
1854 pub volatility: FunctionVolatility,
1855 /// `STRICT` / `RETURNS NULL ON NULL INPUT`: a call with any NULL
1856 /// argument returns NULL without running the body.
1857 pub strict: bool,
1858 pub security_definer: bool,
1859 pub leakproof: bool,
1860 pub parallel: FunctionParallel,
1861 /// `COST n` — `None` leaves PG's per-language default.
1862 pub cost: Option<f64>,
1863 /// `ROWS n` — set-returning functions only; `None` = default.
1864 pub rows: Option<f64>,
1865}
1866
1867impl FunctionAttrs {
1868 /// The attribute words `pg_get_functiondef` puts on their own line,
1869 /// in PG's order (measured on 18.4: volatility, PARALLEL, STRICT,
1870 /// SECURITY DEFINER, LEAKPROOF, COST, ROWS). Empty when everything is
1871 /// at its default — PG then emits no such line at all.
1872 #[must_use]
1873 pub fn render_words(&self) -> alloc::vec::Vec<alloc::string::String> {
1874 let mut out = alloc::vec::Vec::new();
1875 if self.volatility != FunctionVolatility::Volatile {
1876 out.push(alloc::string::String::from(self.volatility.as_sql()));
1877 }
1878 if self.parallel != FunctionParallel::Unsafe {
1879 out.push(alloc::string::String::from(self.parallel.as_sql()));
1880 }
1881 if self.strict {
1882 out.push(alloc::string::String::from("STRICT"));
1883 }
1884 if self.security_definer {
1885 out.push(alloc::string::String::from("SECURITY DEFINER"));
1886 }
1887 if self.leakproof {
1888 out.push(alloc::string::String::from("LEAKPROOF"));
1889 }
1890 if let Some(c) = self.cost {
1891 out.push(alloc::format!("COST {}", render_attr_number(c)));
1892 }
1893 if let Some(r) = self.rows {
1894 out.push(alloc::format!("ROWS {}", render_attr_number(r)));
1895 }
1896 out
1897 }
1898}
1899
1900/// PG prints a whole-numbered cost / rows without a decimal point.
1901fn render_attr_number(v: f64) -> alloc::string::String {
1902 // no_std: `f64::fract` lives in std, so compare against the truncation.
1903 let whole = v as i64;
1904 if v.abs() < 1e15 && (whole as f64) == v {
1905 alloc::format!("{whole}")
1906 } else {
1907 alloc::format!("{v}")
1908 }
1909}
1910
1911/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
1912/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
1913/// (the row-level trigger body the CREATE TRIGGER below references).
1914/// Non-trigger user-defined functions parse but error at execution
1915/// time with a clear unsupported message; that surface lands in
1916/// v7.12.5+.
1917#[derive(Debug, Clone, PartialEq)]
1918pub struct CreateFunctionStatement {
1919 pub name: String,
1920 /// `OR REPLACE` was present; an existing function with the
1921 /// same name is overwritten instead of erroring.
1922 pub or_replace: bool,
1923 /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
1924 /// list `()` (sufficient for trigger functions). Other shapes
1925 /// parse and store the args but the executor refuses to call
1926 /// them.
1927 pub args: Vec<FunctionArg>,
1928 /// `RETURNS <type>` — `trigger` is the supported shape for
1929 /// v7.12.4; arbitrary return types parse to
1930 /// [`FunctionReturn::Other`].
1931 pub returns: FunctionReturn,
1932 /// `LANGUAGE <lang>` clause. PG accepts the clause on either
1933 /// side of `AS $$...$$`; the parser canonicalises to one slot.
1934 /// `plpgsql` and `sql` are the two interesting values.
1935 pub language: String,
1936 /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
1937 /// a structured AST; non-trigger / non-plpgsql bodies stay as
1938 /// the raw source text so the v7.12.5+ executor can pick them
1939 /// up without a parser rev.
1940 pub body: FunctionBody,
1941 /// v7.39 (round 322, V46) — `IMMUTABLE` / `STRICT` / `PARALLEL SAFE` /
1942 /// `SECURITY DEFINER` / `LEAKPROOF` / `COST` / `ROWS`. PG accepts them
1943 /// on either side of the body; before this they were a parse error, so
1944 /// PG's own `pg_dump` output would not restore.
1945 pub attrs: FunctionAttrs,
1946}
1947
1948/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
1949#[derive(Debug, Clone, PartialEq)]
1950pub struct FunctionArg {
1951 /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
1952 /// (the default); `OUT` / `INOUT` parse but the executor
1953 /// refuses them.
1954 pub mode: FunctionArgMode,
1955 /// Optional arg name. Trigger functions traditionally don't
1956 /// name their args (they read NEW/OLD instead), so `None` is
1957 /// the common case.
1958 pub name: Option<String>,
1959 /// Declared type, normalised to the SPG `DataType` mapping
1960 /// where one exists. Unknown / extension types parse as a
1961 /// raw string under [`FunctionArgType::Raw`].
1962 pub ty: FunctionArgType,
1963}
1964
1965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1966pub enum FunctionArgMode {
1967 In,
1968 Out,
1969 InOut,
1970}
1971
1972#[derive(Debug, Clone, PartialEq)]
1973pub enum FunctionArgType {
1974 Typed(ColumnTypeName),
1975 /// Unknown / extension types — kept as the parser-side raw
1976 /// identifier so error messages can name them precisely.
1977 Raw(String),
1978}
1979
1980#[derive(Debug, Clone, PartialEq)]
1981pub enum FunctionReturn {
1982 /// `RETURNS TRIGGER` — the row-level trigger function shape.
1983 /// v7.12.4 ships exactly this for execution.
1984 Trigger,
1985 /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
1986 /// the function is unused (since v7.12.4 doesn't ship scalar
1987 /// function invocation).
1988 Void,
1989 /// `RETURNS <type>` for any concrete data type. Reserved for
1990 /// v7.12.5+'s scalar UDF surface.
1991 Type(ColumnTypeName),
1992 /// `RETURNS <ident>` for types SPG doesn't know — extension
1993 /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
1994 Other(String),
1995}
1996
1997#[derive(Debug, Clone, PartialEq)]
1998pub enum FunctionBody {
1999 /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
2000 /// trigger-function executor walks this directly without
2001 /// re-parsing.
2002 PlPgSql(PlPgSqlBlock),
2003 /// Raw source text — parser couldn't (or didn't try to)
2004 /// structure-parse the body. Used for `LANGUAGE sql`
2005 /// functions and any PL/pgSQL body that contains v7.12.5+
2006 /// features the v7.12.4 parser doesn't yet recognise. The
2007 /// executor returns an unsupported error when invoked.
2008 Raw(String),
2009}
2010
2011/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
2012/// from assignment + return to a real-PL/pgSQL surface:
2013/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
2014/// control flow, `RAISE` diagnostics, and embedded SQL
2015/// statements that execute through the regular engine path.
2016/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
2017/// which mailrs's trigger doesn't need but other PG customers
2018/// may; deferred to a future minor release.
2019#[derive(Debug, Clone, PartialEq)]
2020pub struct PlPgSqlBlock {
2021 /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
2022 /// preceding `BEGIN`. Empty when the body opens directly with
2023 /// `BEGIN`. Declarations execute in order; each may reference
2024 /// earlier-declared locals in its init expression.
2025 pub declarations: Vec<PlPgSqlDeclare>,
2026 pub statements: Vec<PlPgSqlStmt>,
2027 /// v7.37.20 (20.10) — `EXCEPTION WHEN <cond> [OR <cond>...] THEN
2028 /// <body>` handlers appended to the block. Empty when no
2029 /// EXCEPTION clause is present. When a body statement raises
2030 /// (via RAISE EXCEPTION, ASSERT falsy, or a runtime error),
2031 /// handlers are tried in order; the first matching condition
2032 /// runs its body and the block terminates cleanly. `OTHERS`
2033 /// matches any exception. Unhandled exceptions propagate.
2034 pub exception_handlers: Vec<ExceptionHandler>,
2035}
2036
2037/// v7.37.20 (20.10) — one `WHEN <cond> [OR <cond>...] THEN <body>`
2038/// arm inside an EXCEPTION block.
2039#[derive(Debug, Clone, PartialEq)]
2040pub struct ExceptionHandler {
2041 /// Condition names (`OTHERS`, `unique_violation`, etc.). Multiple
2042 /// conditions joined by `OR` share one handler body.
2043 pub conditions: Vec<String>,
2044 /// Statements to run when a matching exception is caught.
2045 pub body: Vec<PlPgSqlStmt>,
2046}
2047
2048/// v7.12.6 — single `DECLARE` entry: variable name + declared
2049/// type + optional initialiser. Variables default to SQL NULL
2050/// when no init is given (matches PG).
2051#[derive(Debug, Clone, PartialEq)]
2052pub struct PlPgSqlDeclare {
2053 pub name: String,
2054 /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
2055 /// knows it; raw text otherwise).
2056 pub ty: FunctionArgType,
2057 pub default: Option<Expr>,
2058}
2059
2060#[derive(Debug, Clone, PartialEq)]
2061pub enum PlPgSqlStmt {
2062 /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
2063 /// for clarity in error reporting (PG also forbids it) — the
2064 /// executor errors with a clear "OLD is read-only" message.
2065 Assign { target: AssignTarget, value: Expr },
2066 /// v7.16.2 — plpgsql `SELECT <projection> INTO <var>
2067 /// [FROM …]` (mailrs round-10 migrate-042). The `body` is
2068 /// the SELECT statement with the INTO clause stripped; the
2069 /// engine runs it via `Engine::execute`, takes the first
2070 /// row's first column, and assigns to the local variable
2071 /// in the DECLARE scope. Single-column / single-row
2072 /// queries only at v7.16.2; multi-target (`INTO a, b`) is
2073 /// a v7.16.x follow-up.
2074 SelectInto {
2075 var: String,
2076 body: Box<SelectStatement>,
2077 },
2078 /// `RETURN <target>;` — trigger functions canonically return
2079 /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
2080 /// expression for forward compatibility with scalar UDFs.
2081 Return(ReturnTarget),
2082 /// v7.39 (read01 round 66) — `RETURN NEXT <expr>;`: append one row to the
2083 /// set a SETOF function is building, and KEEP GOING. Not a return.
2084 ReturnNext(Expr),
2085 /// v7.39 (read01 round 66) — `RETURN QUERY <select>;`: append every row the
2086 /// query yields, and keep going. It used to desugar to a side-effect
2087 /// statement whose result was DISCARDED — in a SETOF function that is the
2088 /// whole answer thrown away.
2089 ReturnQuery(Box<SelectStatement>),
2090 /// v7.39 (read01 round 68) — `RETURN QUERY EXECUTE <sql expr>`: the dynamic
2091 /// twin. Its rows go to the set too; it used to run and discard them.
2092 ReturnQueryExecute { sql: Expr },
2093 /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
2094 /// [ELSE body] END IF;`. Branches are tried in order; first
2095 /// truthy condition wins; the optional ELSE runs when no
2096 /// condition matched.
2097 If {
2098 branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
2099 else_branch: Vec<PlPgSqlStmt>,
2100 },
2101 /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
2102 /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
2103 /// (logging — observable side effect only) or `EXCEPTION`
2104 /// (aborts the trigger and propagates as an error). v7.12.6
2105 /// supports the basic format-string substitution PG uses
2106 /// (`%` placeholders consumed positionally).
2107 Raise {
2108 level: RaiseLevel,
2109 message: String,
2110 args: Vec<Expr>,
2111 },
2112 /// v7.12.6 — embedded SQL statement inside the trigger body
2113 /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
2114 /// NEW.col / OLD.col references inside the embedded
2115 /// statement's expression tree are substituted with the
2116 /// current trigger context before the engine re-executes the
2117 /// statement. Recursion depth into nested triggers is
2118 /// bounded by the engine's existing trigger-fire guard.
2119 EmbeddedSql(Box<Statement>),
2120 /// v7.37.20 (20.14) — `ASSERT <condition> [, <message>];`. If
2121 /// the condition evaluates falsy the trigger / DO block aborts
2122 /// with the message (defaulting to a generic shape when none
2123 /// is provided). Same propagation shape as `RAISE EXCEPTION`
2124 /// — the error reaches the caller's query path. PG's behaviour
2125 /// is identical except for a `plpgsql.check_asserts` GUC that
2126 /// can disable the check globally; SPG always evaluates.
2127 Assert {
2128 condition: Expr,
2129 message: Option<Expr>,
2130 },
2131 /// v7.37.20 (20.3) — `WHILE <condition> LOOP <body> END LOOP;`.
2132 /// Iterate the body while condition evaluates truthy. Iteration
2133 /// count is bounded by `WHILE_LOOP_BUDGET` to prevent runaway
2134 /// loops; the executor errors out when reached. EXIT / CONTINUE
2135 /// inside the body queue with 20.2.
2136 While {
2137 condition: Expr,
2138 body: Vec<PlPgSqlStmt>,
2139 },
2140 /// v7.37.20 (20.4) — `FOR <var> IN [REVERSE] <start>..<end> LOOP
2141 /// <body> END LOOP;`. Integer iteration; `var` is BigInt-valued;
2142 /// bounds inclusive on both sides. REVERSE walks backward.
2143 /// Iteration budget guards runaway.
2144 ForRange {
2145 var: String,
2146 start: Expr,
2147 end: Expr,
2148 reverse: bool,
2149 body: Vec<PlPgSqlStmt>,
2150 },
2151 /// v7.37.20 (20.2) — bare `LOOP <body> END LOOP;`. Runs the body
2152 /// repeatedly; only `EXIT [WHEN <cond>]` breaks out. Iteration
2153 /// budget guards runaway.
2154 Loop { body: Vec<PlPgSqlStmt> },
2155 /// v7.37.20 (20.2) — `EXIT [WHEN <condition>];` inside a loop.
2156 /// Unconditional (no WHEN) or conditional (only breaks when
2157 /// condition is truthy). Bubbles up as BodyOutcome::Break which
2158 /// the enclosing loop catches. Outside a loop it's a no-op.
2159 Exit { when: Option<Expr> },
2160 /// v7.37.20 (20.2) — `CONTINUE [WHEN <condition>];` inside a
2161 /// loop. Same shape as EXIT but bubbles up as BodyOutcome::Continue
2162 /// which the enclosing loop catches, skipping the remainder of
2163 /// the body and jumping to the next iteration.
2164 Continue { when: Option<Expr> },
2165 /// v7.37.20 (20.13) — `EXECUTE <string_expr>;` runs a runtime-
2166 /// computed SQL statement. The expression is evaluated to a
2167 /// text value, the resulting string is parsed and dispatched
2168 /// through the engine like an EmbeddedSql. USING <param_list>
2169 /// for placeholder binding queues with v7.40 PL/pgSQL epic.
2170 ExecuteDynamic { sql: Expr },
2171 /// v7.37.20 (20.5) — `FOR <var> IN <select_body> LOOP <body>
2172 /// END LOOP;`. Runs the SELECT once, iterates the resulting
2173 /// rows, binds the first column of each row to `var` as a
2174 /// scalar Value, then runs the body per iteration. EXIT /
2175 /// CONTINUE / ASSERT / RAISE etc. propagate through the
2176 /// enclosing loop's BodyOutcome discipline the same way
2177 /// FOR range and WHILE do. Full record-binding (var as
2178 /// composite carrying all columns) queues with v7.40 record
2179 /// type infrastructure.
2180 ForQuery {
2181 var: String,
2182 query: Box<SelectStatement>,
2183 body: Vec<PlPgSqlStmt>,
2184 },
2185 /// v7.37.20 (20.6) — `FOR <var> IN EXECUTE <string_expr> LOOP
2186 /// <body> END LOOP;`. Same shape as ForQuery but the SELECT is
2187 /// computed at runtime from a text expression, parsed on the
2188 /// fly, then iterated. Enables dynamic queries where the
2189 /// projection / FROM / WHERE clauses depend on runtime values.
2190 ForExecute {
2191 var: String,
2192 sql_expr: Expr,
2193 body: Vec<PlPgSqlStmt>,
2194 },
2195}
2196
2197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2198pub enum RaiseLevel {
2199 /// `RAISE NOTICE` — diagnostic message, observable in the
2200 /// server log. Does not affect the trigger's outcome.
2201 Notice,
2202 /// `RAISE WARNING` — like NOTICE, slightly louder severity.
2203 Warning,
2204 /// `RAISE INFO` — like NOTICE, slightly quieter.
2205 Info,
2206 /// `RAISE LOG` — like NOTICE, lower priority.
2207 Log,
2208 /// `RAISE DEBUG` — like NOTICE, lowest priority.
2209 Debug,
2210 /// `RAISE EXCEPTION` — aborts the trigger function with the
2211 /// given message, propagating up to the caller as a query-
2212 /// level error.
2213 Exception,
2214}
2215
2216#[derive(Debug, Clone, PartialEq)]
2217pub enum AssignTarget {
2218 NewColumn(String),
2219 OldColumn(String),
2220 /// Reserved for v7.12.5 DECLARE'd local variables.
2221 Local(String),
2222}
2223
2224#[derive(Debug, Clone, PartialEq)]
2225pub enum ReturnTarget {
2226 /// `RETURN NEW;` — for BEFORE triggers, this is the row that
2227 /// actually gets written (possibly with NEW.col mutations
2228 /// applied). For AFTER triggers, the return value is ignored.
2229 New,
2230 /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
2231 /// the delete proceed; for BEFORE UPDATE / INSERT it's
2232 /// equivalent to dropping the write.
2233 Old,
2234 /// `RETURN NULL;` — for BEFORE triggers, skips the write
2235 /// entirely. For AFTER, the return value is ignored.
2236 Null,
2237 /// `RETURN <expr>;` — non-row return shape; reserved for the
2238 /// scalar UDF surface in v7.12.5+. Executor errors when used
2239 /// inside a trigger function.
2240 Expr(Expr),
2241}
2242
2243/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
2244/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
2245/// but the executor refuses them. `WHEN (cond)` clauses are out
2246/// of scope; the trigger function can short-circuit on a leading
2247/// IF inside its body once v7.12.5 lands IF.
2248#[derive(Debug, Clone, PartialEq)]
2249pub struct CreateTriggerStatement {
2250 pub name: String,
2251 pub or_replace: bool,
2252 pub timing: TriggerTiming,
2253 /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
2254 /// three entries in order.
2255 pub events: Vec<TriggerEvent>,
2256 pub table: String,
2257 /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
2258 /// only `Row`; `Statement` parses but the executor refuses.
2259 pub for_each: TriggerForEach,
2260 /// Name of the function to invoke. The function must exist at
2261 /// CREATE TRIGGER time — PG18-measured (round 753): PG refuses a
2262 /// forward reference (`function no_such_fn() does not exist`), so
2263 /// requiring it IS the PG behaviour (the old note claimed the
2264 /// opposite).
2265 pub function: String,
2266 /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
2267 /// (mailrs round-5 G7). Non-empty only when the events list
2268 /// contains UPDATE and the user wrote the column-list filter.
2269 /// PG fires the trigger only when at least one of these
2270 /// columns appears in the SET clause; SPG conservatively
2271 /// fires on any UPDATE matching the listed columns or
2272 /// rewriting them at the row level. Empty vec = no filter
2273 /// (fire on every UPDATE).
2274 pub update_columns: Vec<String>,
2275 /// v7.39 (round 138) — `WHEN ( condition )` row-level filter: the row
2276 /// trigger fires only when the condition (over NEW / OLD) is true. `None`
2277 /// = no WHEN (fire unconditionally). Not allowed on INSTEAD OF triggers.
2278 pub when_condition: Option<Expr>,
2279}
2280
2281/// v7.39 (round 139) — `CREATE RULE` query-rewrite rule AST node.
2282#[derive(Debug, Clone, PartialEq)]
2283pub struct CreateRuleStatement {
2284 pub name: String,
2285 pub or_replace: bool,
2286 /// Event keyword, uppercased: `INSERT` / `UPDATE` / `DELETE` / `SELECT`.
2287 pub event: String,
2288 pub table: String,
2289 /// `true` = `DO INSTEAD` (replace the operation), `false` = `DO ALSO`
2290 /// (run alongside; PG's default when neither keyword is written).
2291 pub instead: bool,
2292 /// Optional `WHERE ( condition )` — the rule applies only when it holds.
2293 pub when_condition: Option<Expr>,
2294 /// The `DO` commands (over NEW / OLD). Empty = `NOTHING`.
2295 pub commands: Vec<Statement>,
2296}
2297
2298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2299pub enum TriggerTiming {
2300 /// Fires before the row is written; the trigger function's
2301 /// return value (NEW or NULL) decides the row content and
2302 /// whether the write proceeds at all.
2303 Before,
2304 /// Fires after the row is written; the return value is
2305 /// ignored.
2306 After,
2307 /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
2308 /// v7.12.4 (SPG has no updatable-view surface).
2309 InsteadOf,
2310}
2311
2312#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2313pub enum TriggerEvent {
2314 Insert,
2315 Update,
2316 Delete,
2317 /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
2318 /// so the trigger never fires.
2319 Truncate,
2320}
2321
2322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2323pub enum TriggerForEach {
2324 Row,
2325 Statement,
2326}
2327
2328/// v7.39 (round 537) — a `CREATE INDEX` key column's ordering clause.
2329///
2330/// SPG's index does not scan in a direction, but `indexdef` reproduces
2331/// the DDL and dropping this made `(a DESC NULLS LAST)` read back as
2332/// `(a)`. `nulls_first` is `None` when the statement did not say, in
2333/// which case PG's default applies — LAST for ascending, FIRST for
2334/// descending, and neither is rendered.
2335#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2336pub struct IndexColumnOrder {
2337 pub descending: bool,
2338 pub nulls_first: Option<bool>,
2339}
2340
2341#[derive(Debug, Clone, PartialEq)]
2342pub struct CreateIndexStatement {
2343 pub name: String,
2344 /// `CREATE INDEX CONCURRENTLY`. SPG builds indexes synchronously
2345 /// either way, so this changes nothing about how the index is made
2346 /// — it is carried because PG refuses the CONCURRENTLY form inside
2347 /// a transaction block and accepts the plain one, and the engine
2348 /// cannot tell them apart without it.
2349 pub concurrently: bool,
2350 /// v7.39 (round 537) — the leading key column's ordering clause,
2351 /// which is the column SPG indexes.
2352 pub key_order: IndexColumnOrder,
2353 /// v7.39 (round 538) — an explicit `COLLATE` on that key, as
2354 /// written. SPG orders text by bytes, so honouring it changes
2355 /// nothing; PG prints it, because an explicitly named collation and
2356 /// the one a column inherits are different objects.
2357 pub key_collation: Option<String>,
2358 pub table: String,
2359 pub column: String,
2360 /// v7.39 (read01 round 52) — `CREATE UNIQUE INDEX … NULLS NOT DISTINCT`
2361 /// (PG 15+). Default (`false`) is the SQL-standard NULLS DISTINCT, where
2362 /// any NULL in the key exempts the row from the uniqueness check.
2363 pub nulls_not_distinct: bool,
2364 /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
2365 /// graph for vector kNN); unspecified is the default B-tree index.
2366 pub method: IndexMethod,
2367 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2368 /// index name already exists, instead of raising `DuplicateIndex`.
2369 pub if_not_exists: bool,
2370 /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
2371 /// non-key columns the planner should treat as "covered" by
2372 /// this index when checking whether a query can run as an
2373 /// index-only scan. Empty when no `INCLUDE` clause was given.
2374 pub included_columns: Vec<String>,
2375 /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
2376 /// for which `<expr>` evaluates truthy enter the index;
2377 /// queries whose `WHERE` clause's canonical Display form
2378 /// matches this expression's Display form can be served by the
2379 /// partial index. Stored as a parsed `Expr` so the engine
2380 /// re-uses the existing evaluation path; storage persists the
2381 /// Display form on the catalog snapshot.
2382 pub partial_predicate: Option<Expr>,
2383 /// v6.8.2 — expression-based index. When `Some(expr)`, the
2384 /// index key is the result of `expr` evaluated on each row
2385 /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
2386 /// field still names the *primary* column the expression
2387 /// touches so existing planner shortcuts that resolve a
2388 /// column position stay valid. `None` = plain
2389 /// column-reference index (the legacy shape).
2390 pub expression: Option<Expr>,
2391 /// v7.9.14 — extra column names after the leading column in a
2392 /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
2393 /// planner today still only uses the leading column for index
2394 /// seeks; the extras are tracked verbatim so the same DDL
2395 /// round-trips through WAL replay + catalog snapshot, and so
2396 /// the engine can emit a clear warning at INDEX CREATE time
2397 /// that only the leading column is currently honoured.
2398 /// Composite BTree index keys land in v7.10.
2399 pub extra_columns: Vec<String>,
2400 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2401 /// enforces uniqueness on the indexed key (combined with the
2402 /// `partial_predicate` filter — only rows where the predicate
2403 /// evaluates truthy enter the uniqueness check). Standard SQL
2404 /// and PG's canonical way to express conditional uniqueness.
2405 /// mailrs K1.
2406 pub is_unique: bool,
2407 /// v7.15.0 — operator class on the leading column, when the
2408 /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2409 /// Lower-cased. Most opclasses are still informational; the
2410 /// engine routes on `gin_trgm_ops` specifically to build a
2411 /// trigram-shingle GIN over a TEXT column, and otherwise
2412 /// keeps the current "accepted and discarded" behaviour for
2413 /// pg_dump compatibility.
2414 pub opclass: Option<String>,
2415 /// r1038 — the access method as WRITTEN, lower-cased; `None` when
2416 /// there was no `USING` clause.
2417 ///
2418 /// `method` cannot answer this: `gist` / `spgist` / `hash` all become
2419 /// `IndexMethod::BTree` so PG schemas naming an AM SPG has no
2420 /// implementation for still load. That degradation is deliberate, but
2421 /// it loses the name — and the operator-class check needs it, both to
2422 /// look the class up under the AM the user actually named and to say
2423 /// which AM it was missing from, the way PG's message does.
2424 pub method_name: Option<String>,
2425}
2426
2427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2428pub enum IndexMethod {
2429 /// Default — B-tree over `IndexKey`. Used for equality / range
2430 /// lookups on scalar columns.
2431 BTree,
2432 /// `USING hnsw` — NSW graph for kNN over a vector column.
2433 Hnsw,
2434 /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2435 /// metadata that records (min_key, max_key) for each page in a
2436 /// cold-tier segment, on the indexed column. The optimizer
2437 /// can use these summaries to skip pages whose range does NOT
2438 /// overlap a query's WHERE predicate. BRIN indexes carry no
2439 /// in-memory data — the summaries live in the segment v2
2440 /// envelope's sidecar. Created via the standard
2441 /// `CREATE INDEX … USING brin (col)` syntax.
2442 Brin,
2443 /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2444 /// column. Posting lists map `lexeme word` → row locators; the
2445 /// planner uses them to narrow `WHERE col @@ tsquery` to the
2446 /// candidate rows whose vectors contain a matching term, then
2447 /// re-evaluates the full `@@` semantics on each candidate.
2448 /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2449 /// silently degraded to a full scan at query time.
2450 Gin,
2451}
2452
2453/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2454/// inside a CREATE TABLE column list.
2455///
2456/// The source table's shape can only be read from the catalog, so the
2457/// parser records the clause and the engine expands it. `at` is how many
2458/// explicit columns preceded it: PG keeps the written order, so
2459/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2460#[derive(Debug, Clone, PartialEq)]
2461pub struct LikeSpec {
2462 pub source: String,
2463 pub at: usize,
2464 pub options: LikeOptions,
2465}
2466
2467/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2468/// types and NOT NULL and nothing else — measured on PG18, where a
2469/// copied generated column becomes a plain one and a copied identity
2470/// column loses its identity.
2471#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2472pub struct LikeOptions {
2473 pub defaults: bool,
2474 pub constraints: bool,
2475 pub identity: bool,
2476 pub generated: bool,
2477 pub indexes: bool,
2478 pub comments: bool,
2479}
2480
2481#[derive(Debug, Clone, PartialEq)]
2482pub struct CreateTableStatement {
2483 /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2484 /// creating session's own namespace: it shadows a permanent table of the
2485 /// same name, other sessions never see it, and it is dropped when the
2486 /// session ends. A `bool` here lands in the struct's existing padding.
2487 pub temporary: bool,
2488 pub name: String,
2489 /// v7.39 — the `ENGINE=` a MySQL dump names. Consumed and discarded
2490 /// before, so `ENGINE=NONSUCH` built a table where MySQL 9.7.2
2491 /// answers `ERROR 1286`, and `sql_mode` claimed
2492 /// `NO_ENGINE_SUBSTITUTION` while doing it.
2493 pub engine: Option<String>,
2494 pub columns: Vec<ColumnDef>,
2495 /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2496 /// the order written. Empty for a table that has none.
2497 pub like_specs: Vec<LikeSpec>,
2498 /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2499 /// Empty for a table that inherits from nothing. Order matters:
2500 /// the child takes each parent's columns in this order before its
2501 /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2502 pub inherits: Vec<String>,
2503 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2504 /// table name already exists, instead of raising `DuplicateTable`.
2505 pub if_not_exists: bool,
2506 /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2507 /// constraints. Column-level `REFERENCES` (single-column inline
2508 /// form) is normalised into this vec at parse time so the engine
2509 /// sees one uniform list.
2510 pub foreign_keys: Vec<ForeignKeyConstraint>,
2511 /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2512 /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2513 /// Engine resolves each into a BTree index named after the
2514 /// constraint's leading column at CREATE TABLE time; INSERT
2515 /// path enforces composite uniqueness via row scan on the
2516 /// leading column index.
2517 pub table_constraints: Vec<TableConstraint>,
2518 /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2519 /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2520 /// the engine creates a parent table whose own rows stay
2521 /// empty and routes INSERT/SELECT through children. Mutually
2522 /// exclusive with `partition_of` (parser enforces).
2523 pub partition_by: Option<PartitionBySpec>,
2524 /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2525 /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2526 /// the table inherits its column list from `parent` (the
2527 /// parser rejects an explicit column list when this is set);
2528 /// engine routes child rows back to the parent at INSERT.
2529 pub partition_of: Option<PartitionOfSpec>,
2530}
2531
2532/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2533/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2534/// future LIST / HASH without breaking the public AST shape.
2535#[derive(Debug, Clone, PartialEq)]
2536pub struct PartitionBySpec {
2537 pub kind: PartitionKindAst,
2538 /// One or more ident references into the parent's column list.
2539 /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2540 /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2541 /// shape PG-compatible.
2542 pub key_columns: Vec<String>,
2543}
2544
2545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2546pub enum PartitionKindAst {
2547 Range,
2548 /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2549 /// `FOR VALUES IN (lit, lit, …)`.
2550 List,
2551 /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2552 /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2553 Hash,
2554}
2555
2556/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2557/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2558/// or the catch-all `DEFAULT` partition.
2559#[derive(Debug, Clone, PartialEq)]
2560pub struct PartitionOfSpec {
2561 pub parent_name: String,
2562 pub bounds: PartitionOfBoundsAst,
2563}
2564
2565#[derive(Debug, Clone, PartialEq)]
2566pub enum PartitionOfBoundsAst {
2567 /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2568 /// (lits include vector bodies), so we box both bounds to keep
2569 /// the variant size in line with `Default` for clippy and to
2570 /// minimise per-statement footprint when the partition shape
2571 /// isn't in use.
2572 Range {
2573 lower: Box<Expr>,
2574 upper: Box<Expr>,
2575 },
2576 /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2577 /// expr resolves to a typed literal at child-create time.
2578 List {
2579 values: Vec<Expr>,
2580 },
2581 /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2582 /// PG enforces `0 ≤ r < m`; m must be positive.
2583 Hash {
2584 modulus: u32,
2585 remainder: u32,
2586 },
2587 Default,
2588}
2589
2590/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2591/// column list. Either a composite PRIMARY KEY or a UNIQUE
2592/// (single- or multi-column).
2593#[derive(Debug, Clone, PartialEq)]
2594pub enum TableConstraint {
2595 /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2596 /// referenced column. Engine builds a BTree index named
2597 /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2598 PrimaryKey {
2599 name: Option<String>,
2600 columns: Vec<String>,
2601 /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2602 /// Round 621 consumed the clauses; these carry them.
2603 deferrable: bool,
2604 initially_deferred: bool,
2605 },
2606 /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2607 /// named `<table>_<leading_col>_key` (single-column) or
2608 /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2609 /// uniqueness on INSERT.
2610 Unique {
2611 name: Option<String>,
2612 columns: Vec<String>,
2613 /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2614 /// G10). PG 15+ flips the NULL handling so any number of
2615 /// NULL rows collide on the constraint. Default is
2616 /// `false` (NULLS DISTINCT, standard SQL behaviour).
2617 nulls_not_distinct: bool,
2618 /// v7.39 (round 711) — see PrimaryKey.
2619 deferrable: bool,
2620 initially_deferred: bool,
2621 },
2622 /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2623 /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2624 /// this same variant at parse time. Engine evaluates the
2625 /// predicate against each INSERT/UPDATE candidate row; a
2626 /// false / NULL result rejects the mutation.
2627 /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2628 /// PG adds such a constraint without scanning the existing rows: new
2629 /// rows are checked, the ones already there are grandfathered in, and
2630 /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2631 /// scans and flips it. pg_dump emits the suffix for exactly those, so
2632 /// validating them on restore would refuse a dump PG itself produced.
2633 Check {
2634 name: Option<String>,
2635 expr: Expr,
2636 not_valid: bool,
2637 },
2638 /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2639 /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2640 /// every element (the booking/scheduling non-overlap constraint,
2641 /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2642 /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2643 /// enforcement doesn't build the index yet). Each element pairs a
2644 /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2645 Exclude {
2646 name: Option<String>,
2647 method: Option<String>,
2648 elements: Vec<(String, String)>,
2649 },
2650 /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2651 /// non-unique secondary-index declaration inline in CREATE
2652 /// TABLE. Engine builds a BTree index on the leading column
2653 /// (composite columns parse but only the leading column is
2654 /// honoured at v7.15 — matches the existing
2655 /// `CreateIndexStatement::extra_columns` semantics). Useful
2656 /// for `mysql/blog`-style schemas that lean on routine
2657 /// secondary indexes for ORM lookups.
2658 Index {
2659 name: Option<String>,
2660 columns: Vec<String>,
2661 },
2662 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2663 /// (cols)` inline declaration. Pre-v7.17 the parser
2664 /// silently dropped these so MyISAM-imported FULLTEXT
2665 /// indexes vanished; v7.17 routes them through the
2666 /// existing tsvector-GIN engine path so MATCH AGAINST
2667 /// queries get a real inverted index instead of falling
2668 /// back to a full scan. Multi-column FULLTEXT KEYs build
2669 /// one GIN per column at v7.17 (per-column posting lists);
2670 /// the leading column drives query planning.
2671 FulltextIndex {
2672 name: Option<String>,
2673 columns: Vec<String>,
2674 },
2675}
2676
2677#[derive(Debug, Clone, PartialEq)]
2678#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2679pub struct ColumnDef {
2680 pub name: String,
2681 pub ty: ColumnTypeName,
2682 pub nullable: bool,
2683 /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2684 /// evaluates this once (with an empty row) and caches the resulting
2685 /// `Value` on the column schema.
2686 pub default: Option<Expr>,
2687 /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2688 /// per such column and fills the slot when INSERT leaves it
2689 /// unbound (omitted from a column-list INSERT or explicitly NULL).
2690 pub auto_increment: bool,
2691 /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2692 /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2693 /// an implicit BTree index named `<table>_pkey` over this
2694 /// column at CREATE TABLE time, satisfying the parent-side
2695 /// index requirement for any FOREIGN KEY pointing at it.
2696 pub is_primary_key: bool,
2697 /// v7.13.0 — inline `UNIQUE` column constraint
2698 /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2699 /// into a single-column `TableConstraint::Unique` so the
2700 /// engine path stays uniform with table-level UNIQUE.
2701 pub is_unique: bool,
2702 /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2703 /// inline column constraint: treat NULL keys as equal so only one NULL
2704 /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2705 /// `TableConstraint::Unique { nulls_not_distinct }`.
2706 pub unique_nulls_not_distinct: bool,
2707 /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2708 /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2709 /// since this round so the fold into the table-level constraint keeps it.
2710 pub constraint_deferrable: bool,
2711 pub constraint_initially_deferred: bool,
2712 /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2713 /// (mailrs round-5 G3). Stored alongside the column so the
2714 /// CREATE TABLE handler can fold these into table-level
2715 /// CHECK constraints. Multiple inline CHECKs on the same
2716 /// column are concatenated with AND at the table level.
2717 pub check: Option<Expr>,
2718 /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2719 /// parser sees an unknown column-type ident (anything not in
2720 /// the built-in `parse_column_type_name` table), it sets
2721 /// `ty = ColumnTypeName::Text` and records the original name
2722 /// here. The engine resolves at CREATE TABLE time: if a
2723 /// catalog enum/domain with this name exists, the column is
2724 /// bound to it (label-checked on INSERT for enums; CHECK-
2725 /// constrained for domains); otherwise the CREATE TABLE
2726 /// errors with "unknown type".
2727 pub user_type_ref: Option<String>,
2728 /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2729 /// CURRENT_TIMESTAMP` column attribute. When set, an
2730 /// UPDATE that does NOT explicitly bind this column
2731 /// overrides the new value with `now()` (engine clock).
2732 /// Pre-v7.17 SPG silently accepted the syntax and never
2733 /// fired the override — `updated_at` columns from mysqldump
2734 /// stayed pinned at their initial DEFAULT forever, an
2735 /// audit Tier-S silent-failure. Generalised as a stored
2736 /// expression source so future shapes (`ON UPDATE
2737 /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2738 /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2739 pub on_update_runtime: Option<Expr>,
2740 /// v7.17.0 Phase 2.5 — text collation derived from the
2741 /// post-fix `COLLATE <name>` clause (and / or the table-level
2742 /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2743 /// per column). Pre-2.5 SPG accepted the clause and
2744 /// discarded the name, leaving every column byte-compared
2745 /// — a Tier-S silent failure when the customer expected
2746 /// `_ci` / `case_insensitive` semantics. Parser normalises
2747 /// the raw collation name into the variants in `Collation`.
2748 /// Default `Binary` preserves the legacy compare path.
2749 pub collation: Collation,
2750 /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2751 /// explicit `COLLATE <name>` clause rather than the default. Under the
2752 /// MySQL dialect a text column with NO explicit clause takes the
2753 /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2754 /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2755 /// flag is the only thing that tells them apart.
2756 pub collation_explicit: bool,
2757 /// v7.39 (round 676) — the collation name AS WRITTEN, because
2758 /// `collation` above cannot carry it: `Collation` is a two-variant
2759 /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2760 /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2761 /// tell them apart.
2762 pub collation_name: Option<String>,
2763 /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2764 /// 4.4 SPG accepted and discarded the keyword, leaving
2765 /// negative values silently accepted on a column the
2766 /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2767 /// rejects negative INSERT / UPDATE values on UNSIGNED int
2768 /// columns. SPG widening to `u64`-shaped storage is out of
2769 /// v7.17 scope; the upper bound remains the signed-type max
2770 /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2771 /// exceeds what every mailrs / Rails app actually uses.
2772 pub is_unsigned: bool,
2773 /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2774 /// value list captured at parse time. When `Some`, the parser
2775 /// recognised `ENUM(...)` in the type slot; the engine
2776 /// validates INSERT cells against this list at
2777 /// column_def_to_schema time and persists the variants on
2778 /// `ColumnSchema.inline_enum_variants`. None for all
2779 /// non-ENUM columns.
2780 pub inline_enum_variants: Option<Vec<String>>,
2781 /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2782 /// value list. Distinct from ENUM (subset semantics rather
2783 /// than pick-one). None for all non-SET columns.
2784 pub inline_set_variants: Option<Vec<String>>,
2785 /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2786 /// STORED` computed-column source. When `Some`, the engine
2787 /// stores the Display-form of the parsed expression on
2788 /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2789 /// and re-evaluates the expression against every INSERT /
2790 /// UPDATE candidate row, overwriting whatever the caller
2791 /// supplied for this column. Boxed to keep `ColumnDef` from
2792 /// blowing past the `large_enum_variant` clippy ceiling
2793 /// (`Expr` widens with vector literals).
2794 pub generated_stored_expr: Option<Box<Expr>>,
2795 /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2796 /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2797 /// `auto_increment`; this additionally marks the ALWAYS one, whose
2798 /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2799 /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2800 /// VALUE`. Only meaningful when the column is also an identity column.
2801 pub identity_always: bool,
2802 /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2803 /// integer width (TINYINT / MEDIUMINT), captured before the type
2804 /// collapses to SmallInt / Int. The engine copies it to
2805 /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2806 /// path can enforce the real range. None for every other column and
2807 /// under the PG dialect.
2808 pub mysql_int_width: Option<MysqlIntWidth>,
2809 /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2810 /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2811 /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2812 /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2813 /// CREATE TABLE time so the write path can truncate and the render path
2814 /// can pad. None under the PG dialect, where temporal columns keep full
2815 /// microseconds.
2816 pub mysql_fsp: Option<u8>,
2817 /// v7.39.2 — the column was written `TIMESTAMP` rather than
2818 /// `DATETIME` in a MySQL session. The engine copies it to
2819 /// `ColumnSchema.mysql_declared_timestamp` at CREATE TABLE.
2820 pub mysql_declared_timestamp: bool,
2821 /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)` pair, copied to
2822 /// `ColumnSchema.mysql_float_md` at CREATE TABLE.
2823 pub mysql_float_md: Option<(u8, u8)>,
2824}
2825
2826/// v7.17.0 Phase 2.5 — text collation classification surfaced
2827/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2828/// engine bridges between the two at CREATE TABLE time.
2829///
2830/// Recognised collation-name patterns (case-insensitive):
2831/// * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase` → CaseInsensitive
2832/// * Everything else (`C`, `POSIX`, `default`,
2833/// `pg_catalog.default`, `*_cs`, `*_bin`, unknown names) → Binary
2834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2835pub enum Collation {
2836 Binary,
2837 CaseInsensitive,
2838}
2839
2840/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2841/// integer width for a column whose `ColumnTypeName` is too wide to carry
2842/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2843/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2844/// TABLE time. Only recorded under the MySQL dialect.
2845#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2846pub enum MysqlIntWidth {
2847 Tiny,
2848 Small,
2849 Medium,
2850 Int,
2851 /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2852 Big,
2853}
2854
2855#[allow(clippy::derivable_impls)]
2856impl Default for Collation {
2857 fn default() -> Self {
2858 Self::Binary
2859 }
2860}
2861
2862impl Collation {
2863 /// Classify a `COLLATE <name>` ident into one of the supported
2864 /// variants. Empty / unknown names fall back to `Binary` —
2865 /// matches the pre-2.5 silent-accept behaviour for snapshots
2866 /// that load through but don't actually depend on the
2867 /// collation semantics.
2868 #[must_use]
2869 pub fn from_collation_name(name: &str) -> Self {
2870 let lc = name.trim().to_ascii_lowercase();
2871 // Strip any quotes / schema-qualifier the parser left on
2872 // (e.g. `pg_catalog.default`).
2873 let bare = lc
2874 .trim_matches(|c: char| c == '"' || c == '\'')
2875 .rsplit('.')
2876 .next()
2877 .unwrap_or("");
2878 if bare.is_empty() {
2879 return Self::Binary;
2880 }
2881 if bare == "case_insensitive" || bare == "nocase" {
2882 return Self::CaseInsensitive;
2883 }
2884 // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2885 // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2886 if bare.ends_with("_ci") {
2887 return Self::CaseInsensitive;
2888 }
2889 Self::Binary
2890 }
2891}
2892
2893/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2894/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2895/// parse into this shape — the column-level form has a single-entry
2896/// `columns` / `parent_columns`.
2897#[derive(Debug, Clone, PartialEq)]
2898pub struct ForeignKeyConstraint {
2899 /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2900 /// today but parses + stores it so a future ALTER TABLE DROP
2901 /// CONSTRAINT can target by name (v7.6.8).
2902 pub name: Option<String>,
2903 /// Local columns participating in the FK (≥ 1).
2904 pub columns: Vec<String>,
2905 /// Referenced parent table.
2906 pub parent_table: String,
2907 /// Referenced parent columns. Must have the same arity as
2908 /// `columns`; engine validates parent has a PK / UNIQUE index
2909 /// on exactly this column set (v7.6.1).
2910 pub parent_columns: Vec<String>,
2911 /// `ON DELETE` action. Defaults to `Restrict` if absent.
2912 pub on_delete: FkAction,
2913 /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2914 pub on_update: FkAction,
2915 /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2916 pub match_type: MatchType,
2917 /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2918 /// dropped on the floor, so a constraint declared DEFERRABLE was
2919 /// enforced immediately and a circular-FK migration could not load.
2920 pub deferrable: bool,
2921 /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2922 /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2923 pub initially_deferred: bool,
2924}
2925
2926/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2927/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2928/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2929#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2930pub enum MatchType {
2931 #[default]
2932 Simple,
2933 Full,
2934}
2935
2936/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2937#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2938pub enum FkAction {
2939 /// Reject the parent mutation if any child row references it.
2940 /// SQL spec default; SPG default when no clause is given.
2941 Restrict,
2942 /// Recursively propagate the parent's delete / update to the
2943 /// child rows. Same TX.
2944 Cascade,
2945 /// Set the child FK column(s) to NULL. Requires the FK columns
2946 /// to be NULL-able.
2947 SetNull,
2948 /// Set the child FK column(s) to their declared DEFAULT.
2949 /// Requires the child column(s) to have DEFAULT.
2950 SetDefault,
2951 /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2952 /// `Restrict` because the single-writer model has no deferred
2953 /// constraint window; the keyword is accepted for compatibility.
2954 NoAction,
2955}
2956
2957/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2958/// optional `USING <encoding>` clause; omitting it keeps the
2959/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2960/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2961/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2962/// binary16 (2× compression, ~3 decimal digits of precision).
2963#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2964pub enum VecEncoding {
2965 /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
2966 /// uncompressed `vector` type wire / storage layout.
2967 #[default]
2968 F32,
2969 /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
2970 /// `spg_storage::quantize::Sq8Vector` for the math + recall
2971 /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
2972 /// dim ≥ 32).
2973 Sq8,
2974 /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
2975 /// per-element. DDL keyword `HALF` (pgvector convention).
2976 /// Bit-exact dequantise to f32 at the storage layer; no
2977 /// rerank pass needed for kNN search.
2978 F16,
2979}
2980
2981impl fmt::Display for VecEncoding {
2982 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2983 match self {
2984 Self::F32 => f.write_str("F32"),
2985 Self::Sq8 => f.write_str("SQ8"),
2986 // pgvector convention: DDL keyword is `HALF`, not `F16`.
2987 Self::F16 => f.write_str("HALF"),
2988 }
2989 }
2990}
2991
2992/// SQL-level type names. The mapping to the storage runtime's `DataType`
2993/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
2994#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2995pub enum ColumnTypeName {
2996 /// v7.39 (round 291) — PG's `name`, the identifier type its
2997 /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
2998 /// answered `type "name" does not exist` to.
2999 Name,
3000 /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
3001 /// 32-bit wrapping counter the row header carries; `xid8` is the
3002 /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
3003 /// SPG answered `type "xid" does not exist` to.
3004 Xid,
3005 Xid8,
3006 /// v7.39 (round 667) — `OID`. `XID` was already a column type here
3007 /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
3008 /// `type "oid" does not exist` while `t(x XID)` built fine.
3009 Oid,
3010 SmallInt,
3011 Int,
3012 BigInt,
3013 Float,
3014 /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
3015 /// IEEE. It used to map to [`Self::Float`] on the theory that a
3016 /// wider float is harmless, but the width is observable: a `real`
3017 /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
3018 /// answered false where PG answers true.
3019 Real,
3020 Text,
3021 /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
3022 Varchar(u32),
3023 /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
3024 Char(u32),
3025 Bool,
3026 /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
3027 /// `USING <encoding>` clause; omitting it surfaces as
3028 /// `encoding = VecEncoding::F32` (the pre-v6 default).
3029 Vector {
3030 dim: u32,
3031 encoding: VecEncoding,
3032 },
3033 /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
3034 /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
3035 /// v7.39 (round 271) — scale widened to u16 alongside the value's.
3036 /// v7.39 (round 272) — precision too: PG's runs to 1000.
3037 /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
3038 /// a negative one rounds to tens / hundreds. A VALUE's display scale
3039 /// stays unsigned.
3040 Numeric(u16, i16),
3041 /// `DATE` — calendar day, no time-of-day component.
3042 Date,
3043 /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
3044 /// precision.
3045 Timestamp,
3046 /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
3047 /// stores all timestamps as UTC microseconds-since-epoch and
3048 /// does not carry per-row offset (PG's internal representation
3049 /// is the same — TZ is a display convention). The distinction
3050 /// from `TIMESTAMP` exists for the PG-wire layer to advertise
3051 /// OID 1184 so sqlx-style clients decode into
3052 /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
3053 Timestamptz,
3054 /// v4.9 `JSON` — text-backed JSON document. No parse-time
3055 /// validation; the engine round-trips the literal verbatim.
3056 /// PG OID 114 on the wire.
3057 Json,
3058 /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
3059 /// PG OID 3802 on the wire so sqlx-style binary-typed clients
3060 /// decode without a custom type registration.
3061 Jsonb,
3062 /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
3063 /// Literal forms (decoded by the engine at coercion time):
3064 /// - PG hex form: `'\xDEADBEEF'`
3065 /// - Escape form: `'foo\\000bar'` (backslash octal triples)
3066 Bytes,
3067 /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
3068 /// OID 1009. Literal forms accepted by the parser:
3069 /// - `ARRAY['a', 'b', NULL]`
3070 /// - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
3071 /// form at coerce time)
3072 TextArray,
3073 /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
3074 /// 1007. Same literal forms as TEXT[] (substituting integer
3075 /// elements).
3076 IntArray,
3077 /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
3078 /// OID 1016.
3079 BigIntArray,
3080 /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
3081 /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
3082 /// external form). G-CRIT-3.
3083 TsVector,
3084 /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
3085 /// wire OID 3615.
3086 TsQuery,
3087 /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
3088 /// Literal input accepts canonical hyphenated, unhyphenated,
3089 /// uppercase, and `{...}`-braced forms; display normalises to
3090 /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
3091 /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
3092 /// gen_random_uuid()`.
3093 Uuid,
3094 /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
3095 /// microseconds since 00:00:00. PG wire OID 1083. Literal
3096 /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
3097 /// (6-digit microsecond precision). Display normalises to
3098 /// the canonical `HH:MM:SS[.ffffff]`.
3099 Time,
3100 /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
3101 /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
3102 /// PG OID; advertised as INT4 on the wire. Display always
3103 /// 4 digits zero-padded.
3104 Year,
3105 /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
3106 /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
3107 /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
3108 /// Offset range: ±14 hours.
3109 TimeTz,
3110 /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
3111 /// (locale-independent storage). Wire OID 790. Literal input
3112 /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
3113 /// major units), optional leading `-`. Display: en_US locale.
3114 Money,
3115 /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
3116 /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
3117 /// — the engine bridges to `DataType::Range(RangeKind)`.
3118 Range(RangeKindAst),
3119 /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
3120 /// `text => text` map with NULL value support.
3121 Hstore,
3122 /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
3123 IntArray2D,
3124 BigIntArray2D,
3125 TextArray2D,
3126 /// v7.39 (read01 round 75) — `bool[][]`.
3127 BoolArray2D,
3128 /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
3129 /// three-field {months, days, micros} struct (PG-byte-equal),
3130 /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
3131 /// β-P2 `INTERVAL` was runtime-only — literal in expression
3132 /// position but rejected at CREATE TABLE.
3133 Interval,
3134 /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
3135 /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
3136 /// PG external form quotes each non-NULL element because
3137 /// interval text contains spaces / colons
3138 /// (`{"1 day","24:00:00",NULL}`).
3139 IntervalArray,
3140 /// v7.37.5 γ — full PG array-of-scalar family. Each variant
3141 /// mirrors a scalar `ColumnTypeName` that already existed.
3142 BoolArray,
3143 SmallIntArray,
3144 FloatArray,
3145 NumericArray,
3146 DateArray,
3147 TimestampArray,
3148 TimestamptzArray,
3149 UuidArray,
3150 JsonArray,
3151 JsonbArray,
3152 BytesArray,
3153 VarcharArray,
3154 CharArray,
3155 /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
3156 /// as `Range(RangeKindAst)` — one column type variant covers
3157 /// all six builtin multiranges, kind pins the element type.
3158 /// Wire OIDs in pgwire.
3159 Multirange(RangeKindAst),
3160 /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3161 /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3162 /// Wire OIDs in pgwire.
3163 Point,
3164 Lseg,
3165 Path,
3166 PgBox,
3167 Polygon,
3168 Line,
3169 Circle,
3170 /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3171 Inet,
3172 Cidr,
3173 Macaddr,
3174 Macaddr8,
3175 /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3176 Bit(u32),
3177 /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3178 BitVarying(u32),
3179 Xml,
3180 Char1,
3181 MoneyArray,
3182}
3183
3184/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3185/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3186/// crate doesn't depend on storage. Bridged at engine boundary.
3187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3188pub enum RangeKindAst {
3189 Int4,
3190 Int8,
3191 Num,
3192 Ts,
3193 TsTz,
3194 Date,
3195}
3196
3197impl fmt::Display for ColumnTypeName {
3198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3199 match self {
3200 Self::SmallInt => f.write_str("SMALLINT"),
3201 Self::Int => f.write_str("INT"),
3202 Self::BigInt => f.write_str("BIGINT"),
3203 Self::Float => f.write_str("FLOAT"),
3204 Self::Real => f.write_str("REAL"),
3205 Self::Text => f.write_str("TEXT"),
3206 Self::Name => f.write_str("name"),
3207 Self::Xid => f.write_str("xid"),
3208 Self::Xid8 => f.write_str("xid8"),
3209 Self::Oid => f.write_str("oid"),
3210 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3211 Self::Char(n) => write!(f, "CHAR({n})"),
3212 Self::Bool => f.write_str("BOOL"),
3213 Self::Vector { dim, encoding } => match encoding {
3214 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3215 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3216 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3217 },
3218 Self::Json => f.write_str("JSON"),
3219 Self::Jsonb => f.write_str("JSONB"),
3220 Self::Bytes => f.write_str("BYTEA"),
3221 Self::TextArray => f.write_str("TEXT[]"),
3222 Self::IntArray => f.write_str("INT[]"),
3223 Self::BigIntArray => f.write_str("BIGINT[]"),
3224 Self::TsVector => f.write_str("TSVECTOR"),
3225 Self::TsQuery => f.write_str("TSQUERY"),
3226 Self::Uuid => f.write_str("UUID"),
3227 Self::Numeric(p, s) => {
3228 if *s == 0 {
3229 write!(f, "NUMERIC({p})")
3230 } else {
3231 write!(f, "NUMERIC({p}, {s})")
3232 }
3233 }
3234 Self::Date => f.write_str("DATE"),
3235 Self::Timestamp => f.write_str("TIMESTAMP"),
3236 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3237 Self::Time => f.write_str("TIME"),
3238 Self::Year => f.write_str("YEAR"),
3239 Self::TimeTz => f.write_str("TIMETZ"),
3240 Self::Money => f.write_str("MONEY"),
3241 Self::Range(k) => f.write_str(match k {
3242 RangeKindAst::Int4 => "INT4RANGE",
3243 RangeKindAst::Int8 => "INT8RANGE",
3244 RangeKindAst::Num => "NUMRANGE",
3245 RangeKindAst::Ts => "TSRANGE",
3246 RangeKindAst::TsTz => "TSTZRANGE",
3247 RangeKindAst::Date => "DATERANGE",
3248 }),
3249 Self::Hstore => f.write_str("HSTORE"),
3250 Self::Interval => f.write_str("INTERVAL"),
3251 Self::IntervalArray => f.write_str("INTERVAL[]"),
3252 Self::BoolArray => f.write_str("BOOL[]"),
3253 Self::SmallIntArray => f.write_str("SMALLINT[]"),
3254 Self::FloatArray => f.write_str("FLOAT[]"),
3255 Self::NumericArray => f.write_str("NUMERIC[]"),
3256 Self::DateArray => f.write_str("DATE[]"),
3257 Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3258 Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3259 Self::UuidArray => f.write_str("UUID[]"),
3260 Self::JsonArray => f.write_str("JSON[]"),
3261 Self::JsonbArray => f.write_str("JSONB[]"),
3262 Self::BytesArray => f.write_str("BYTEA[]"),
3263 Self::VarcharArray => f.write_str("VARCHAR[]"),
3264 Self::CharArray => f.write_str("CHAR[]"),
3265 Self::Multirange(k) => f.write_str(match k {
3266 RangeKindAst::Int4 => "INT4MULTIRANGE",
3267 RangeKindAst::Int8 => "INT8MULTIRANGE",
3268 RangeKindAst::Num => "NUMMULTIRANGE",
3269 RangeKindAst::Ts => "TSMULTIRANGE",
3270 RangeKindAst::TsTz => "TSTZMULTIRANGE",
3271 RangeKindAst::Date => "DATEMULTIRANGE",
3272 }),
3273 Self::Point => f.write_str("POINT"),
3274 Self::Lseg => f.write_str("LSEG"),
3275 Self::Path => f.write_str("PATH"),
3276 Self::PgBox => f.write_str("BOX"),
3277 Self::Polygon => f.write_str("POLYGON"),
3278 Self::Line => f.write_str("LINE"),
3279 Self::Circle => f.write_str("CIRCLE"),
3280 Self::Inet => f.write_str("INET"),
3281 Self::Cidr => f.write_str("CIDR"),
3282 Self::Macaddr => f.write_str("MACADDR"),
3283 Self::Macaddr8 => f.write_str("MACADDR8"),
3284 Self::Bit(0) => f.write_str("BIT"),
3285 Self::Bit(n) => write!(f, "BIT({n})"),
3286 Self::BitVarying(0) => f.write_str("VARBIT"),
3287 Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3288 Self::Xml => f.write_str("XML"),
3289 Self::Char1 => f.write_str("\"char\""),
3290 Self::MoneyArray => f.write_str("MONEY[]"),
3291 Self::IntArray2D => f.write_str("INT[][]"),
3292 Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3293 Self::TextArray2D => f.write_str("TEXT[][]"),
3294 Self::BoolArray2D => f.write_str("BOOL[][]"),
3295 }
3296 }
3297}
3298
3299/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3300/// engine evaluates `expr` per matched row in the table's row order
3301/// and rewrites cells in place. Indexed columns are dropped + re-
3302/// inserted into the affected B-tree on each row change.
3303/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3304/// tail on a DML statement. Boxed off the statement struct so the PG-only
3305/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3306/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3307/// the identical meaning, so both share this one payload rather than each
3308/// growing its own.
3309#[derive(Debug, Clone, PartialEq)]
3310pub struct DmlOrderLimit {
3311 pub order_by: Vec<OrderBy>,
3312 pub limit: Option<u32>,
3313}
3314
3315/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3316/// FROM, kept so the engine can finish the job.
3317///
3318/// The parser rewrites the statement onto correlated subqueries, and it
3319/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3320/// name belongs to the target or to a source needs their column lists,
3321/// which parse time does not have. Carrying the clause lets the engine
3322/// — which has the catalog — resolve the rest.
3323#[derive(Debug, Clone, PartialEq)]
3324pub struct UpdateFromSources {
3325 pub from: FromClause,
3326 pub sub_where: Option<Expr>,
3327}
3328
3329#[derive(Debug, Clone, PartialEq)]
3330pub struct UpdateStatement {
3331 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3332 /// level UPDATE. Empty for a plain UPDATE.
3333 pub ctes: Vec<Cte>,
3334 pub table: String,
3335 /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3336 /// to `t`'s own rows and not to anything that descends from it.
3337 ///
3338 /// Round 644 taught the FROM clause the keyword and left DML behind
3339 /// because it needed a field here, and this struct carries a warning
3340 /// that round 413 measured widening it in place overflowing the
3341 /// parser's nesting stack. That warning was about `from_sources`, a
3342 /// struct wide enough to need boxing; a `bool` lands in the padding
3343 /// already present — same as `CreateTableStatement::temporary`.
3344 ///
3345 /// It also earns its keep beyond the spelling: the inheritance
3346 /// fan-out needs a way to say "the parent's own rows" as a
3347 /// statement, or running one on the parent recurses forever.
3348 pub only: bool,
3349 /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3350 /// statement's expressions refer to the target row by. PG allows the
3351 /// bare spelling here (unlike INSERT, which requires AS).
3352 pub alias: Option<String>,
3353 pub assignments: Vec<(String, Expr)>,
3354 /// v7.39 (round 533) — boxed: round 413 measured that widening this
3355 /// struct in place overflows the parser's nesting stack.
3356 pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3357 pub where_: Option<Expr>,
3358 /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3359 /// mutate the first `limit` rows in the given order. PG has no such
3360 /// clause; the parser accepts it only under the MySQL dialect. Boxed
3361 /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3362 /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3363 /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3364 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3365 /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3366 /// clause (legacy CommandComplete path). Some = engine
3367 /// evaluates the projection over each mutated row and
3368 /// streams the result as a Rows QueryResult.
3369 pub returning: Option<Vec<SelectItem>>,
3370}
3371
3372/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3373/// from the active catalog and prunes them from every index.
3374#[derive(Debug, Clone, PartialEq)]
3375pub struct DeleteStatement {
3376 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3377 /// level DELETE. Empty for a plain DELETE.
3378 pub ctes: Vec<Cte>,
3379 pub table: String,
3380 /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3381 /// to `t`'s own rows and not to anything that descends from it.
3382 ///
3383 /// Round 644 taught the FROM clause the keyword and left DML behind
3384 /// because it needed a field here, and this struct carries a warning
3385 /// that round 413 measured widening it in place overflowing the
3386 /// parser's nesting stack. That warning was about `from_sources`, a
3387 /// struct wide enough to need boxing; a `bool` lands in the padding
3388 /// already present — same as `CreateTableStatement::temporary`.
3389 ///
3390 /// It also earns its keep beyond the spelling: the inheritance
3391 /// fan-out needs a way to say "the parent's own rows" as a
3392 /// statement, or running one on the parent recurses forever.
3393 pub only: bool,
3394 /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3395 /// the WHERE / RETURNING expressions refer to the target row by.
3396 pub alias: Option<String>,
3397 pub where_: Option<Expr>,
3398 /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3399 /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3400 /// form (round 413), so it shares that payload — and it is boxed for
3401 /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3402 /// statement tipped the parser's 512 KiB nesting stack.
3403 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3404 /// v7.9.4 — `RETURNING <projection>`.
3405 pub returning: Option<Vec<SelectItem>>,
3406}
3407
3408/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3409/// One WHEN clause fires per source row depending on whether the
3410/// `on` condition matched any target row(s); the executor walks
3411/// `clauses` in declaration order and fires the first whose
3412/// `matched` kind and optional `condition` are both satisfied.
3413#[derive(Debug, Clone, PartialEq)]
3414pub struct MergeStatement {
3415 /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3416 /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3417 /// in PG). Each CTE materialises before the merge runs and its alias
3418 /// resolves as a source relation.
3419 pub ctes: Vec<Cte>,
3420 pub target: String,
3421 pub target_alias: Option<String>,
3422 pub source: String,
3423 pub source_alias: Option<String>,
3424 /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3425 /// the engine materialises this SELECT for the source rows and `source`
3426 /// is empty; the alias (required by PG for a subquery source) is in
3427 /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3428 pub source_select: Option<Box<SelectStatement>>,
3429 /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3430 /// positional column-alias list after the source alias. Empty when
3431 /// the statement carries none; the engine renames the materialised
3432 /// source columns positionally (PG's rule).
3433 pub source_column_aliases: Vec<String>,
3434 pub on: Expr,
3435 pub clauses: Vec<MergeWhenClause>,
3436 /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3437 /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3438 /// target/source aliases. `None` = no RETURNING (the common form).
3439 pub returning: Option<Vec<SelectItem>>,
3440}
3441
3442#[derive(Debug, Clone, PartialEq)]
3443pub struct MergeWhenClause {
3444 pub matched: MergeMatched,
3445 /// Optional `AND <expr>` filter — when present, the clause
3446 /// only fires for the source rows whose match-pair satisfies
3447 /// the predicate.
3448 pub condition: Option<Expr>,
3449 pub action: MergeAction,
3450}
3451
3452#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3453pub enum MergeMatched {
3454 Matched,
3455 /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3456 /// target row (the classic insert branch).
3457 NotMatched,
3458 /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3459 /// row no source row matches. Actions are UPDATE / DELETE / DO
3460 /// NOTHING only (INSERT is a syntax error, as in PG).
3461 NotMatchedBySource,
3462}
3463
3464#[derive(Debug, Clone, PartialEq)]
3465pub enum MergeAction {
3466 /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3467 /// explicit column list (the bare `INSERT VALUES (vals)`
3468 /// shape lands later).
3469 Insert {
3470 columns: Vec<String>,
3471 values: Vec<Expr>,
3472 },
3473 /// `UPDATE SET col = expr [, …]` — applied to every matched
3474 /// target row for the firing source row.
3475 Update { assignments: Vec<(String, Expr)> },
3476 /// `DELETE` — drop every matched target row.
3477 Delete,
3478 /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3479 /// the clause and SPG mirrors so a customer-side MERGE that
3480 /// uses it for branch-control doesn't error).
3481 DoNothing,
3482}
3483
3484#[derive(Debug, Clone, PartialEq)]
3485pub struct InsertStatement {
3486 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3487 /// level INSERT (writable CTE outer body). Empty for a plain
3488 /// INSERT. PG semantics: each CTE materialises before the
3489 /// outer INSERT runs, sharing the same transaction.
3490 pub ctes: Vec<Cte>,
3491 pub table: String,
3492 /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3493 /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3494 /// row by. PG requires the AS keyword in this position.
3495 pub alias: Option<String>,
3496 /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3497 /// `None`, every tuple is positional and must match the table arity.
3498 /// When `Some`, the engine maps each tuple slot to the named column and
3499 /// fills the rest with NULL (must be nullable).
3500 pub columns: Option<Vec<String>>,
3501 /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3502 /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3503 /// `select_source` is `Some` (the engine builds rows from the
3504 /// inner SELECT result set instead).
3505 pub rows: Vec<Vec<Expr>>,
3506 /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3507 /// round-5 G4). When present, `rows` is empty and the engine
3508 /// materialises the SELECT result, coerces each output tuple to
3509 /// the target column types, and inserts as a single batch.
3510 pub select_source: Option<Box<SelectStatement>>,
3511 /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3512 /// upsert clause. None = legacy INSERT (conflict raises a
3513 /// DuplicateKey error). mailrs migration blocker #2.
3514 pub on_conflict: Option<OnConflictClause>,
3515 /// v7.9.4 — `RETURNING <projection>`.
3516 pub returning: Option<Vec<SelectItem>>,
3517 /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3518 /// between the column list and VALUES. Governs how explicitly-supplied
3519 /// values interact with `GENERATED … AS IDENTITY` columns:
3520 /// * `None` — default. A `GENERATED ALWAYS` identity column rejects
3521 /// an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3522 /// * `System` — override the ALWAYS restriction: the explicit value
3523 /// is used verbatim, as for a `BY DEFAULT` column.
3524 /// * `User` — ignore any explicit value on a `BY DEFAULT` identity
3525 /// column and generate from the sequence instead (no effect on
3526 /// non-identity columns).
3527 pub overriding: Overriding,
3528 /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3529 /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3530 /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3531 /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3532 /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3533 /// into a NOT NULL column becomes the type's default), and the engine
3534 /// cannot recover that intent from the conflict clause alone. A plain
3535 /// `bool` lands in this struct's existing padding, so the AST does not
3536 /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3537 pub mysql_ignore: bool,
3538}
3539
3540/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3541#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3542pub enum Overriding {
3543 /// No `OVERRIDING` clause.
3544 #[default]
3545 None,
3546 /// `OVERRIDING SYSTEM VALUE`.
3547 System,
3548 /// `OVERRIDING USER VALUE`.
3549 User,
3550}
3551
3552/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3553#[derive(Debug, Clone, PartialEq)]
3554pub struct OnConflictClause {
3555 /// Local columns that identify the conflict (must match a
3556 /// UNIQUE / PRIMARY KEY index on the target table). Empty
3557 /// list means the user wrote `ON CONFLICT DO …` without a
3558 /// target — the engine arbitrates on every unique constraint
3559 /// (round 240).
3560 pub target_columns: Vec<String>,
3561 /// v7.39 (round 240) — the index predicate after the target list
3562 /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3563 /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3564 /// which satisfy any predicate, so it is parsed and carried but not
3565 /// consulted (recorded residual: partial-unique-index arbiters).
3566 pub index_where: Option<Expr>,
3567 /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3568 /// <name>`: the pg_dump conflict-target form. The engine
3569 /// resolves the name to the constraint's columns.
3570 pub constraint_name: Option<String>,
3571 /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3572 /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3573 /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3574 /// `ON CONFLICT DO UPDATE` is refused (42601).
3575 pub mysql_lowered: bool,
3576 /// The action on conflict.
3577 pub action: OnConflictAction,
3578}
3579
3580/// v7.9.7 — action on conflict.
3581#[derive(Debug, Clone, PartialEq)]
3582pub enum OnConflictAction {
3583 /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3584 /// silently skips conflicting ones.
3585 Nothing,
3586 /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3587 /// may reference `EXCLUDED.col` to read the incoming row's
3588 /// value (engine wires `EXCLUDED` as a virtual table).
3589 Update {
3590 assignments: Vec<(String, Expr)>,
3591 where_: Option<Expr>,
3592 },
3593}
3594
3595/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3596///
3597/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3598/// policies are spelled again here and mapped at the engine boundary.
3599/// v7.39 — the modes `BEGIN` / `START TRANSACTION` / `SET TRANSACTION`
3600/// / `SET SESSION CHARACTERISTICS` accept. `read_only` used to be parsed
3601/// and dropped on the floor, so `BEGIN READ ONLY` opened an ordinary
3602/// read-write transaction and every write in it was accepted.
3603///
3604/// `None` on either field means the statement did not name that mode, so
3605/// the session default applies — which is not the same as naming the
3606/// default explicitly.
3607#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3608pub struct TransactionModes {
3609 pub isolation: Option<IsolationLevel>,
3610 /// `Some(true)` = READ ONLY, `Some(false)` = READ WRITE.
3611 pub read_only: Option<bool>,
3612}
3613
3614/// v7.39 — what a read-only transaction refuses, and what PG calls it.
3615///
3616/// SPG did not enforce read-only transactions at all: `BEGIN READ ONLY;
3617/// INSERT …` answered `INSERT 0 1` and committed, and
3618/// `default_transaction_read_only = on` changed nothing. Both GUCs were
3619/// in the inventory, so a session could set one, read it back, and be
3620/// told it held a guarantee nothing was enforcing. Applications open
3621/// read-only transactions as a SAFETY measure — a reporting connection,
3622/// a read-only leg in a pool, a "this path must not write" discipline —
3623/// so accepting the writes is the worst possible answer.
3624///
3625/// `Some(tag)` means refuse with PG's message, `cannot execute {tag} in
3626/// a read-only transaction` (SQLSTATE 25006). Every tag below was read
3627/// back from PostgreSQL 18.6 by running the statement inside
3628/// `BEGIN READ ONLY`, one statement per transaction so no error could be
3629/// attributed to the wrong line.
3630///
3631/// Several answers were not what one would guess, which is why they were
3632/// measured rather than reasoned:
3633///
3634/// * `CREATE TEMP TABLE` is REFUSED, tagged `CREATE TABLE`.
3635/// * `NOTIFY`, `LISTEN` and `REINDEX` are ALLOWED.
3636/// * `PREPARE` of an INSERT is ALLOWED — only the EXECUTE writes.
3637/// * `UPDATE … WHERE false`, which changes nothing, is still REFUSED:
3638/// the verb decides, not the row count.
3639/// * `GRANT`, `COMMENT ON` and `SELECT … FOR SHARE` are all REFUSED.
3640///
3641/// The match is exhaustive on purpose. A new statement cannot be added
3642/// without deciding here whether it writes, which is the failure this
3643/// repository keeps meeting: one member of a family gets handled and its
3644/// siblings quietly do not.
3645impl Statement {
3646 #[must_use]
3647 pub fn read_only_violation_tag(&self) -> Option<&'static str> {
3648 match self {
3649 // v7.39.9 — MySQL's RENAME TABLE is DDL, refused read-only
3650 // for the same reason ALTER TABLE … RENAME TO is.
3651 Self::RenameTables(_) => Some("RENAME TABLE"),
3652 // ---- writes rows -------------------------------------------
3653 Self::Insert { .. } => Some("INSERT"),
3654 Self::Update { .. } => Some("UPDATE"),
3655 Self::Delete { .. } => Some("DELETE"),
3656 Self::Merge { .. } => Some("MERGE"),
3657 Self::Truncate { .. } => Some("TRUNCATE TABLE"),
3658 Self::CopyFromFile { .. } => Some("COPY FROM"),
3659
3660 // A SELECT that takes row locks writes lock state, and PG
3661 // names the strength it was asked for.
3662 Self::Select(sel) => sel.locking.as_ref().map(|l| match l.strength {
3663 LockStrength::Update => "SELECT FOR UPDATE",
3664 LockStrength::NoKeyUpdate => "SELECT FOR NO KEY UPDATE",
3665 LockStrength::Share => "SELECT FOR SHARE",
3666 LockStrength::KeyShare => "SELECT FOR KEY SHARE",
3667 }),
3668
3669 // ---- changes the catalog -----------------------------------
3670 Self::CreateTable { .. } => Some("CREATE TABLE"),
3671 Self::DropTable { .. } => Some("DROP TABLE"),
3672 Self::AlterTable { .. } => Some("ALTER TABLE"),
3673 Self::CreateIndex { .. } => Some("CREATE INDEX"),
3674 Self::DropIndex { .. } => Some("DROP INDEX"),
3675 Self::AlterIndex { .. } => Some("ALTER INDEX"),
3676 Self::CreateView { .. } => Some("CREATE VIEW"),
3677 Self::DropView { .. } => Some("DROP VIEW"),
3678 Self::CreateMaterializedView { .. } => Some("CREATE MATERIALIZED VIEW"),
3679 Self::RefreshMaterializedView { .. } => Some("REFRESH MATERIALIZED VIEW"),
3680 Self::DropMaterializedView { .. } => Some("DROP MATERIALIZED VIEW"),
3681 Self::CreateSequence { .. } => Some("CREATE SEQUENCE"),
3682 Self::AlterSequence { .. } => Some("ALTER SEQUENCE"),
3683 Self::DropSequence { .. } => Some("DROP SEQUENCE"),
3684 Self::CreateType { .. } => Some("CREATE TYPE"),
3685 Self::DropType { .. } => Some("DROP TYPE"),
3686 Self::AlterTypeAddValue { .. } | Self::AlterTypeRenameValue { .. } => {
3687 Some("ALTER TYPE")
3688 }
3689 Self::CreateDomain { .. } => Some("CREATE DOMAIN"),
3690 Self::AlterDomain { .. } => Some("ALTER DOMAIN"),
3691 Self::DropDomain { .. } => Some("DROP DOMAIN"),
3692 Self::CreateSchema { .. } => Some("CREATE SCHEMA"),
3693 Self::DropSchema { .. } => Some("DROP SCHEMA"),
3694 Self::CreateFunction { .. } => Some("CREATE FUNCTION"),
3695 Self::DropFunction { .. } => Some("DROP FUNCTION"),
3696 Self::CreateTrigger { .. } => Some("CREATE TRIGGER"),
3697 Self::DropTrigger { .. } => Some("DROP TRIGGER"),
3698 Self::CreateRule { .. } => Some("CREATE RULE"),
3699 Self::DropRule { .. } => Some("DROP RULE"),
3700 Self::CreateExtension { .. } => Some("CREATE EXTENSION"),
3701 Self::CreateStatistics { .. } => Some("CREATE STATISTICS"),
3702 Self::DropStatistics { .. } => Some("DROP STATISTICS"),
3703 Self::DropAggregate { .. } => Some("DROP AGGREGATE"),
3704 Self::CommentOn { .. } => Some("COMMENT"),
3705 Self::DropDatabase { .. } => Some("DROP DATABASE"),
3706 Self::CreatePublication { .. } => Some("CREATE PUBLICATION"),
3707 Self::DropPublication { .. } => Some("DROP PUBLICATION"),
3708 Self::CreateSubscription { .. } => Some("CREATE SUBSCRIPTION"),
3709 Self::DropSubscription { .. } => Some("DROP SUBSCRIPTION"),
3710
3711 // ---- changes roles / permissions ---------------------------
3712 Self::CreateUser { .. } => Some("CREATE ROLE"),
3713 Self::DropUser { .. } => Some("DROP ROLE"),
3714 Self::AlterRolePassword { .. } | Self::SetDbRoleSetting { .. } => Some("ALTER ROLE"),
3715 Self::Grant { .. } => Some("GRANT"),
3716 Self::Revoke { .. } => Some("REVOKE"),
3717 Self::CreatePolicy { .. } => Some("CREATE POLICY"),
3718 Self::AlterPolicy { .. } => Some("ALTER POLICY"),
3719 Self::DropPolicy { .. } => Some("DROP POLICY"),
3720 Self::AlterSystem { .. } => Some("ALTER SYSTEM"),
3721
3722 // ---- SPG's own writers -------------------------------------
3723 // Rewrites cold-tier segments on disk. PG has no equivalent to
3724 // ask, so the test is what it does, not what it is called.
3725 Self::CompactColdSegments => Some("COMPACT COLD SEGMENTS"),
3726
3727 // ---- allowed -----------------------------------------------
3728 // Reads, transaction control, session state, cursors, and the
3729 // maintenance statements PG itself permits. `REINDEX` really is
3730 // allowed in a read-only transaction (measured), which is why
3731 // `Maintain` is here.
3732 //
3733 // `Prepare`, `Execute`, `Call` and `DoBlock` are allowed at
3734 // this level for the reason PG allows them: the write inside
3735 // is refused when it runs, by this same check. Measured:
3736 // `PREPARE p AS INSERT …` succeeds; `DO $$ … INSERT … $$`
3737 // fails with `cannot execute INSERT`.
3738 Self::Explain { .. }
3739 | Self::CopyTo { .. }
3740 | Self::CopyToFile { .. }
3741 | Self::Analyze { .. }
3742 | Self::Maintain { .. }
3743 | Self::Vacuum { .. }
3744 | Self::Begin { .. }
3745 | Self::Commit
3746 | Self::Rollback
3747 | Self::Savepoint { .. }
3748 | Self::RollbackToSavepoint { .. }
3749 | Self::ReleaseSavepoint { .. }
3750 | Self::PrepareTransaction { .. }
3751 | Self::SetTransaction { .. }
3752 | Self::SetConstraints { .. }
3753 | Self::SetParameter { .. }
3754 | Self::SetParameterList { .. }
3755 | Self::SetUserVars { .. }
3756 | Self::SetRole { .. }
3757 | Self::ResetParameter { .. }
3758 | Self::ShowParameter { .. }
3759 | Self::Discard { .. }
3760 | Self::Prepare { .. }
3761 | Self::Execute { .. }
3762 | Self::Deallocate { .. }
3763 | Self::Call { .. }
3764 | Self::DoBlock { .. }
3765 | Self::DeclareCursor { .. }
3766 | Self::FetchCursor { .. }
3767 | Self::MoveCursor { .. }
3768 | Self::CloseCursor { .. }
3769 | Self::Listen { .. }
3770 | Self::Notify { .. }
3771 | Self::Unlisten { .. }
3772 | Self::Kill { .. }
3773 | Self::WaitForWalPosition { .. }
3774 | Self::ValidateOnly { .. }
3775 | Self::NoOpPreventedInTransaction { .. }
3776 | Self::Empty
3777 | Self::ShowTables
3778 | Self::ShowDatabases
3779 | Self::UseDatabase(_)
3780 | Self::ShowCreateTable { .. }
3781 | Self::ShowIndexes { .. }
3782 | Self::ShowStatus
3783 | Self::ShowVariables
3784 | Self::ShowVariablesLike { .. }
3785 | Self::ShowProcesslist
3786 | Self::ShowColumns { .. }
3787 | Self::ShowUsers
3788 | Self::ShowPublications
3789 | Self::ShowSubscriptions => None,
3790 }
3791 }
3792}
3793
3794#[derive(Debug, Clone, PartialEq, Eq)]
3795pub struct LockingClause {
3796 pub strength: LockStrength,
3797 /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3798 pub of_tables: Vec<String>,
3799 pub policy: LockWait,
3800}
3801
3802/// PG's four tuple-lock strengths, weakest first.
3803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3804pub enum LockStrength {
3805 KeyShare,
3806 Share,
3807 NoKeyUpdate,
3808 Update,
3809}
3810
3811/// What to do when the row is already locked.
3812#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3813pub enum LockWait {
3814 /// Block until it is free — PG's default.
3815 #[default]
3816 Wait,
3817 /// `NOWAIT` — fail the statement with 55P03.
3818 NoWait,
3819 /// `SKIP LOCKED` — leave the row out of the result.
3820 SkipLocked,
3821}
3822
3823#[derive(Debug, Clone, PartialEq, Default)]
3824pub struct SelectStatement {
3825 /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3826 /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3827 /// whole syntax and locked nothing: two workers running the classic
3828 /// `SKIP LOCKED` queue take both took the same row.
3829 /// v7.39 (round 305) — boxed. A locking clause appears on a
3830 /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3831 /// cost every `SelectStatement` 32 bytes, and this struct sits in
3832 /// recursive evaluation frames where the engine already runs close to
3833 /// its stack budget (a 512 KB depth guard is the canary).
3834 pub locking: Option<alloc::boxed::Box<LockingClause>>,
3835 /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3836 /// expressions, materialised once at query start before the
3837 /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3838 /// only — no `WITH RECURSIVE` for v4.x.
3839 pub ctes: Vec<Cte>,
3840 pub distinct: bool,
3841 /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3842 /// keep the first row (per ORDER BY) of each group the
3843 /// expressions define. Empty = no DISTINCT ON.
3844 pub distinct_on: Vec<Expr>,
3845 pub items: Vec<SelectItem>,
3846 pub from: Option<FromClause>,
3847 pub where_: Option<Expr>,
3848 pub group_by: Option<Vec<Expr>>,
3849 /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3850 /// expands `group_by` to every non-aggregate SELECT-list item
3851 /// before the executor runs. Mutually exclusive with an
3852 /// explicit `group_by` list (the parser sets exactly one).
3853 pub group_by_all: bool,
3854 /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3855 /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3856 /// aggregate executor resolves them through the same synthetic
3857 /// schema used for the SELECT items.
3858 pub having: Option<Expr>,
3859 /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3860 /// itself a `SelectStatement` with `order_by = None` and `limit =
3861 /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3862 /// top of the chain).
3863 pub unions: Vec<(UnionKind, SelectStatement)>,
3864 /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3865 /// Keys are matched left-to-right: first key decides, ties break
3866 /// to the second, etc.
3867 pub order_by: Vec<OrderBy>,
3868 /// `LIMIT <n>` — bound on row output. `n` is an integer
3869 /// literal **or** (v7.9.24) a placeholder `$N` resolved
3870 /// against the prepared-statement Bind values. mailrs
3871 /// migration follow-up H2.
3872 pub limit: Option<LimitExpr>,
3873 /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3874 /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3875 pub offset: Option<LimitExpr>,
3876 /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3877 /// (SQL:2008). When true and an ORDER BY is present, the
3878 /// executor extends past the LIMIT-truncated tail to include
3879 /// every row whose ORDER BY key equals the last-kept row's
3880 /// key. Requires an ORDER BY; the executor errors otherwise
3881 /// (matching PG's `WITH TIES` rule). The parser was already
3882 /// accepting `WITH TIES` since Phase 5.1; this field captures
3883 /// the choice so the executor can act on it.
3884 pub limit_with_ties: bool,
3885 /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3886 /// that NOTHING referenced. PG analyses every definition whether
3887 /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3888 /// and silently succeeded here — the referenced ones get their columns
3889 /// resolved through the WindowFunction nodes they were inlined into,
3890 /// and the unreferenced ones used to be dropped at parse, unexamined.
3891 /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3892 ///
3893 /// Not part of `Display`: an unreferenced definition has no effect on
3894 /// the result, so a deparsed body (a stored view) omits it.
3895 pub window_check_exprs: Vec<Expr>,
3896}
3897
3898impl Expr {
3899 /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3900 /// directly inside this expression to `f`. `f` receives each nested
3901 /// statement once; descending further (into that statement's own
3902 /// clauses) is the caller's job, which keeps this walk finite and
3903 /// lets the caller order the recursion.
3904 ///
3905 /// The match is deliberately **wildcard-free**: a new `Expr` variant
3906 /// does not compile until it says whether it can carry a subquery.
3907 /// The row-count resolution pass is built on this, and a shape it
3908 /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3909 /// which every row-count reader would take as "no limit", i.e. the
3910 /// whole table. Compile-time exhaustiveness is what rules that out.
3911 /// Iterative on purpose. Expression trees here get deep (long
3912 /// boolean chains, big IN lists), and this walk is on the path of
3913 /// every statement; recursing would add a frame per node to a stack
3914 /// budget the engine already runs close to — a depth guard that runs
3915 /// on a deliberately small stack caught exactly that. Depth costs
3916 /// heap here instead.
3917 pub fn for_each_subquery_mut<E>(
3918 &mut self,
3919 f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3920 ) -> Result<(), E> {
3921 let mut stack: Vec<&mut Self> = alloc::vec![self];
3922 while let Some(e) = stack.pop() {
3923 match e {
3924 Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3925 Self::NamedArg { expr, .. }
3926 | Self::Collate { expr, .. }
3927 | Self::Variadic(expr)
3928 | Self::Unary { expr, .. }
3929 | Self::Cast { expr, .. }
3930 | Self::FieldAccess { base: expr, .. }
3931 | Self::IsNull { expr, .. }
3932 | Self::BoolTest { expr, .. }
3933 | Self::Extract { source: expr, .. } => stack.push(expr),
3934 Self::Binary { lhs, rhs, .. } => {
3935 stack.push(lhs);
3936 stack.push(rhs);
3937 }
3938 Self::Like { expr, pattern, .. } => {
3939 stack.push(expr);
3940 stack.push(pattern);
3941 }
3942 Self::ArraySubscript { target, index } => {
3943 stack.push(target);
3944 stack.push(index);
3945 }
3946 Self::ArraySlice { target, lo, hi } => {
3947 stack.push(target);
3948 stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
3949 }
3950 Self::AnyAll { expr, array, .. } => {
3951 stack.push(expr);
3952 stack.push(array);
3953 }
3954 Self::FunctionCall { args, .. } | Self::Array(args) => {
3955 stack.extend(args.iter_mut());
3956 }
3957 Self::AggregateOrdered {
3958 call,
3959 order_by,
3960 filter,
3961 ..
3962 } => {
3963 stack.push(call);
3964 stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
3965 stack.extend(filter.iter_mut().map(|b| &mut **b));
3966 }
3967 Self::WindowFunction {
3968 args,
3969 partition_by,
3970 order_by,
3971 filter,
3972 ..
3973 } => {
3974 // `frame` bounds hold folded numbers / interval
3975 // parts, never expressions — nothing to visit there.
3976 stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
3977 stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
3978 stack.extend(filter.iter_mut().map(|b| &mut **b));
3979 }
3980 Self::InList { expr, list, .. } => {
3981 stack.push(expr);
3982 stack.extend(list.iter_mut());
3983 }
3984 Self::Case {
3985 operand,
3986 branches,
3987 else_branch,
3988 } => {
3989 stack.extend(
3990 operand
3991 .iter_mut()
3992 .chain(else_branch.iter_mut())
3993 .map(|b| &mut **b),
3994 );
3995 for (when, then) in branches.iter_mut() {
3996 stack.push(when);
3997 stack.push(then);
3998 }
3999 }
4000 Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
4001 Self::InSubquery { expr, subquery, .. } => {
4002 stack.push(expr);
4003 f(subquery)?;
4004 }
4005 Self::RowInSubquery { row, subquery, .. }
4006 | Self::RowCmpSubquery { row, subquery, .. } => {
4007 stack.extend(row.iter_mut());
4008 f(subquery)?;
4009 }
4010 }
4011 }
4012 Ok(())
4013 }
4014}
4015
4016/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
4017/// time or a placeholder `$N` resolved during extended-query
4018/// Bind. mailrs migration follow-up H2.
4019///
4020/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
4021/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
4022/// made the compiler point at every site that used to duplicate a
4023/// row-count out of the AST, which is exactly the set that must not
4024/// bypass the resolution pre-pass.
4025#[derive(Debug, Clone, PartialEq)]
4026pub enum LimitExpr {
4027 /// `LIMIT 10` — value known at parse time.
4028 Literal(u32),
4029 /// `LIMIT $N` — the 1-based parameter index, resolved against
4030 /// the bind values when the prepared statement executes.
4031 Placeholder(u16),
4032 /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
4033 /// greatest(2,3)`: a row-count expression that isn't constant, so
4034 /// it can't be folded at parse time. Evaluated once, before
4035 /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
4036 /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
4037 /// "no limit"). **No execution path may see this variant** —
4038 /// `as_literal` would report `None`, which every row-count reader
4039 /// takes to mean "unlimited", i.e. the whole table.
4040 Expr(alloc::boxed::Box<Expr>),
4041}
4042
4043impl fmt::Display for LimitExpr {
4044 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4045 match self {
4046 Self::Literal(n) => write!(f, "{n}"),
4047 Self::Placeholder(n) => write!(f, "${n}"),
4048 // Parenthesised so the round-trip text re-parses as one
4049 // row-count expression (`LIMIT (SELECT 4)`), which is also
4050 // the only spelling `FETCH FIRST` accepts.
4051 Self::Expr(e) => write!(f, "({e})"),
4052 }
4053 }
4054}
4055
4056impl LimitExpr {
4057 /// Convenience for the simple-query path where no placeholders
4058 /// can possibly exist. Returns the literal value or `None` if
4059 /// this is a placeholder (caller must surface as Unsupported).
4060 ///
4061 /// v7.39 (round 305) — `None` is read by every row-count consumer as
4062 /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
4063 /// therefore silently return the whole table, so the engine's
4064 /// `resolve_limit_exprs` pre-pass rewrites the variant away before
4065 /// dispatch. The assertion makes a missed nesting site fail loudly
4066 /// in every test build rather than quietly widening a result set.
4067 #[must_use]
4068 pub fn as_literal(&self) -> Option<u32> {
4069 match self {
4070 Self::Literal(n) => Some(*n),
4071 Self::Placeholder(_) => None,
4072 Self::Expr(_) => {
4073 debug_assert!(
4074 false,
4075 "LimitExpr::Expr reached execution — resolve_limit_exprs \
4076 missed a nesting site; treating it as `no limit` would \
4077 return every row"
4078 );
4079 None
4080 }
4081 }
4082 }
4083}
4084
4085/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
4086/// the engine's `substitute_placeholders` pass these are
4087/// always Literal; in the simple-query path a Placeholder
4088/// shape returns None (executor surfaces as
4089/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
4090impl SelectStatement {
4091 #[must_use]
4092 pub fn limit_literal(&self) -> Option<u32> {
4093 self.limit.as_ref().and_then(LimitExpr::as_literal)
4094 }
4095 #[must_use]
4096 pub fn offset_literal(&self) -> Option<u32> {
4097 self.offset.as_ref().and_then(LimitExpr::as_literal)
4098 }
4099}
4100
4101#[derive(Debug, Clone, PartialEq)]
4102pub struct Cte {
4103 pub name: String,
4104 /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
4105 /// classical case) or a data-modifying statement
4106 /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
4107 /// CTE semantics. The modifying body's RETURNING projection
4108 /// becomes the materialised CTE table the outer query can
4109 /// reference; the modifying statement runs once before the
4110 /// outer query, within the same transaction.
4111 pub body: CteBody,
4112 /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
4113 /// RECURSIVE keyword. Applies to every CTE in the clause per
4114 /// PG semantics. A non-recursive body in a RECURSIVE WITH is
4115 /// allowed; the engine just runs it once.
4116 pub recursive: bool,
4117 /// v4.22: optional `WITH name(a, b, c)` column-name list. When
4118 /// non-empty, these override the body's output column names
4119 /// position-by-position; the engine errors out if the count
4120 /// doesn't match the body's projection width.
4121 pub column_overrides: Vec<String>,
4122 /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
4123 /// SET seqcol` on a recursive CTE. Desugared at parse time into an
4124 /// extra ordering column on the body (see `rewrite_search_and_cycle`).
4125 pub search: Option<SearchClause>,
4126 /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
4127 /// USING pathcol` cycle detection, desugared at parse time.
4128 pub cycle: Option<CycleClause>,
4129}
4130
4131/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
4132#[derive(Debug, Clone, PartialEq)]
4133pub struct SearchClause {
4134 /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
4135 pub depth_first: bool,
4136 /// The CTE output columns the search orders by.
4137 pub by_columns: Vec<String>,
4138 /// The new column holding the ordering key (a row-array for depth,
4139 /// a `(depth, keys…)` row for breadth).
4140 pub set_column: String,
4141}
4142
4143/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
4144#[derive(Debug, Clone, PartialEq)]
4145pub struct CycleClause {
4146 /// Columns whose repetition along a path marks a cycle.
4147 pub columns: Vec<String>,
4148 /// The new boolean-ish column set to `mark_value` on a cycle.
4149 pub mark_column: String,
4150 /// Value written to `mark_column` when a cycle is detected (default
4151 /// `true`); `default_value` otherwise. PG allows any type; SPG carries
4152 /// them as literals.
4153 pub mark_value: Option<Literal>,
4154 pub default_value: Option<Literal>,
4155 /// The new column accumulating the visited-row path array.
4156 pub path_column: String,
4157}
4158
4159/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
4160/// (Insert / Update / Delete with optional RETURNING). The
4161/// data-modifying variants must carry a RETURNING projection for the
4162/// outer query to reference the CTE alias by; an empty RETURNING is
4163/// only valid if no outer reference materialises (rare — typically
4164/// caught at planning).
4165#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
4166#[derive(Debug, Clone, PartialEq)]
4167pub enum CteBody {
4168 Select(SelectStatement),
4169 Insert(Box<InsertStatement>),
4170 Update(Box<UpdateStatement>),
4171 Delete(Box<DeleteStatement>),
4172 /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
4173 /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
4174 Merge(Box<MergeStatement>),
4175}
4176
4177impl CteBody {
4178 /// Convenience accessor used by classical (read-only) CTE
4179 /// callsites that still expect a SELECT body. Returns None for
4180 /// data-modifying CTEs; callers must explicitly route those
4181 /// through `exec_with_ctes`'s modifying branch.
4182 #[must_use]
4183 pub fn as_select(&self) -> Option<&SelectStatement> {
4184 match self {
4185 Self::Select(s) => Some(s),
4186 _ => None,
4187 }
4188 }
4189
4190 #[must_use]
4191 pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
4192 match self {
4193 Self::Select(s) => Some(s),
4194 _ => None,
4195 }
4196 }
4197
4198 #[must_use]
4199 pub fn is_modifying(&self) -> bool {
4200 !matches!(self, Self::Select(_))
4201 }
4202}
4203
4204#[derive(Debug, Clone, PartialEq)]
4205pub struct OrderBy {
4206 pub expr: Expr,
4207 /// `false` = ASC (default), `true` = DESC.
4208 pub desc: bool,
4209 /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
4210 /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
4211 /// NULLS FIRST for DESC); the engine resolves the effective
4212 /// value via `nulls_first.unwrap_or(desc)`.
4213 pub nulls_first: Option<bool>,
4214 /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
4215 /// It lives here rather than in the expression for the same reason
4216 /// `desc` does: at an ORDER BY key a collation is ordering
4217 /// information, and nothing downstream of the sort needs it. A new
4218 /// `Expr` variant would instead put a new arm on `eval_expr`, which
4219 /// this repo has measured to overflow the debug stack.
4220 ///
4221 /// `None` means none was written, and the key falls back to whatever
4222 /// its COLUMN declares — which is every key that existed before this.
4223 pub collation: Option<String>,
4224}
4225
4226#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4227pub enum UnionKind {
4228 /// `UNION` — dedupes the combined set.
4229 Distinct,
4230 /// `UNION ALL` — concatenates without dedup.
4231 All,
4232 /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
4233 /// present on both sides.
4234 Intersect,
4235 /// `INTERSECT ALL` — multiset intersection (min per-row count).
4236 IntersectAll,
4237 /// `EXCEPT` — distinct left rows absent from the right.
4238 Except,
4239 /// `EXCEPT ALL` — multiset subtraction.
4240 ExceptAll,
4241}
4242
4243#[derive(Debug, Clone, PartialEq)]
4244pub enum SelectItem {
4245 Wildcard,
4246 /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
4247 /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
4248 /// `NEW` pseudo-relation).
4249 QualifiedWildcard(String),
4250 Expr {
4251 expr: Expr,
4252 alias: Option<String>,
4253 },
4254}
4255
4256#[derive(Debug, Clone, PartialEq)]
4257pub struct TableRef {
4258 pub name: String,
4259 pub alias: Option<String>,
4260 /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
4261 /// children.
4262 ///
4263 /// The keyword used to be absorbed at parse time, on the reasoning
4264 /// that SPG's inheritance children are separate relations a plain
4265 /// scan does not descend into — so ONLY already described what the
4266 /// scan did. That stopped being true when a partition parent
4267 /// started unioning its children: measured, `SELECT count(*) FROM
4268 /// ONLY <partitioned parent>` answered 2 where PG answers 0.
4269 pub only: bool,
4270 /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
4271 /// When `Some(id)`, the scan restricts to rows that live in
4272 /// segment `<id>` only — useful for forensic inspection of a
4273 /// specific freezer-emitted segment without exposing the hot
4274 /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
4275 /// is STABILITY carve-out for v6.10 — needs the freezer to
4276 /// stamp each segment with a wall-clock at creation time.
4277 pub as_of_segment: Option<u32>,
4278 /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
4279 /// source. When `Some`, `name` is the alias (defaulting to
4280 /// `"unnest"` when no `AS` is given) and the engine builds a
4281 /// synthetic single-column table by evaluating the expression
4282 /// once at SELECT entry. Each TEXT[] element becomes one row;
4283 /// NULL elements become NULL cells. v7.11 supported
4284 /// uncorrelated UNNEST only as the FROM primary; v7.13.2
4285 /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
4286 /// position (cross-join with regular tables).
4287 pub unnest_expr: Option<Box<Expr>>,
4288 /// v7.13.2 — mailrs round-6 S5. PG-standard
4289 /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
4290 /// when non-empty, the first entry overrides the projected
4291 /// column name for the unnested column. Empty = fall back to
4292 /// the table alias (pre-v7.13.2 behaviour).
4293 pub unnest_column_aliases: Vec<String>,
4294 /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
4295 /// row-stream gains a trailing BIGINT column counting rows
4296 /// from 1 in element order. PG names it `ordinality`; a second
4297 /// entry in the column-alias list renames it.
4298 pub with_ordinality: bool,
4299 /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
4300 /// [, step])` set-returning source. When `Some`, the engine
4301 /// materialises a single-column virtual table by stepping
4302 /// `start` to `stop` inclusive. Args are the literal arg list
4303 /// (2 for default-step, 3 for explicit-step). Supports:
4304 /// * SmallInt / Int / BigInt with integer step (default = 1)
4305 /// * Timestamp with INTERVAL step (PG date-range pattern)
4306 /// Mutually exclusive with `unnest_expr` — both populate the
4307 /// same downstream dispatch slot. `name` defaults to
4308 /// `"generate_series"` when no alias is provided.
4309 pub generate_series_args: Option<Vec<Expr>>,
4310 /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
4311 /// table. When `Some`, the TableRef is a parenthesised SELECT
4312 /// that may reference columns from the preceding FROM items
4313 /// (correlated derived table). The executor materialises the
4314 /// subquery per left-row, substituting outer-column references
4315 /// against the current join row's values before running the
4316 /// inner SELECT, then cross-joins the result back.
4317 /// Mutually exclusive with `name` / `unnest_expr` /
4318 /// `generate_series_args`.
4319 pub lateral_subquery: Option<Box<SelectStatement>>,
4320 /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
4321 /// function as a FROM item. PG semantics: for each key/value
4322 /// pair in the JSONB object argument, emit one (key TEXT,
4323 /// value TEXT) row. When prefixed by `LATERAL` and joined via
4324 /// `CROSS JOIN LATERAL`, the argument may reference columns
4325 /// from a preceding FROM item, in which case the executor
4326 /// evaluates `<expr>` per outer row.
4327 /// Mutually exclusive with `unnest_expr` / `generate_series_args`
4328 /// / `lateral_subquery`. The optional `LATERAL` keyword does not
4329 /// require a separate flag — the executor evaluates per-row
4330 /// whenever the join sits in a JoinKind context.
4331 ///
4332 /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
4333 /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
4334 /// `json_each` / `json_each_text`) so the executor picks the
4335 /// value-column rendering (JSON text vs unwrapped text).
4336 pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
4337 /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
4338 /// function channel: `(lowercase fn name, args)`. Carries
4339 /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
4340 /// dispatches by name.
4341 pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
4342 /// v7.39 (read01 round 78) — this FROM item is a call to a function that
4343 /// returns a BASE type, so the item's row type IS that scalar: a whole-row
4344 /// reference to it yields the value, not a one-field composite
4345 /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
4346 /// desugared shape is indistinguishable from a hand-written
4347 /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
4348 /// only the parser knows which one it built, so it says so here.
4349 pub scalar_fn_item: bool,
4350 /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
4351 /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
4352 /// target-list SRFs follow — see round 67). The array-returning family keeps
4353 /// its own lowering; this channel carries the ones that have no array form
4354 /// (`generate_series`, a user `RETURNS SETOF` function).
4355 pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
4356 /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4357 /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4358 /// tables (implicit LATERAL, like every SRF channel). Executed by
4359 /// walking the row path over the parsed doc, then each column's
4360 /// path per row-item; NESTED expands as a per-parent outer join.
4361 pub json_table: Option<Box<JsonTable>>,
4362}
4363
4364/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4365#[derive(Debug, Clone, PartialEq)]
4366pub struct JsonTable {
4367 /// The document expression (jsonb/json/text). May reference outer
4368 /// columns → implicit LATERAL.
4369 pub doc: Box<Expr>,
4370 /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4371 /// match is one row's context item.
4372 pub row_path: String,
4373 /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4374 pub columns: Vec<JsonTableColumn>,
4375 /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4376 pub passing: Vec<(String, Expr)>,
4377}
4378
4379/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4380#[derive(Debug, Clone, PartialEq)]
4381pub enum JsonTableColumn {
4382 /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4383 Ordinality { name: String },
4384 /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4385 /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4386 /// `<name> <type> EXISTS [PATH '<p>']`.
4387 Regular {
4388 name: String,
4389 ty: ColumnTypeName,
4390 /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4391 path: String,
4392 /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4393 exists: bool,
4394 /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4395 format_json: bool,
4396 /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4397 wrapper: bool,
4398 /// Behaviour when the path matches nothing (default NULL).
4399 on_empty: JsonTableOnBehavior,
4400 /// Behaviour when coercion fails (default NULL).
4401 on_error: JsonTableOnBehavior,
4402 },
4403 /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4404 /// row like a LEFT JOIN (a parent with no nested match still emits one
4405 /// row, nested cols NULL).
4406 Nested {
4407 path: String,
4408 columns: Vec<JsonTableColumn>,
4409 },
4410}
4411
4412/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4413#[derive(Debug, Clone, PartialEq)]
4414pub enum JsonTableOnBehavior {
4415 /// Default: the column value is NULL.
4416 Null,
4417 /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4418 Error,
4419 /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4420 Default(Box<Expr>),
4421}
4422
4423/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4424/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4425/// joins evaluate left-associatively in nested-loop order.
4426#[derive(Debug, Clone, PartialEq)]
4427pub struct FromClause {
4428 pub primary: TableRef,
4429 pub joins: Vec<FromJoin>,
4430}
4431
4432#[derive(Debug, Clone, PartialEq)]
4433pub struct FromJoin {
4434 pub kind: JoinKind,
4435 pub table: TableRef,
4436 /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4437 pub on: Option<Expr>,
4438 /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4439 /// USING column list so the executor can perform PG's column-merge
4440 /// (the join columns collapse to a single unqualified output column,
4441 /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4442 /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4443 /// USING into an equivalent `on` predicate so the join filter/count
4444 /// path works unchanged; `using_cols` drives only the output-shape
4445 /// rewrite. Empty/`None` for `ON` and CROSS joins.
4446 pub using_cols: Option<Vec<String>>,
4447 /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4448 /// column names are not known until the table schemas are available
4449 /// (parse time is schema-less), so the parser only sets this flag and
4450 /// leaves `on`/`using_cols` empty; the engine resolves the common
4451 /// columns at execution time, synthesises the `on` predicate + the
4452 /// USING column-merge, and clears the flag. If there are no common
4453 /// columns PG treats it as a CROSS join.
4454 pub natural: bool,
4455}
4456
4457#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4458pub enum JoinKind {
4459 Inner,
4460 Left,
4461 Cross,
4462 /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4463 /// NULL-filling the left (drive) columns on unmatched right rows.
4464 /// The executor runs the LEFT algorithm's mirror: it tracks which
4465 /// peer rows matched and emits the unmatched ones with a NULL-left
4466 /// tuple after the probe loop. Output column order is unchanged
4467 /// (left-table cols then right-table cols).
4468 Right,
4469 /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4470 /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4471 FullOuter,
4472 /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4473 /// once, paired with the first peer row that satisfies the ON. Not
4474 /// reachable from SQL — the EXISTS pull-up emits it, which is what
4475 /// frees positive EXISTS from the round-721 uniqueness gate (an
4476 /// INNER join would multiply the outer rows; a semi join cannot).
4477 Semi,
4478}
4479
4480#[derive(Debug, Clone, PartialEq)]
4481pub enum Expr {
4482 Literal(Literal),
4483 /// v7.39.2 — `<expr> COLLATE <name>`: the collation this expression
4484 /// compares under, whatever the column or the database says.
4485 ///
4486 /// The parser used to refuse the locale names in this position and
4487 /// SILENTLY ABSORB the byte-order ones, so `'a' COLLATE "C" < 'B'`
4488 /// answered `t` where PostgreSQL 18.6 answers `f` — the one family
4489 /// it let through is the one where dropping it changes the answer.
4490 ///
4491 /// Whether dropping is safe depends on the DATABASE's own collation,
4492 /// which the parser cannot see: under `SPG_LC_COLLATE=C` absorbing
4493 /// `COLLATE "C"` is exactly right. So the name rides along and the
4494 /// engine, which knows, decides.
4495 Collate {
4496 expr: Box<Expr>,
4497 collation: String,
4498 },
4499 Column(ColumnName),
4500 /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4501 /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4502 /// callee's declared parameter names, and a user function's live in the
4503 /// catalog — which the parser cannot see. So the name rides along in the
4504 /// tree and the evaluator, which has the catalog, does the reordering.
4505 /// Appears only inside a `FunctionCall`'s argument list.
4506 NamedArg {
4507 name: String,
4508 expr: Box<Expr>,
4509 },
4510 /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4511 /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4512 /// expression evaluates to an array whose elements the evaluator splices
4513 /// into the call as individual trailing arguments. Appears only inside a
4514 /// `FunctionCall`'s argument list.
4515 Variadic(Box<Expr>),
4516 /// v6.1.1 — `$N` parameter placeholder for the extended query
4517 /// protocol. The number is 1-based per PostgreSQL convention.
4518 /// Evaluation looks up `params[N-1]` from the prepared-statement
4519 /// bind buffer; out-of-range indices raise a runtime error
4520 /// (same shape as a column-not-found miss).
4521 Placeholder(u16),
4522 Binary {
4523 lhs: Box<Expr>,
4524 op: BinOp,
4525 rhs: Box<Expr>,
4526 },
4527 Unary {
4528 op: UnOp,
4529 expr: Box<Expr>,
4530 },
4531 /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4532 /// TEXT, BOOL targets; engine coerces at evaluation time.
4533 Cast {
4534 expr: Box<Expr>,
4535 target: CastTarget,
4536 },
4537 /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4538 /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4539 /// whole-row reference, or a composite-returning function); `field` names
4540 /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4541 /// column names for a whole-row). Only the parenthesised form reaches
4542 /// here — a bare `a.b` is parsed as a qualified column reference.
4543 FieldAccess {
4544 base: Box<Expr>,
4545 field: String,
4546 },
4547 /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4548 IsNull {
4549 expr: Box<Expr>,
4550 negated: bool,
4551 },
4552 /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4553 /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4554 /// `Some(false)` for FALSE and `None` for UNKNOWN.
4555 ///
4556 /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4557 /// The semantics were right, but the AST then had no way to say what
4558 /// the user wrote, so every renderer printed the lowering:
4559 /// `CHECK ((a > 1) IS TRUE)` came back as
4560 /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4561 /// dumped view lost the form too.
4562 BoolTest {
4563 expr: Box<Expr>,
4564 value: Option<bool>,
4565 negated: bool,
4566 },
4567 /// Function call `name(args...)`. v1.4 supports a small built-in set
4568 /// (length, upper, lower, abs, coalesce); unknown names error at eval
4569 /// time so the parser stays open for v1.5 aggregates.
4570 FunctionCall {
4571 name: String,
4572 args: Vec<Expr>,
4573 },
4574 /// v7.24 (mailrs round-16 A) — an aggregate call with an
4575 /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4576 /// Wraps the plain [`Expr::FunctionCall`] so every existing
4577 /// FunctionCall consumer stays untouched; only the aggregate
4578 /// executor (and the expression walkers) know the wrapper.
4579 /// Non-aggregate evaluation contexts reject it at eval time.
4580 AggregateOrdered {
4581 call: Box<Expr>,
4582 order_by: Vec<OrderBy>,
4583 /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4584 /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4585 /// aggregate modifier so plain FunctionCall stays untouched.
4586 distinct: bool,
4587 /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4588 /// Only the rows where `cond` is true contribute to this
4589 /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4590 /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4591 /// END)`, which is faithful for NULL-ignoring aggregates but
4592 /// WRONG for `array_agg` (it would collect a NULL per excluded
4593 /// row). The executor instead skips excluded rows before
4594 /// accumulation, which is correct for every aggregate.
4595 filter: Option<Box<Expr>>,
4596 },
4597 /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4598 /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4599 /// the next char (so `\%` matches a literal `%`).
4600 Like {
4601 expr: Box<Expr>,
4602 pattern: Box<Expr>,
4603 negated: bool,
4604 /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4605 /// match. PG folds both operands.
4606 case_insensitive: bool,
4607 },
4608 /// v4.12 window function call: `name(args) OVER (PARTITION BY
4609 /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4610 /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4611 /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4612 /// unordered windows and "from start of partition through
4613 /// current row" for ordered windows — no explicit ROWS /
4614 /// RANGE clause in v4.12 MVP.
4615 WindowFunction {
4616 name: String,
4617 args: Vec<Expr>,
4618 partition_by: Vec<Expr>,
4619 /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4620 /// (None = PG default, same contract as [`OrderBy`]).
4621 order_by: Vec<(
4622 Expr,
4623 bool, /* desc */
4624 Option<bool>, /* nulls_first */
4625 )>,
4626 /// v4.20 explicit frame. `None` means "use the default":
4627 /// whole-partition when unordered, running aggregate from
4628 /// partition start through current row when ordered.
4629 frame: Option<WindowFrame>,
4630 /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4631 /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4632 /// `Respect` (PG / ANSI default — NULLs participate). Other
4633 /// window functions ignore this flag.
4634 null_treatment: NullTreatment,
4635 /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4636 /// = no FILTER. Only aggregate window functions honor it; the
4637 /// predicate restricts which peer rows contribute within the frame.
4638 filter: Option<Box<Expr>>,
4639 },
4640 /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4641 /// position. Must return exactly one row × one column at eval
4642 /// time; the engine errors out otherwise. Uncorrelated only —
4643 /// the inner SELECT cannot reference outer columns.
4644 ScalarSubquery(Box<SelectStatement>),
4645 /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4646 /// projection is ignored; only row-count matters.
4647 Exists {
4648 subquery: Box<SelectStatement>,
4649 negated: bool,
4650 },
4651 /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4652 /// project exactly one column; membership is tested by Eq
4653 /// against each row's value (NULL handling follows ANSI:
4654 /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4655 InSubquery {
4656 expr: Box<Expr>,
4657 subquery: Box<SelectStatement>,
4658 negated: bool,
4659 },
4660 /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4661 /// against a multi-column subquery. Row comparisons against a *list*
4662 /// decompose to OR-of-AND at parse time, but the subquery form can't
4663 /// (its rows are only known at runtime), so this survives as its own
4664 /// node evaluated with PG's row-comparison three-valued logic.
4665 RowInSubquery {
4666 row: Vec<Expr>,
4667 subquery: Box<SelectStatement>,
4668 negated: bool,
4669 },
4670 /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4671 /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4672 /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4673 /// subquery form can't, so it survives as its own node. The subquery
4674 /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4675 RowCmpSubquery {
4676 row: Vec<Expr>,
4677 op: BinOp,
4678 subquery: Box<SelectStatement>,
4679 },
4680 /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4681 /// list. Both the parser's literal-list path and the engine's
4682 /// IN-subquery materialisation used to desugar into a left-deep
4683 /// OR-Eq chain, so expression depth scaled with the element count
4684 /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4685 /// (recursive eval AND recursive Box drop) and aborted embedding
4686 /// host processes. The flat node keeps depth constant: eval is an
4687 /// iterative scan with PG three-valued logic, drop is a Vec drop.
4688 InList {
4689 expr: Box<Expr>,
4690 list: Vec<Expr>,
4691 negated: bool,
4692 },
4693 /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4694 /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4695 /// because the `FROM` keyword is what separates the two halves,
4696 /// not a comma.
4697 Extract {
4698 field: ExtractField,
4699 source: Box<Expr>,
4700 },
4701 /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4702 /// element is evaluated independently; NULLs are allowed.
4703 /// v7.10 supports only single-dimension TEXT[] semantically;
4704 /// non-text elements coerce at engine evaluation time when
4705 /// the surrounding context (column type / cast) makes the
4706 /// target clear.
4707 Array(Vec<Expr>),
4708 /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4709 /// engine returns NULL for out-of-range indices.
4710 ArraySubscript {
4711 target: Box<Expr>,
4712 index: Box<Expr>,
4713 },
4714 /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4715 /// inclusive; a missing bound extends to that end of the
4716 /// array and out-of-range bounds clamp. Returns an array of
4717 /// the same element type.
4718 ArraySlice {
4719 target: Box<Expr>,
4720 lo: Option<Box<Expr>>,
4721 hi: Option<Box<Expr>>,
4722 },
4723 /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4724 /// operator is the comparison binary op (Eq / Ne / Lt / …);
4725 /// the engine desugars: `ANY` returns true if any element
4726 /// satisfies; `ALL` returns true only if every element does.
4727 /// NULL handling follows PG's three-valued logic.
4728 AnyAll {
4729 expr: Box<Expr>,
4730 op: BinOp,
4731 array: Box<Expr>,
4732 /// `true` = ANY, `false` = ALL.
4733 is_any: bool,
4734 },
4735 /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4736 /// (searched form, `operand` is None) and
4737 /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4738 /// `operand` is the lead expression compared against each
4739 /// branch's match). Each `(when_expr, then_expr)` branch
4740 /// stays as written; engine short-circuits on the first match.
4741 /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4742 /// mailrs round-5 G9.
4743 Case {
4744 operand: Option<Box<Expr>>,
4745 branches: Vec<(Expr, Expr)>,
4746 else_branch: Option<Box<Expr>>,
4747 },
4748}
4749
4750/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4751/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4752/// in the offset walk. `Ignore` causes the function to skip NULL
4753/// values in the argument expression, returning the next non-NULL.
4754#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4755pub enum NullTreatment {
4756 #[default]
4757 Respect,
4758 Ignore,
4759}
4760
4761/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4762/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4763/// where end implicitly = CURRENT ROW.
4764#[derive(Debug, Clone, PartialEq, Eq)]
4765pub struct WindowFrame {
4766 pub kind: FrameKind,
4767 pub start: FrameBound,
4768 pub end: Option<FrameBound>,
4769 /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4770 /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4771 /// no-op; CURRENT ROW drops the current row from the frame.
4772 pub exclude: FrameExclusion,
4773}
4774
4775#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4776pub enum FrameExclusion {
4777 /// Default — exclude nothing.
4778 #[default]
4779 NoOthers,
4780 /// Drop the current row from the frame.
4781 CurrentRow,
4782 /// Drop the current row's whole peer group.
4783 Group,
4784 /// Drop the current row's peers but keep the current row.
4785 Ties,
4786}
4787
4788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4789pub enum FrameKind {
4790 Rows,
4791 Range,
4792 /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4793 /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4794 /// bounds (no explicit integer offsets) GROUPS behaves identically
4795 /// to RANGE — both consult the peer-group of the current row.
4796 /// Integer offsets are not yet supported; the executor rejects
4797 /// them at run time.
4798 Groups,
4799}
4800
4801#[derive(Debug, Clone, PartialEq, Eq)]
4802pub enum FrameBound {
4803 UnboundedPreceding,
4804 OffsetPreceding(u64),
4805 CurrentRow,
4806 OffsetFollowing(u64),
4807 UnboundedFollowing,
4808 /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4809 /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4810 /// interval is folded to its (months, days, micros) components at
4811 /// parse time.
4812 IntervalPreceding {
4813 months: i32,
4814 days: i32,
4815 micros: i64,
4816 },
4817 IntervalFollowing {
4818 months: i32,
4819 days: i32,
4820 micros: i64,
4821 },
4822}
4823
4824impl fmt::Display for FrameBound {
4825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4826 match self {
4827 Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4828 Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4829 Self::CurrentRow => f.write_str("CURRENT ROW"),
4830 Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4831 Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4832 Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4833 Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4834 }
4835 }
4836}
4837
4838#[derive(Debug, Clone, PartialEq, Eq)]
4839pub enum ExtractField {
4840 Year,
4841 Month,
4842 Day,
4843 Hour,
4844 Minute,
4845 Second,
4846 Microsecond,
4847 /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4848 /// SPG keeps the integer convention — truncated seconds).
4849 Epoch,
4850 /// Day of week, 0 = Sunday … 6 = Saturday.
4851 Dow,
4852 /// ISO day of week, 1 = Monday … 7 = Sunday.
4853 Isodow,
4854 /// Day of year, 1-366.
4855 Doy,
4856 /// ISO 8601 week number, 1-53.
4857 Week,
4858 /// ISO 8601 week-numbering year (pairs with `Week`).
4859 Isoyear,
4860 /// Quarter, 1-4.
4861 Quarter,
4862 /// Year divided by 10 (floor).
4863 Decade,
4864 /// Century — 2001-2100 is century 21.
4865 Century,
4866 /// Millennium — 2001-3000 is millennium 3.
4867 Millennium,
4868 /// Julian day number (truncated for timestamps).
4869 Julian,
4870 /// Seconds and fraction in milliseconds (ss·1000 + frac).
4871 Millisecond,
4872 /// UTC offset in seconds — SPG sessions run UTC, so 0.
4873 Timezone,
4874 /// Hour component of the UTC offset — 0.
4875 TimezoneHour,
4876 /// Minute component of the UTC offset — 0.
4877 TimezoneMinute,
4878 /// v7.39 (round 253) — a field name the parser does not know. PG
4879 /// resolves EXTRACT fields at RUNTIME and reports them with the
4880 /// source type (`unit "nosuch" not recognized for type timestamp
4881 /// without time zone`, 22023), so the parser carries the raw name
4882 /// instead of rejecting.
4883 Other(String),
4884}
4885
4886impl fmt::Display for ExtractField {
4887 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4888 f.write_str(match self {
4889 Self::Year => "YEAR",
4890 Self::Month => "MONTH",
4891 Self::Day => "DAY",
4892 Self::Hour => "HOUR",
4893 Self::Minute => "MINUTE",
4894 Self::Second => "SECOND",
4895 Self::Microsecond => "MICROSECOND",
4896 Self::Epoch => "EPOCH",
4897 Self::Dow => "DOW",
4898 Self::Isodow => "ISODOW",
4899 Self::Doy => "DOY",
4900 Self::Week => "WEEK",
4901 Self::Isoyear => "ISOYEAR",
4902 Self::Quarter => "QUARTER",
4903 Self::Decade => "DECADE",
4904 Self::Century => "CENTURY",
4905 Self::Millennium => "MILLENNIUM",
4906 Self::Julian => "JULIAN",
4907 Self::Millisecond => "MILLISECOND",
4908 Self::Timezone => "TIMEZONE",
4909 Self::TimezoneHour => "TIMEZONE_HOUR",
4910 Self::TimezoneMinute => "TIMEZONE_MINUTE",
4911 Self::Other(name) => return f.write_str(name),
4912 })
4913 }
4914}
4915
4916#[derive(Debug, Clone, PartialEq, Eq)]
4917pub enum CastTarget {
4918 Int,
4919 BigInt,
4920 Float,
4921 Text,
4922 Bool,
4923 Vector,
4924 Date,
4925 Timestamp,
4926 /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4927 /// H3a. Engine reuses the existing runtime-interval / timestamp
4928 /// paths (parse the text input, return the matching Value).
4929 Interval,
4930 Timestamptz,
4931 /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4932 /// types (v7.9.0); the cast just routes Text→Json with the
4933 /// requested OID for the wire layer.
4934 Json,
4935 Jsonb,
4936 /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4937 /// compatibility; engine surfaces as Unsupported with a
4938 /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4939 RegType,
4940 RegClass,
4941 /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
4942 /// the PG external array form `{a,b,NULL}`.
4943 TextArray,
4944 /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
4945 /// `{1,2,3}` or widens a `TextArray` whose elements are
4946 /// integer-shaped.
4947 IntArray,
4948 BigIntArray,
4949 /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
4950 /// external form text representation. Used by pg_dump output
4951 /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
4952 TsVector,
4953 TsQuery,
4954 /// v7.17.0 — `::uuid`. Decodes the LHS Text via
4955 /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
4956 /// unhyphenated, uppercase, and brace-wrapped forms); malformed
4957 /// input is a SQL error.
4958 Uuid,
4959 /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
4960 /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
4961 /// inputs pass through unchanged. Closes the mailrs D-pre #3
4962 /// reverse-acceptance gap — anywhere a PG schema writes
4963 /// `expr::bytea`, SPG now matches.
4964 Bytea,
4965 /// v7.37.5 ship triage — generic cast target for the long tail
4966 /// of PG type names the parser meets in `expr::TYPE` shapes that
4967 /// don't deserve their own enum variant. The engine routes these
4968 /// through `column_type_to_data_type` + the existing typed
4969 /// `coerce_value` dispatch, so adding a new PG type to SPG
4970 /// implicitly adds its cast-target form too — no parser change
4971 /// per type. The string carries the lowercase PG type ident
4972 /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
4973 /// a clear message when the type isn't known.
4974 Named(String),
4975}
4976
4977impl fmt::Display for CastTarget {
4978 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4979 f.write_str(match self {
4980 Self::Int => "int",
4981 Self::BigInt => "bigint",
4982 Self::Float => "float",
4983 Self::Text => "text",
4984 Self::Bool => "bool",
4985 Self::Vector => "vector",
4986 Self::Interval => "interval",
4987 Self::Timestamptz => "timestamptz",
4988 Self::Json => "json",
4989 Self::Jsonb => "jsonb",
4990 Self::RegType => "regtype",
4991 Self::RegClass => "regclass",
4992 Self::Date => "date",
4993 Self::Timestamp => "timestamp",
4994 Self::TextArray => "TEXT[]",
4995 Self::IntArray => "INT[]",
4996 Self::BigIntArray => "BIGINT[]",
4997 Self::TsVector => "tsvector",
4998 Self::TsQuery => "tsquery",
4999 Self::Uuid => "uuid",
5000 Self::Bytea => "bytea",
5001 // v7.37.5 — `Self::Named` carries its own canonical name.
5002 Self::Named(name) => return f.write_str(name),
5003 })
5004 }
5005}
5006
5007#[derive(Debug, Clone, PartialEq)]
5008pub enum Literal {
5009 Integer(i64),
5010 Float(f64),
5011 /// Exact decimal literal — a bare `12.34`-style token, kept as
5012 /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
5013 /// before it becomes a `Value::Numeric`. PG parses such literals as
5014 /// `numeric`, not `double precision`. (Scientific/huge literals stay
5015 /// `Float`.)
5016 Numeric {
5017 unscaled: i128,
5018 /// v7.39 (round 271) — widened to u16. At u8 a literal with more
5019 /// than 255 decimal places could not be represented, and the
5020 /// conversion's `.expect("lexer-validated decimal")` aborted the
5021 /// query with an internal error on SQL PG accepts.
5022 scale: u16,
5023 },
5024 /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
5025 /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
5026 /// `Value::NumericBig` at eval; previously such literals fell back to double.
5027 NumericBig(String),
5028 String(String),
5029 /// v7.38.8 — a temporal constant that has already been decoded.
5030 ///
5031 /// Without these the only way to carry one through the AST was as
5032 /// text, and a predicate comparing a `timestamp` column against a
5033 /// literal then coerced that text back into a timestamp ONCE PER
5034 /// ROW — 32 ns of the 52 a comparison cost, measured on a customer
5035 /// profile. `constfold` produced text for the same reason: its exit
5036 /// had nothing else to hand back.
5037 ///
5038 /// `text` keeps the spelling so `Display` round-trips byte for byte,
5039 /// the way `Interval` already does and for the same reason: this
5040 /// node is printed in EXPLAIN, in dumps and in error messages, and
5041 /// none of those should change because the value stopped being
5042 /// carried as a string. The enum already holds a `String` and an
5043 /// `i128`, so neither variant widens it.
5044 Timestamp {
5045 micros: i64,
5046 text: String,
5047 },
5048 /// Days since the epoch `Value::Date` counts from. See
5049 /// [`Literal::Timestamp`].
5050 Date {
5051 days: i32,
5052 text: String,
5053 },
5054 Bool(bool),
5055 Null,
5056 /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
5057 Vector(Vec<f32>),
5058 /// TEXT[] value carried through the prepared-bind path
5059 /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
5060 /// text form, so the array rides the AST natively).
5061 TextArray(Vec<Option<String>>),
5062 /// INT[] value carried through the prepared-bind path.
5063 IntArray(Vec<Option<i32>>),
5064 /// BIGINT[] value carried through the prepared-bind path.
5065 BigIntArray(Vec<Option<i64>>),
5066 /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
5067 /// Three independent dimensions: `months` (variable-length;
5068 /// year/month), `days` (fixed 86400 seconds at non-DST, but
5069 /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
5070 /// stays distinguishable), and `micros` (sub-day; can carry).
5071 /// `text` keeps the original spelling so Display round-trips
5072 /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
5073 Interval {
5074 months: i32,
5075 days: i32,
5076 micros: i64,
5077 text: String,
5078 },
5079}
5080
5081#[derive(Debug, Clone, PartialEq, Eq)]
5082pub struct ColumnName {
5083 pub qualifier: Option<String>,
5084 pub name: String,
5085}
5086
5087#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5088pub enum BinOp {
5089 Or,
5090 And,
5091 Eq,
5092 NotEq,
5093 /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
5094 /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
5095 /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
5096 /// non-NULL behaviour matches `<>` / `=` exactly. Common in
5097 /// PG-style JOIN ON predicates and pg_dump output.
5098 IsDistinctFrom,
5099 IsNotDistinctFrom,
5100 /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
5101 /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
5102 /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
5103 /// is a real division (round 351).
5104 IntDiv,
5105 Lt,
5106 LtEq,
5107 Gt,
5108 GtEq,
5109 Add,
5110 Sub,
5111 Mul,
5112 Div,
5113 /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
5114 /// precedence as Mul/Div; result type follows left operand.
5115 Mod,
5116 /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
5117 /// operands of equal dimension; engine returns `Value::Float(d)`.
5118 L2Distance,
5119 /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
5120 GeomParallel,
5121 /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
5122 OverLeft,
5123 OverRight,
5124 /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
5125 GeomPerp,
5126 /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
5127 GeomSameAs,
5128 /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
5129 /// object to the left-hand one.
5130 ClosestPoint,
5131 /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
5132 GeomHoriz,
5133 /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
5134 /// more similar" remains true (matches pgvector's published convention).
5135 InnerProduct,
5136 /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
5137 CosineDistance,
5138 /// SQL string concatenation `||`. NULL propagates.
5139 Concat,
5140 /// Bitwise OR `|` on integers.
5141 BitOr,
5142 /// Bitwise AND `&` on integers.
5143 BitAnd,
5144 /// Bitwise XOR `#` on integers and equal-length bit strings.
5145 BitXor,
5146 /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
5147 /// sides as truth values and returns their exclusive-or (`1 XOR 0`
5148 /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
5149 /// MySQL dialect produces it; PG has no logical XOR. Its precedence
5150 /// sits between OR (loosest) and AND.
5151 LogicalXor,
5152 /// v4.14 `json -> key` — element access by string key (object)
5153 /// or integer index (array). Returns a JSON value.
5154 JsonGet,
5155 /// v4.14 `json ->> key` — same access, returns the result as
5156 /// TEXT (unwraps a top-level JSON string; renders other scalars
5157 /// as their canonical text).
5158 JsonGetText,
5159 /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
5160 /// text array literal like `'{a,0,b}'`. Returns JSON.
5161 JsonGetPath,
5162 /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
5163 JsonGetPathText,
5164 /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
5165 /// when every key/value in `sub_json` is structurally present in
5166 /// the left side. Matches PG semantics (top-level + recursive).
5167 JsonContains,
5168 /// `@?` — jsonb path existence (jsonb_path_exists).
5169 JsonPathExists,
5170 /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
5171 /// `a <@ b` is defined as `b @> a` (same semantics, swapped
5172 /// sides). Eval dispatch reuses `JsonContains` with swapped args.
5173 JsonContainedBy,
5174 /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
5175 /// returns BOOL. For an object, true if `key` is an existing
5176 /// member name; for an array, true if any element is the string
5177 /// `key` (PG semantics).
5178 JsonKeyExists,
5179 /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
5180 /// returns BOOL.
5181 JsonKeysAny,
5182 /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
5183 /// returns BOOL.
5184 JsonKeysAll,
5185 /// `jsonb #- path_text[]` — delete the value at a nested path.
5186 /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
5187 JsonDeletePath,
5188 /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
5189 /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
5190 /// tsvector` and engine eval normalises either ordering.
5191 TsMatch,
5192 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
5193 /// `<<`. LHS network is strictly inside RHS network (no equality).
5194 InetContainedBy,
5195 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
5196 /// `<<=`. LHS network ⊆ RHS network.
5197 InetContainedByEq,
5198 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
5199 /// LHS network strictly contains RHS network.
5200 InetContains,
5201 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
5202 /// LHS network ⊇ RHS network.
5203 InetContainsEq,
5204 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
5205 /// True iff either network contains any address of the other.
5206 InetOverlap,
5207 /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
5208 /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
5209 Intersects,
5210 /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
5211 /// (point, box).
5212 IsBelow,
5213 IsAbove,
5214 /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
5215 /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
5216 /// where `'A' < 'a'` is false under a non-C collation, which is the
5217 /// whole reason the operator family exists — it is what makes a LIKE
5218 /// prefix index-usable. pg_dump writes these into index definitions.
5219 PatternLt,
5220 PatternLtEq,
5221 PatternGt,
5222 PatternGtEq,
5223}
5224
5225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5226pub enum UnOp {
5227 Not,
5228 Neg,
5229 /// Bitwise NOT `~` on integers.
5230 BitNot,
5231 /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
5232 /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
5233 /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
5234 /// while PG18 and MariaDB accept every one of them.
5235 ///
5236 /// It is not a no-op to drop at parse time — PG refuses it on
5237 /// non-numeric operands ("operator does not exist: + boolean"), so the
5238 /// operand's type has to be seen at eval.
5239 Plus,
5240}
5241
5242// --- Display impls (round-trip-safe) --------------------------------------
5243
5244impl Statement {
5245 /// v7.18 — classify whether the statement is read-only at
5246 /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
5247 /// route SELECT-shaped traffic through the fan-out
5248 /// `AsyncReadHandle` (no writer-lock contention) while
5249 /// keeping DML / DDL / TX-control on the single-writer path.
5250 ///
5251 /// The classification matches what
5252 /// `Engine::execute_readonly_with_cancel` accepts: anything
5253 /// that does NOT mutate catalog, statistics, session state,
5254 /// or transaction state. WaitForWalPosition is included
5255 /// (engine returns `Unsupported`, but the classification is
5256 /// semantically read-only — no mutation). Empty is excluded
5257 /// out of an abundance of caution — the no-op routes
5258 /// through the writer so any future side effect lands
5259 /// uniformly.
5260 ///
5261 /// **Not connection-state aware**. `SET LOCAL` / `RESET`
5262 /// affect session parameters and must run on the writer
5263 /// engine that owns the session state; they classify as
5264 /// writer-path here. Same for `BEGIN` / `COMMIT` /
5265 /// `ROLLBACK` / `SAVEPOINT` — transaction control is
5266 /// always writer-path.
5267 /// v7.39 (round 435) — does this statement implicitly COMMIT an open
5268 /// transaction under MySQL?
5269 ///
5270 /// PG runs DDL inside the transaction; MySQL commits before (and after)
5271 /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
5272 /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
5273 /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
5274 /// nested START TRANSACTION; and measured NOT to fire for `CREATE
5275 /// TEMPORARY TABLE`, `SET`, or a SELECT.
5276 ///
5277 /// A positive list, not "everything that is not DML": a statement
5278 /// wrongly listed here commits a client's data early, which is as bad as
5279 /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
5280 /// COMPACT) are left out — a MySQL session never sends them.
5281 #[must_use]
5282 pub fn mysql_implicit_commit(&self) -> bool {
5283 match self {
5284 // MySQL's documented exception, measured on MariaDB 11: a
5285 // TEMPORARY table is not DDL for this purpose and does not
5286 // commit. (Round 435 got this for free because the parser then
5287 // lowered that spelling to `Statement::Empty`; round 436 made it
5288 // a real CREATE TABLE, and the round-435 pin caught it.)
5289 Self::CreateTable(c) => !c.temporary,
5290 // MySQL commits the open transaction and opens a fresh one.
5291 Self::Begin { .. }
5292 | Self::DropTable { .. }
5293 | Self::DropIndex { .. }
5294 | Self::CreateIndex(_)
5295 | Self::AlterIndex { .. }
5296 | Self::AlterTable(_)
5297 | Self::Truncate { .. }
5298 | Self::Analyze { .. }
5299 | Self::CreateStatistics { .. }
5300 | Self::DropStatistics { .. }
5301 | Self::CreateView { .. }
5302 | Self::DropView { .. }
5303 | Self::CreateMaterializedView { .. }
5304 | Self::RefreshMaterializedView { .. }
5305 | Self::DropMaterializedView { .. }
5306 | Self::CreateSequence(_)
5307 | Self::AlterSequence { .. }
5308 | Self::DropSequence { .. }
5309 | Self::CreateFunction(_)
5310 | Self::DropFunction { .. }
5311 | Self::CreateTrigger(_)
5312 | Self::DropTrigger { .. }
5313 | Self::CreateRule(_)
5314 | Self::DropRule { .. }
5315 | Self::CreateType(_)
5316 | Self::DropType { .. }
5317 | Self::AlterTypeAddValue { .. }
5318 | Self::AlterTypeRenameValue { .. }
5319 | Self::CreateDomain(_)
5320 | Self::AlterDomain { .. }
5321 | Self::DropDomain { .. }
5322 | Self::CreateSchema { .. }
5323 | Self::DropSchema { .. }
5324 | Self::CreateUser { .. }
5325 | Self::DropUser { .. }
5326 | Self::Grant { .. }
5327 | Self::Revoke { .. }
5328 | Self::CreatePolicy(_)
5329 | Self::AlterPolicy(_)
5330 | Self::DropPolicy { .. }
5331 | Self::CommentOn { .. }
5332 | Self::CreateExtension { .. } => true,
5333 _ => false,
5334 }
5335 }
5336
5337 #[must_use]
5338 pub fn is_readonly(&self) -> bool {
5339 match self {
5340 Statement::RenameTables(_) => false,
5341 // v7.39 (round 288) — SET CONSTRAINTS changes transaction
5342 // state, and IMMEDIATE can run the deferred checks there and
5343 // then; writer-path.
5344 Statement::SetConstraints { .. } => false,
5345 // v7.39 (round 695) — it writes nothing (SPG has no
5346 // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
5347 // writer and a read-only session refuses it there too.
5348 Statement::AlterSystem { .. } => false,
5349 // Same shape: a no-op here, a writer to PG, so a read-only
5350 // session refuses it as PG's would.
5351 Statement::NoOpPreventedInTransaction { .. } => false,
5352 Statement::DropDatabase { .. } => false,
5353 // v7.39 (round 696) — they perform nothing, so nothing is
5354 // written; PG classes LOCK and the OWNED BY pair as writers and
5355 // a read-only session refuses them there.
5356 Statement::ValidateOnly { .. } => false,
5357 // v7.39 (round 750) — a credential rotation persists.
5358 Statement::AlterRolePassword { .. } => true,
5359 Statement::DropAggregate { .. } => false,
5360 // v7.39 (round 547) — records a GUC default in the catalog.
5361 Statement::SetDbRoleSetting(_) => false,
5362 // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
5363 // but they name a relation and PG refuses one that is not
5364 // there, so they are not read-only in the sense this asks.
5365 Statement::Maintain { .. } => false,
5366 // v7.39 (round 277) — the prepared-statement surface is
5367 // session state, like SET; writer-path so it lands on the
5368 // engine that owns the session. EXECUTE may also run a
5369 // write, and its body is only known at execution time.
5370 Statement::Prepare { .. }
5371 | Statement::Execute { .. }
5372 | Statement::Deallocate(_)
5373 | Statement::Call(_)
5374 | Statement::PrepareTransaction(_)
5375 | Statement::CreateStatistics { .. }
5376 | Statement::DropStatistics { .. }
5377 // v7.39 (round 318, V51) — KILL signals another connection;
5378 // it must run on the writer path that owns the registry hook.
5379 | Statement::Kill { .. }
5380 // v7.39 (round 320, V53) — DISCARD throws session state away;
5381 // writer path, like SET / RESET.
5382 | Statement::Discard(_)
5383 // v7.39.2 — `USE <db>` writes session state, the same way
5384 // SET does, and takes the same path.
5385 | Statement::UseDatabase(_) => false,
5386 // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
5387 // locks MUTATES the lock table, so it is not a read. Left as
5388 // a read it went to the read-only executor and the locking
5389 // pre-pass never ran at all — the clause was honoured only
5390 // inside an explicit transaction, and silently ignored in
5391 // autocommit, which is where a queue worker runs it.
5392 Statement::Select(s) if s.locking.is_some() => false,
5393 Statement::Select(_)
5394 | Statement::CopyTo { .. }
5395 | Statement::CopyToFile { .. }
5396 | Statement::Explain(_)
5397 | Statement::ShowTables
5398 | Statement::ShowDatabases
5399 | Statement::ShowCreateTable(_)
5400 | Statement::ShowIndexes(_)
5401 | Statement::ShowStatus
5402 | Statement::ShowVariables
5403 | Statement::ShowVariablesLike(_)
5404 | Statement::ShowProcesslist
5405 | Statement::ShowColumns(_)
5406 | Statement::ShowUsers
5407 | Statement::ShowPublications
5408 | Statement::ShowSubscriptions
5409 | Statement::WaitForWalPosition { .. } => true,
5410 // Everything else mutates catalog, statistics,
5411 // session state, or transaction state — writer path.
5412 // Listed explicitly so a new Statement variant fails
5413 // the match exhaustiveness check and forces a
5414 // classification decision at add-site.
5415 Statement::Empty
5416 // v7.39 (round 169) — VACUUM mutates storage (reclaims
5417 // tombstoned versions): writer path.
5418 | Statement::Vacuum { .. }
5419 | Statement::DropTable { .. }
5420 | Statement::DropIndex { .. }
5421 | Statement::CreateTable(_)
5422 | Statement::CreateExtension(_)
5423 | Statement::DoBlock(_)
5424 | Statement::CreateIndex(_)
5425 | Statement::Insert(_)
5426 | Statement::Update(_)
5427 | Statement::Delete(_)
5428 | Statement::Merge(_)
5429 | Statement::Begin(_)
5430 | Statement::Commit
5431 | Statement::Rollback
5432 | Statement::Savepoint(_)
5433 | Statement::RollbackToSavepoint(_)
5434 | Statement::ReleaseSavepoint(_)
5435 | Statement::CreateUser(_)
5436 | Statement::DropUser { .. }
5437 | Statement::SetRole(_)
5438 | Statement::Grant(_)
5439 | Statement::Revoke(_)
5440 | Statement::CreatePolicy(_)
5441 | Statement::AlterPolicy(_)
5442 | Statement::DropPolicy(_)
5443 | Statement::AlterIndex(_)
5444 | Statement::AlterTable(_)
5445 | Statement::CreatePublication(_)
5446 | Statement::DropPublication { .. }
5447 | Statement::CreateSubscription(_)
5448 | Statement::DropSubscription { .. }
5449 | Statement::Analyze(_)
5450 | Statement::Truncate { .. }
5451 | Statement::CompactColdSegments
5452 | Statement::SetParameter { .. }
5453 | Statement::SetParameterList(_)
5454 | Statement::SetUserVars(..)
5455 | Statement::SetTransaction { .. }
5456 | Statement::ShowParameter(_)
5457 | Statement::ResetParameter(_)
5458 | Statement::CreateFunction(_)
5459 | Statement::CreateTrigger(_)
5460 | Statement::DropTrigger { .. }
5461 | Statement::CreateRule(_)
5462 | Statement::DropRule { .. }
5463 | Statement::DropFunction { .. }
5464 | Statement::CreateSequence(_)
5465 | Statement::AlterSequence(_)
5466 | Statement::DropSequence { .. }
5467 | Statement::CreateView(_)
5468 | Statement::DropView { .. }
5469 | Statement::CreateMaterializedView(_)
5470 | Statement::RefreshMaterializedView { .. }
5471 | Statement::DropMaterializedView { .. }
5472 | Statement::CreateType(_)
5473 | Statement::AlterTypeAddValue { .. }
5474 | Statement::AlterTypeRenameValue { .. }
5475 | Statement::CommentOn { .. }
5476 | Statement::DropType { .. }
5477 | Statement::CreateDomain(_)
5478 | Statement::DropDomain { .. }
5479 | Statement::CreateSchema { .. }
5480 | Statement::DropSchema { .. }
5481 // v7.39 (round 218) — cursors mutate per-session cursor state
5482 // (open/position/close) on the writer engine: writer path.
5483 | Statement::DeclareCursor { .. }
5484 | Statement::FetchCursor { .. }
5485 | Statement::MoveCursor { .. }
5486 | Statement::CloseCursor { .. }
5487 // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5488 // state / the notification queue: writer path.
5489 | Statement::Listen(_)
5490 | Statement::Notify { .. }
5491 | Statement::Unlisten(_)
5492 | Statement::CopyFromFile { .. }
5493 | Statement::AlterDomain { .. } => false,
5494 }
5495 }
5496}
5497
5498/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5499/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5500#[derive(Debug, Clone, PartialEq, Eq)]
5501pub struct GrantStatement {
5502 /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5503 /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5504 /// is why they keep the case the user typed.
5505 pub privileges: Vec<GrantPriv>,
5506 /// What the privileges are on.
5507 pub object: GrantObject,
5508 /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5509 pub grantees: Vec<String>,
5510 /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5511 /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5512 /// privilege itself).
5513 pub grant_option: bool,
5514}
5515
5516/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5517/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5518/// An empty column list means the privilege is table-wide.
5519#[derive(Debug, Clone, PartialEq, Eq)]
5520pub struct GrantPriv {
5521 pub word: String,
5522 pub columns: Vec<String>,
5523}
5524
5525/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5526/// privileges; every other object class parses and is accepted as a no-op, so
5527/// a pg_dump that grants on schemas / sequences / functions still restores.
5528#[derive(Debug, Clone, PartialEq, Eq)]
5529pub enum GrantObject {
5530 /// `ON [TABLE] a, b` — the enforced case.
5531 Tables(Vec<String>),
5532 /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5533 /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5534 /// granted roles; the grantees are the members.
5535 Roles(Vec<String>),
5536 /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5537 /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5538 Sequences(Vec<String>),
5539 /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5540 Schemas(Vec<String>),
5541 /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5542 Databases(Vec<String>),
5543 /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5544 /// (SPG keys functions by name); the argument list parses and is dropped.
5545 Functions(Vec<(String, Option<Vec<String>>)>),
5546 /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5547 /// every table at GRANT time, exactly like PG.
5548 AllTablesInSchema,
5549 /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5550 /// message.
5551 Other(String),
5552}
5553
5554impl GrantStatement {
5555 /// Round-trip text. `grant = false` renders the REVOKE form.
5556 fn render(&self, grant: bool) -> alloc::string::String {
5557 use core::fmt::Write as _;
5558 let mut s = alloc::string::String::new();
5559 let privs = if self.privileges.is_empty() {
5560 alloc::string::String::from("ALL")
5561 } else {
5562 let parts: Vec<_> = self
5563 .privileges
5564 .iter()
5565 .map(|p| {
5566 if p.columns.is_empty() {
5567 p.word.clone()
5568 } else {
5569 let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5570 alloc::format!("{} ({})", p.word, cols.join(", "))
5571 }
5572 })
5573 .collect();
5574 parts.join(", ")
5575 };
5576 let obj = match &self.object {
5577 GrantObject::Tables(t) => {
5578 let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5579 alloc::format!("TABLE {}", names.join(", "))
5580 }
5581 GrantObject::Roles(r) => {
5582 let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5583 names.join(", ")
5584 }
5585 GrantObject::Sequences(n) => {
5586 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5587 alloc::format!("SEQUENCE {}", names.join(", "))
5588 }
5589 GrantObject::Schemas(n) => {
5590 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5591 alloc::format!("SCHEMA {}", names.join(", "))
5592 }
5593 GrantObject::Databases(n) => {
5594 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5595 alloc::format!("DATABASE {}", names.join(", "))
5596 }
5597 GrantObject::Functions(n) => {
5598 let names: Vec<_> = n
5599 .iter()
5600 .map(|(name, args)| match args {
5601 Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5602 None => quote_ident(name),
5603 })
5604 .collect();
5605 alloc::format!("FUNCTION {}", names.join(", "))
5606 }
5607 GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5608 GrantObject::Other(k) => k.clone(),
5609 };
5610 let who: Vec<_> = self
5611 .grantees
5612 .iter()
5613 .map(|g| {
5614 if g.is_empty() {
5615 "PUBLIC".into()
5616 } else {
5617 quote_ident(g)
5618 }
5619 })
5620 .collect();
5621 if let GrantObject::Roles(_) = &self.object {
5622 let _ = if grant {
5623 write!(s, "GRANT {obj} TO {}", who.join(", "))
5624 } else {
5625 write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5626 };
5627 return s;
5628 }
5629 if grant {
5630 let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5631 if self.grant_option {
5632 s.push_str(" WITH GRANT OPTION");
5633 }
5634 } else {
5635 s.push_str("REVOKE ");
5636 if self.grant_option {
5637 s.push_str("GRANT OPTION FOR ");
5638 }
5639 let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5640 }
5641 s
5642 }
5643}
5644
5645impl fmt::Display for Statement {
5646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5647 match self {
5648 Self::Empty => Ok(()),
5649 // v7.39 (round 695) — deparsed the way PG writes it.
5650 // v7.39 (round 696) — never deparsed into a dump (nothing is
5651 // stored), so the shortest faithful spelling of what it was.
5652 Self::DropAggregate { if_exists, items } => {
5653 f.write_str("DROP AGGREGATE ")?;
5654 if *if_exists {
5655 f.write_str("IF EXISTS ")?;
5656 }
5657 for (i, (name, args)) in items.iter().enumerate() {
5658 if i > 0 {
5659 f.write_str(", ")?;
5660 }
5661 match args {
5662 Some(a) => write!(f, "{name}({})", a.join(", "))?,
5663 None => write!(f, "{name}(*)")?,
5664 }
5665 }
5666 Ok(())
5667 }
5668 Self::AlterRolePassword { name, password } => {
5669 write!(f, "ALTER ROLE {}", quote_ident(name))?;
5670 match password {
5671 Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5672 None => f.write_str(" PASSWORD NULL"),
5673 }
5674 }
5675 Self::ValidateOnly { kind, names } => match kind {
5676 ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5677 ValidateOnlyKind::RoleName => {
5678 write!(f, "DROP OWNED BY {}", names.join(", "))
5679 }
5680 ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5681 ValidateOnlyKind::ExtensionAvailable => {
5682 write!(f, "CREATE EXTENSION {}", names.join(", "))
5683 }
5684 ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5685 ValidateOnlyKind::CollationName => {
5686 write!(f, "DROP COLLATION {}", names.join(", "))
5687 }
5688 ValidateOnlyKind::TsConfigName => {
5689 write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5690 }
5691 ValidateOnlyKind::EventTriggerName => {
5692 write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5693 }
5694 ValidateOnlyKind::TablespaceName => {
5695 write!(f, "DROP TABLESPACE {}", names.join(", "))
5696 }
5697 ValidateOnlyKind::LargeObjectOid => {
5698 write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5699 }
5700 ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5701 ValidateOnlyKind::AggregateName => {
5702 write!(f, "ALTER AGGREGATE {}", names.join(", "))
5703 }
5704 ValidateOnlyKind::ConversionName => {
5705 write!(f, "DROP CONVERSION {}", names.join(", "))
5706 }
5707 ValidateOnlyKind::LanguageName => {
5708 write!(f, "DROP LANGUAGE {}", names.join(", "))
5709 }
5710 ValidateOnlyKind::ExtensionInstalled => {
5711 write!(f, "DROP EXTENSION {}", names.join(", "))
5712 }
5713 },
5714 Self::AlterSystem { parameter } => match parameter {
5715 Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5716 None => f.write_str("ALTER SYSTEM RESET ALL"),
5717 },
5718 // v7.39 (round 547) — round-trips as PG writes it.
5719 Self::SetDbRoleSetting(st) => {
5720 match (&st.database, &st.role) {
5721 (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5722 (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5723 (None, None) => f.write_str("ALTER ROLE ALL")?,
5724 }
5725 if let (Some(d), Some(_)) = (&st.database, &st.role) {
5726 write!(f, " IN DATABASE {d}")?;
5727 }
5728 match (&st.param, &st.value) {
5729 (None, _) => f.write_str(" RESET ALL"),
5730 (Some(p), None) => write!(f, " RESET {p}"),
5731 (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5732 }
5733 }
5734 Self::Maintain {
5735 kind,
5736 concurrently,
5737 target,
5738 } => {
5739 f.write_str(match kind {
5740 crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5741 _ => "REINDEX ",
5742 })?;
5743 if *concurrently {
5744 f.write_str("CONCURRENTLY ")?;
5745 }
5746 if let Some(t) = target {
5747 f.write_str(t)?;
5748 }
5749 Ok(())
5750 }
5751 Self::DropDatabase { name, if_exists } => {
5752 f.write_str("DROP DATABASE ")?;
5753 if *if_exists {
5754 f.write_str("IF EXISTS ")?;
5755 }
5756 f.write_str(name)
5757 }
5758 Self::NoOpPreventedInTransaction { what, .. } => f.write_str(what),
5759 Self::SetConstraints { names, deferred } => {
5760 f.write_str("SET CONSTRAINTS ")?;
5761 if names.is_empty() {
5762 f.write_str("ALL")?;
5763 } else {
5764 for (i, n) in names.iter().enumerate() {
5765 if i > 0 {
5766 f.write_str(", ")?;
5767 }
5768 f.write_str(n)?;
5769 }
5770 }
5771 f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5772 }
5773 // v7.39 (round 277) — the source text is kept verbatim so
5774 // `pg_prepared_statements.statement` can report it the way
5775 // PG does (the whole PREPARE statement, not just the body).
5776 Self::Prepare { source, .. } => f.write_str(source),
5777 Self::Execute { name, args } => {
5778 write!(f, "EXECUTE {}", quote_ident(name))?;
5779 if !args.is_empty() {
5780 f.write_str("(")?;
5781 for (i, a) in args.iter().enumerate() {
5782 if i > 0 {
5783 f.write_str(", ")?;
5784 }
5785 write!(f, "{a}")?;
5786 }
5787 f.write_str(")")?;
5788 }
5789 Ok(())
5790 }
5791 Self::CreateStatistics {
5792 name,
5793 if_not_exists,
5794 kinds,
5795 columns,
5796 table,
5797 } => {
5798 f.write_str("CREATE STATISTICS ")?;
5799 if *if_not_exists {
5800 f.write_str("IF NOT EXISTS ")?;
5801 }
5802 write!(f, "{}", quote_ident(name))?;
5803 if !kinds.is_empty() {
5804 write!(f, " ({})", kinds.join(", "))?;
5805 }
5806 write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5807 }
5808 Self::DropStatistics { name, if_exists } => {
5809 f.write_str("DROP STATISTICS ")?;
5810 if *if_exists {
5811 f.write_str("IF EXISTS ")?;
5812 }
5813 write!(f, "{}", quote_ident(name))
5814 }
5815 Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5816 Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5817 Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5818 Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5819 Self::DeclareCursor {
5820 name,
5821 scroll,
5822 hold,
5823 query,
5824 } => {
5825 write!(f, "DECLARE {} ", quote_ident(name))?;
5826 match scroll {
5827 Some(true) => f.write_str("SCROLL ")?,
5828 Some(false) => f.write_str("NO SCROLL ")?,
5829 None => {}
5830 }
5831 f.write_str("CURSOR ")?;
5832 if *hold {
5833 f.write_str("WITH HOLD ")?;
5834 }
5835 write!(f, "FOR {query}")
5836 }
5837 Self::FetchCursor { name, direction } => {
5838 write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5839 }
5840 Self::MoveCursor { name, direction } => {
5841 write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5842 }
5843 Self::CloseCursor { name } => match name {
5844 Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5845 None => f.write_str("CLOSE ALL"),
5846 },
5847 Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5848 Self::Notify { channel, payload } => {
5849 write!(f, "NOTIFY {}", quote_ident(channel))?;
5850 if let Some(p) = payload {
5851 write!(f, ", '{}'", p.replace('\'', "''"))?;
5852 }
5853 Ok(())
5854 }
5855 Self::Unlisten(ch) => match ch {
5856 Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5857 None => f.write_str("UNLISTEN *"),
5858 },
5859 Self::CopyTo {
5860 table,
5861 columns,
5862 query,
5863 options,
5864 } => {
5865 if let Some(q) = query {
5866 write!(f, "COPY ({q})")?;
5867 } else {
5868 write!(f, "COPY {table}")?;
5869 if let Some(cols) = columns {
5870 write!(f, " ({})", cols.join(", "))?;
5871 }
5872 }
5873 write!(f, " TO STDOUT")?;
5874 let mut parts: Vec<String> = Vec::new();
5875 if options.format == CopyFormat::Csv {
5876 parts.push("FORMAT csv".to_string());
5877 }
5878 if options.header {
5879 parts.push("HEADER true".to_string());
5880 }
5881 if let Some(d) = options.delimiter {
5882 parts.push(alloc::format!("DELIMITER '{d}'"));
5883 }
5884 if let Some(n) = &options.null_str {
5885 parts.push(alloc::format!("NULL '{n}'"));
5886 }
5887 if let Some(q) = options.quote {
5888 parts.push(alloc::format!("QUOTE '{q}'"));
5889 }
5890 if !parts.is_empty() {
5891 write!(f, " WITH ({})", parts.join(", "))?;
5892 }
5893 Ok(())
5894 }
5895 Self::CopyFromFile {
5896 table,
5897 columns,
5898 path,
5899 options,
5900 } => {
5901 write!(f, "COPY {table}")?;
5902 if let Some(cols) = columns {
5903 write!(f, " ({})", cols.join(", "))?;
5904 }
5905 write!(f, " FROM '{path}'")?;
5906 let mut parts: Vec<String> = Vec::new();
5907 if options.format == CopyFormat::Csv {
5908 parts.push("FORMAT csv".to_string());
5909 }
5910 if options.header {
5911 parts.push("HEADER true".to_string());
5912 }
5913 if let Some(d) = options.delimiter {
5914 parts.push(alloc::format!("DELIMITER '{d}'"));
5915 }
5916 if let Some(n) = &options.null_str {
5917 parts.push(alloc::format!("NULL '{n}'"));
5918 }
5919 if let Some(q) = options.quote {
5920 parts.push(alloc::format!("QUOTE '{q}'"));
5921 }
5922 if !parts.is_empty() {
5923 write!(f, " WITH ({})", parts.join(", "))?;
5924 }
5925 Ok(())
5926 }
5927 Self::CopyToFile {
5928 table,
5929 columns,
5930 query,
5931 path,
5932 options,
5933 } => {
5934 if let Some(q) = query {
5935 write!(f, "COPY ({q})")?;
5936 } else {
5937 write!(f, "COPY {table}")?;
5938 if let Some(cols) = columns {
5939 write!(f, " ({})", cols.join(", "))?;
5940 }
5941 }
5942 write!(f, " TO '{path}'")?;
5943 let mut parts: Vec<String> = Vec::new();
5944 if options.format == CopyFormat::Csv {
5945 parts.push("FORMAT csv".to_string());
5946 }
5947 if options.header {
5948 parts.push("HEADER true".to_string());
5949 }
5950 if let Some(d) = options.delimiter {
5951 parts.push(alloc::format!("DELIMITER '{d}'"));
5952 }
5953 if let Some(n) = &options.null_str {
5954 parts.push(alloc::format!("NULL '{n}'"));
5955 }
5956 if let Some(q) = options.quote {
5957 parts.push(alloc::format!("QUOTE '{q}'"));
5958 }
5959 if !parts.is_empty() {
5960 write!(f, " WITH ({})", parts.join(", "))?;
5961 }
5962 Ok(())
5963 }
5964 Self::AlterDomain { name, action } => {
5965 write!(f, "ALTER DOMAIN {name} ")?;
5966 match action {
5967 AlterDomainAction::AddConstraint { name: cn, check } => match cn {
5968 Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
5969 None => write!(f, "ADD CHECK ({check})"),
5970 },
5971 AlterDomainAction::DropConstraint {
5972 name: cn,
5973 if_exists,
5974 } => {
5975 if *if_exists {
5976 write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
5977 } else {
5978 write!(f, "DROP CONSTRAINT {cn}")
5979 }
5980 }
5981 AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
5982 AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
5983 AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
5984 AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
5985 AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
5986 }
5987 }
5988 Self::Truncate {
5989 tables,
5990 restart_identity,
5991 cascade,
5992 only,
5993 } => {
5994 f.write_str("TRUNCATE TABLE ")?;
5995 if *only {
5996 f.write_str("ONLY ")?;
5997 }
5998 for (i, t) in tables.iter().enumerate() {
5999 if i > 0 {
6000 f.write_str(", ")?;
6001 }
6002 f.write_str(t)?;
6003 }
6004 if *restart_identity {
6005 f.write_str(" RESTART IDENTITY")?;
6006 }
6007 if *cascade {
6008 f.write_str(" CASCADE")?;
6009 }
6010 Ok(())
6011 }
6012 Self::DropTable { names, if_exists } => {
6013 f.write_str("DROP TABLE ")?;
6014 if *if_exists {
6015 f.write_str("IF EXISTS ")?;
6016 }
6017 for (i, n) in names.iter().enumerate() {
6018 if i > 0 {
6019 f.write_str(", ")?;
6020 }
6021 write!(f, "{}", quote_ident(n))?;
6022 }
6023 Ok(())
6024 }
6025 Self::DropIndex {
6026 name,
6027 if_exists,
6028 table,
6029 } => {
6030 f.write_str("DROP INDEX ")?;
6031 if *if_exists {
6032 f.write_str("IF EXISTS ")?;
6033 }
6034 write!(f, "{}", quote_ident(name))?;
6035 if let Some(t) = table {
6036 write!(f, " ON {}", quote_ident(t))?;
6037 }
6038 Ok(())
6039 }
6040 Self::Select(s) => s.fmt(f),
6041 Self::CreateTable(s) => s.fmt(f),
6042 Self::CreateIndex(s) => s.fmt(f),
6043 Self::Insert(s) => s.fmt(f),
6044 Self::Update(s) => s.fmt(f),
6045 Self::Delete(s) => s.fmt(f),
6046 Self::Merge(s) => s.fmt(f),
6047 Self::Vacuum { table, analyze } => {
6048 f.write_str("VACUUM")?;
6049 if *analyze {
6050 f.write_str(" ANALYZE")?;
6051 }
6052 if let Some(t) = table {
6053 write!(f, " {}", quote_ident(t))?;
6054 }
6055 Ok(())
6056 }
6057 Self::Begin(modes) => {
6058 f.write_str("BEGIN")?;
6059 if let Some(level) = modes.isolation {
6060 write!(f, " ISOLATION LEVEL {level}")?;
6061 }
6062 match modes.read_only {
6063 Some(true) => f.write_str(" READ ONLY")?,
6064 Some(false) => f.write_str(" READ WRITE")?,
6065 None => {}
6066 }
6067 Ok(())
6068 }
6069 Self::Commit => f.write_str("COMMIT"),
6070 Self::Rollback => f.write_str("ROLLBACK"),
6071 Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
6072 Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
6073 Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
6074 Self::ShowTables => f.write_str("SHOW TABLES"),
6075 Self::ShowDatabases => f.write_str("SHOW DATABASES"),
6076 Self::UseDatabase(n) => write!(f, "USE {}", quote_ident(n)),
6077 Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
6078 Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
6079 Self::ShowStatus => f.write_str("SHOW STATUS"),
6080 Self::ShowVariables => f.write_str("SHOW VARIABLES"),
6081 Self::ShowVariablesLike(p) => {
6082 write!(f, "SHOW VARIABLES LIKE '{}'", p.replace('\'', "''"))
6083 }
6084 Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
6085 Self::Discard(t) => write!(f, "DISCARD {t}"),
6086 Self::Kill { query_only, id } => {
6087 if *query_only {
6088 write!(f, "KILL QUERY {id}")
6089 } else {
6090 write!(f, "KILL CONNECTION {id}")
6091 }
6092 }
6093 Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
6094 Self::CreateUser(s) => write!(
6095 f,
6096 "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
6097 quote_ident(&s.name),
6098 s.role
6099 ),
6100 Self::DropUser { name, if_exists } => {
6101 let ie = if *if_exists { "IF EXISTS " } else { "" };
6102 write!(f, "DROP USER {ie}{}", quote_ident(name))
6103 }
6104 Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
6105 Self::SetRole(None) => f.write_str("RESET ROLE"),
6106 Self::Grant(g) => write!(f, "{}", g.render(true)),
6107 Self::Revoke(g) => write!(f, "{}", g.render(false)),
6108 Self::CreatePolicy(s) => {
6109 write!(
6110 f,
6111 "CREATE POLICY {} ON {}",
6112 quote_ident(&s.name),
6113 quote_ident(&s.table)
6114 )?;
6115 if !s.permissive {
6116 f.write_str(" AS RESTRICTIVE")?;
6117 }
6118 if !matches!(s.cmd, PolicyCmd::All) {
6119 let w = match s.cmd {
6120 PolicyCmd::Select => "SELECT",
6121 PolicyCmd::Insert => "INSERT",
6122 PolicyCmd::Update => "UPDATE",
6123 PolicyCmd::Delete => "DELETE",
6124 PolicyCmd::All => unreachable!(),
6125 };
6126 write!(f, " FOR {w}")?;
6127 }
6128 if !s.roles.is_empty() {
6129 write!(f, " TO {}", s.roles.join(", "))?;
6130 }
6131 if let Some(u) = &s.using {
6132 write!(f, " USING ({u})")?;
6133 }
6134 if let Some(c) = &s.with_check {
6135 write!(f, " WITH CHECK ({c})")?;
6136 }
6137 Ok(())
6138 }
6139 Self::AlterPolicy(s) => {
6140 write!(
6141 f,
6142 "ALTER POLICY {} ON {}",
6143 quote_ident(&s.name),
6144 quote_ident(&s.table)
6145 )?;
6146 if let Some(nn) = &s.rename_to {
6147 return write!(f, " RENAME TO {}", quote_ident(nn));
6148 }
6149 if let Some(roles) = &s.roles {
6150 write!(f, " TO {}", roles.join(", "))?;
6151 }
6152 if let Some(u) = &s.using {
6153 write!(f, " USING ({u})")?;
6154 }
6155 if let Some(c) = &s.with_check {
6156 write!(f, " WITH CHECK ({c})")?;
6157 }
6158 Ok(())
6159 }
6160 Self::DropPolicy(s) => {
6161 f.write_str("DROP POLICY ")?;
6162 if s.if_exists {
6163 f.write_str("IF EXISTS ")?;
6164 }
6165 write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
6166 }
6167 Self::ShowUsers => f.write_str("SHOW USERS"),
6168 Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
6169 Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
6170 Self::CreateSubscription(s) => {
6171 write!(
6172 f,
6173 "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
6174 quote_ident(&s.name),
6175 s.conn_str.replace('\'', "''")
6176 )?;
6177 for (i, p) in s.publications.iter().enumerate() {
6178 if i > 0 {
6179 f.write_str(", ")?;
6180 }
6181 write!(f, "{}", quote_ident(p))?;
6182 }
6183 Ok(())
6184 }
6185 Self::DropSubscription { name, if_exists } => {
6186 let opt = if *if_exists { "IF EXISTS " } else { "" };
6187 write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
6188 }
6189 Self::WaitForWalPosition { pos, timeout_ms } => {
6190 write!(f, "WAIT FOR WAL POSITION {pos}")?;
6191 if let Some(ms) = timeout_ms {
6192 write!(f, " WITH TIMEOUT {ms}")?;
6193 }
6194 Ok(())
6195 }
6196 Self::RenameTables(pairs) => {
6197 f.write_str("RENAME TABLE ")?;
6198 for (i, (from, to)) in pairs.iter().enumerate() {
6199 if i > 0 {
6200 f.write_str(", ")?;
6201 }
6202 write!(f, "{} TO {}", quote_ident(from), quote_ident(to))?;
6203 }
6204 Ok(())
6205 }
6206 Self::Analyze(None) => f.write_str("ANALYZE"),
6207 Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
6208 Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
6209 Self::Explain(e) => {
6210 if e.suggest {
6211 write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
6212 } else if e.analyze {
6213 write!(f, "EXPLAIN ANALYZE {}", e.inner)
6214 } else {
6215 write!(f, "EXPLAIN {}", e.inner)
6216 }
6217 }
6218 Self::AlterIndex(a) => {
6219 write!(f, "ALTER INDEX ")?;
6220 match &a.target {
6221 // Parameters are consumed, not stored; the shortest
6222 // faithful spelling.
6223 AlterIndexTarget::StorageParams => {
6224 write!(f, "{} SET ()", quote_ident(&a.name))
6225 }
6226 AlterIndexTarget::Rebuild { encoding } => {
6227 write!(f, "{} REBUILD", quote_ident(&a.name))?;
6228 if let Some(enc) = encoding {
6229 write!(f, " WITH (encoding = {enc})")?;
6230 }
6231 Ok(())
6232 }
6233 AlterIndexTarget::Rename { new, if_exists } => {
6234 if *if_exists {
6235 f.write_str("IF EXISTS ")?;
6236 }
6237 write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
6238 }
6239 }
6240 }
6241 Self::AlterTable(a) => {
6242 write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
6243 for (i, t) in a.targets.iter().enumerate() {
6244 if i > 0 {
6245 f.write_str(", ")?;
6246 }
6247 fmt_alter_target(f, t)?;
6248 }
6249 Ok(())
6250 }
6251 Self::CreatePublication(p) => {
6252 write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
6253 match &p.scope {
6254 PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
6255 PublicationScope::ForTables(ts) => {
6256 f.write_str(" FOR TABLE ")?;
6257 for (i, t) in ts.iter().enumerate() {
6258 if i > 0 {
6259 f.write_str(", ")?;
6260 }
6261 write!(f, "{}", quote_ident(t))?;
6262 }
6263 Ok(())
6264 }
6265 PublicationScope::TablesInSchema(schema) => {
6266 write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
6267 Ok(())
6268 }
6269 PublicationScope::AllTablesExcept(ts) => {
6270 f.write_str(" FOR ALL TABLES EXCEPT ")?;
6271 for (i, t) in ts.iter().enumerate() {
6272 if i > 0 {
6273 f.write_str(", ")?;
6274 }
6275 write!(f, "{}", quote_ident(t))?;
6276 }
6277 Ok(())
6278 }
6279 }
6280 }
6281 Self::CreateExtension(name) => {
6282 write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
6283 }
6284 Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
6285 Self::DropPublication { name, if_exists } => {
6286 let opt = if *if_exists { "IF EXISTS " } else { "" };
6287 write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
6288 }
6289 Self::SetParameter { name, value, local } => {
6290 write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
6291 match value {
6292 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
6293 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
6294 SetValue::Default => f.write_str("DEFAULT"),
6295 }
6296 }
6297 Self::SetTransaction { modes } => {
6298 f.write_str("SET TRANSACTION")?;
6299 if let Some(isolation) = modes.isolation {
6300 let name = match isolation {
6301 IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
6302 IsolationLevel::ReadCommitted => "READ COMMITTED",
6303 IsolationLevel::RepeatableRead => "REPEATABLE READ",
6304 IsolationLevel::Serializable => "SERIALIZABLE",
6305 };
6306 write!(f, " ISOLATION LEVEL {name}")?;
6307 }
6308 match modes.read_only {
6309 Some(true) => f.write_str(" READ ONLY")?,
6310 Some(false) => f.write_str(" READ WRITE")?,
6311 None => {}
6312 }
6313 Ok(())
6314 }
6315 Self::ShowParameter(name) => write!(f, "SHOW {name}"),
6316 Self::SetUserVars(assigns, _) => {
6317 f.write_str("SET ")?;
6318 for (i, (name, value)) in assigns.iter().enumerate() {
6319 if i > 0 {
6320 f.write_str(", ")?;
6321 }
6322 write!(f, "@{name} = {value}")?;
6323 }
6324 Ok(())
6325 }
6326 Self::SetParameterList(pairs) => {
6327 f.write_str("SET ")?;
6328 for (i, (name, value)) in pairs.iter().enumerate() {
6329 if i > 0 {
6330 f.write_str(", ")?;
6331 }
6332 write!(f, "{name} = ")?;
6333 match value {
6334 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
6335 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
6336 SetValue::Default => f.write_str("DEFAULT")?,
6337 }
6338 }
6339 Ok(())
6340 }
6341 Self::ResetParameter(None) => f.write_str("RESET ALL"),
6342 Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
6343 Self::CreateFunction(s) => s.fmt(f),
6344 Self::CreateTrigger(s) => s.fmt(f),
6345 Self::DropTrigger {
6346 name,
6347 table,
6348 if_exists,
6349 } => {
6350 f.write_str("DROP TRIGGER ")?;
6351 if *if_exists {
6352 f.write_str("IF EXISTS ")?;
6353 }
6354 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6355 }
6356 Self::DropFunction {
6357 name,
6358 args,
6359 if_exists,
6360 } => {
6361 f.write_str("DROP FUNCTION ")?;
6362 if *if_exists {
6363 f.write_str("IF EXISTS ")?;
6364 }
6365 write!(f, "{}", quote_ident(name))?;
6366 if let Some(a) = args {
6367 write!(f, "({})", a.join(", "))?;
6368 }
6369 Ok(())
6370 }
6371 Self::CreateSequence(s) => s.fmt(f),
6372 Self::AlterSequence(s) => s.fmt(f),
6373 Self::DropSequence { names, if_exists } => {
6374 f.write_str("DROP SEQUENCE ")?;
6375 if *if_exists {
6376 f.write_str("IF EXISTS ")?;
6377 }
6378 for (i, n) in names.iter().enumerate() {
6379 if i > 0 {
6380 f.write_str(", ")?;
6381 }
6382 write!(f, "{}", quote_ident(n))?;
6383 }
6384 Ok(())
6385 }
6386 Self::CreateView(v) => v.fmt(f),
6387 Self::DropView { names, if_exists } => {
6388 f.write_str("DROP VIEW ")?;
6389 if *if_exists {
6390 f.write_str("IF EXISTS ")?;
6391 }
6392 for (i, n) in names.iter().enumerate() {
6393 if i > 0 {
6394 f.write_str(", ")?;
6395 }
6396 write!(f, "{}", quote_ident(n))?;
6397 }
6398 Ok(())
6399 }
6400 Self::CreateMaterializedView(v) => v.fmt(f),
6401 Self::RefreshMaterializedView { name, with_data } => {
6402 write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
6403 if !*with_data {
6404 f.write_str(" WITH NO DATA")?;
6405 }
6406 Ok(())
6407 }
6408 Self::DropMaterializedView { names, if_exists } => {
6409 f.write_str("DROP MATERIALIZED VIEW ")?;
6410 if *if_exists {
6411 f.write_str("IF EXISTS ")?;
6412 }
6413 for (i, n) in names.iter().enumerate() {
6414 if i > 0 {
6415 f.write_str(", ")?;
6416 }
6417 write!(f, "{}", quote_ident(n))?;
6418 }
6419 Ok(())
6420 }
6421 Self::CreateType(t) => t.fmt(f),
6422 Self::CommentOn {
6423 kind,
6424 name,
6425 comment,
6426 } => {
6427 let body = match comment {
6428 Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
6429 None => "NULL".into(),
6430 };
6431 write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
6432 }
6433 Self::AlterTypeRenameValue {
6434 type_name,
6435 old,
6436 new,
6437 } => write!(
6438 f,
6439 "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
6440 quote_ident(type_name),
6441 old.replace('\'', "''"),
6442 new.replace('\'', "''")
6443 ),
6444 Self::AlterTypeAddValue {
6445 type_name,
6446 label,
6447 if_not_exists,
6448 position,
6449 } => {
6450 write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6451 if *if_not_exists {
6452 write!(f, "IF NOT EXISTS ")?;
6453 }
6454 write!(f, "'{label}'")?;
6455 if let Some((is_before, anchor)) = position {
6456 write!(
6457 f,
6458 " {} '{anchor}'",
6459 if *is_before { "BEFORE" } else { "AFTER" }
6460 )?;
6461 }
6462 Ok(())
6463 }
6464 Self::DropType { names, if_exists } => {
6465 f.write_str("DROP TYPE ")?;
6466 if *if_exists {
6467 f.write_str("IF EXISTS ")?;
6468 }
6469 for (i, n) in names.iter().enumerate() {
6470 if i > 0 {
6471 f.write_str(", ")?;
6472 }
6473 write!(f, "{}", quote_ident(n))?;
6474 }
6475 Ok(())
6476 }
6477 Self::CreateDomain(d) => d.fmt(f),
6478 Self::DropDomain { names, if_exists } => {
6479 f.write_str("DROP DOMAIN ")?;
6480 if *if_exists {
6481 f.write_str("IF EXISTS ")?;
6482 }
6483 for (i, n) in names.iter().enumerate() {
6484 if i > 0 {
6485 f.write_str(", ")?;
6486 }
6487 write!(f, "{}", quote_ident(n))?;
6488 }
6489 Ok(())
6490 }
6491 Self::CreateSchema {
6492 name,
6493 if_not_exists,
6494 } => {
6495 f.write_str("CREATE SCHEMA ")?;
6496 if *if_not_exists {
6497 f.write_str("IF NOT EXISTS ")?;
6498 }
6499 write!(f, "{}", quote_ident(name))
6500 }
6501 Self::DropSchema { names, if_exists } => {
6502 f.write_str("DROP SCHEMA ")?;
6503 if *if_exists {
6504 f.write_str("IF EXISTS ")?;
6505 }
6506 for (i, n) in names.iter().enumerate() {
6507 if i > 0 {
6508 f.write_str(", ")?;
6509 }
6510 write!(f, "{}", quote_ident(n))?;
6511 }
6512 Ok(())
6513 }
6514 Self::CreateRule(r) => {
6515 f.write_str("CREATE ")?;
6516 if r.or_replace {
6517 f.write_str("OR REPLACE ")?;
6518 }
6519 write!(
6520 f,
6521 "RULE {} AS ON {} TO {}",
6522 quote_ident(&r.name),
6523 r.event,
6524 quote_ident(&r.table)
6525 )?;
6526 if let Some(w) = &r.when_condition {
6527 write!(f, " WHERE {w}")?;
6528 }
6529 f.write_str(if r.instead {
6530 " DO INSTEAD "
6531 } else {
6532 " DO ALSO "
6533 })?;
6534 if r.commands.is_empty() {
6535 f.write_str("NOTHING")?;
6536 } else if r.commands.len() == 1 {
6537 write!(f, "{}", r.commands[0])?;
6538 } else {
6539 f.write_str("(")?;
6540 for (i, c) in r.commands.iter().enumerate() {
6541 if i > 0 {
6542 f.write_str("; ")?;
6543 }
6544 write!(f, "{c}")?;
6545 }
6546 f.write_str(")")?;
6547 }
6548 Ok(())
6549 }
6550 Self::DropRule {
6551 name,
6552 table,
6553 if_exists,
6554 } => {
6555 f.write_str("DROP RULE ")?;
6556 if *if_exists {
6557 f.write_str("IF EXISTS ")?;
6558 }
6559 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6560 }
6561 }
6562 }
6563}
6564
6565impl fmt::Display for CreateDomainStatement {
6566 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6567 write!(
6568 f,
6569 "CREATE DOMAIN {} AS {}",
6570 quote_ident(&self.name),
6571 self.base_type
6572 )?;
6573 if let Some(d) = &self.default {
6574 write!(f, " DEFAULT {d}")?;
6575 }
6576 if self.not_null {
6577 f.write_str(" NOT NULL")?;
6578 }
6579 for c in &self.checks {
6580 write!(f, " CHECK ({c})")?;
6581 }
6582 Ok(())
6583 }
6584}
6585
6586impl fmt::Display for CreateTypeStatement {
6587 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6588 write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6589 match &self.kind {
6590 TypeKind::Enum { labels } => {
6591 f.write_str("ENUM (")?;
6592 for (i, l) in labels.iter().enumerate() {
6593 if i > 0 {
6594 f.write_str(", ")?;
6595 }
6596 write!(f, "'{}'", l.replace('\'', "''"))?;
6597 }
6598 f.write_str(")")
6599 }
6600 TypeKind::Composite { fields, .. } => {
6601 f.write_str("(")?;
6602 for (i, (n, t)) in fields.iter().enumerate() {
6603 if i > 0 {
6604 f.write_str(", ")?;
6605 }
6606 write!(f, "{} {}", quote_ident(n), t)?;
6607 }
6608 f.write_str(")")
6609 }
6610 }
6611 }
6612}
6613
6614impl fmt::Display for CreateMaterializedViewStatement {
6615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6616 f.write_str("CREATE MATERIALIZED VIEW ")?;
6617 if self.if_not_exists {
6618 f.write_str("IF NOT EXISTS ")?;
6619 }
6620 write!(f, "{}", quote_ident(&self.name))?;
6621 if !self.columns.is_empty() {
6622 f.write_str(" (")?;
6623 for (i, c) in self.columns.iter().enumerate() {
6624 if i > 0 {
6625 f.write_str(", ")?;
6626 }
6627 write!(f, "{}", quote_ident(c))?;
6628 }
6629 f.write_str(")")?;
6630 }
6631 write!(f, " AS {}", self.body)?;
6632 if !self.with_data {
6633 f.write_str(" WITH NO DATA")?;
6634 }
6635 Ok(())
6636 }
6637}
6638
6639impl fmt::Display for CreateViewStatement {
6640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6641 f.write_str("CREATE ")?;
6642 if self.or_replace {
6643 f.write_str("OR REPLACE ")?;
6644 }
6645 if self.temporary {
6646 f.write_str("TEMPORARY ")?;
6647 }
6648 f.write_str("VIEW ")?;
6649 if self.if_not_exists {
6650 f.write_str("IF NOT EXISTS ")?;
6651 }
6652 write!(f, "{}", quote_ident(&self.name))?;
6653 if !self.columns.is_empty() {
6654 f.write_str(" (")?;
6655 for (i, c) in self.columns.iter().enumerate() {
6656 if i > 0 {
6657 f.write_str(", ")?;
6658 }
6659 write!(f, "{}", quote_ident(c))?;
6660 }
6661 f.write_str(")")?;
6662 }
6663 write!(f, " AS {}", self.body)?;
6664 match self.check_option {
6665 Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6666 Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6667 None => Ok(()),
6668 }
6669 }
6670}
6671
6672impl fmt::Display for CreateSequenceStatement {
6673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6674 f.write_str("CREATE ")?;
6675 if self.temporary {
6676 f.write_str("TEMPORARY ")?;
6677 }
6678 f.write_str("SEQUENCE ")?;
6679 if self.if_not_exists {
6680 f.write_str("IF NOT EXISTS ")?;
6681 }
6682 write!(f, "{}", quote_ident(&self.name))?;
6683 if let Some(dt) = self.data_type {
6684 write!(f, " AS {dt}")?;
6685 }
6686 write_sequence_options(f, &self.options)
6687 }
6688}
6689
6690impl fmt::Display for AlterSequenceStatement {
6691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6692 f.write_str("ALTER SEQUENCE ")?;
6693 if self.if_exists {
6694 f.write_str("IF EXISTS ")?;
6695 }
6696 write!(f, "{}", quote_ident(&self.name))?;
6697 write_sequence_options(f, &self.options)
6698 }
6699}
6700
6701impl fmt::Display for SequenceDataType {
6702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6703 f.write_str(match self {
6704 Self::SmallInt => "smallint",
6705 Self::Int => "integer",
6706 Self::BigInt => "bigint",
6707 })
6708 }
6709}
6710
6711fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6712 if let Some(n) = o.increment {
6713 write!(f, " INCREMENT BY {n}")?;
6714 }
6715 match o.min_value {
6716 Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6717 Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6718 None => {}
6719 }
6720 match o.max_value {
6721 Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6722 Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6723 None => {}
6724 }
6725 if let Some(n) = o.start {
6726 write!(f, " START WITH {n}")?;
6727 }
6728 match o.restart {
6729 Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6730 Some(None) => f.write_str(" RESTART")?,
6731 None => {}
6732 }
6733 if let Some(n) = o.cache {
6734 write!(f, " CACHE {n}")?;
6735 }
6736 match o.cycle {
6737 Some(true) => f.write_str(" CYCLE")?,
6738 Some(false) => f.write_str(" NO CYCLE")?,
6739 None => {}
6740 }
6741 if let Some(ob) = &o.owned_by {
6742 match ob {
6743 SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6744 SequenceOwnedBy::Column { table, column } => {
6745 write!(
6746 f,
6747 " OWNED BY {}.{}",
6748 quote_ident(table),
6749 quote_ident(column)
6750 )?;
6751 }
6752 }
6753 }
6754 Ok(())
6755}
6756
6757impl fmt::Display for CreateFunctionStatement {
6758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6759 f.write_str("CREATE ")?;
6760 if self.or_replace {
6761 f.write_str("OR REPLACE ")?;
6762 }
6763 write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6764 for (i, arg) in self.args.iter().enumerate() {
6765 if i > 0 {
6766 f.write_str(", ")?;
6767 }
6768 match arg.mode {
6769 FunctionArgMode::In => {}
6770 FunctionArgMode::Out => f.write_str("OUT ")?,
6771 FunctionArgMode::InOut => f.write_str("INOUT ")?,
6772 }
6773 if let Some(name) = &arg.name {
6774 write!(f, "{} ", quote_ident(name))?;
6775 }
6776 match &arg.ty {
6777 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6778 FunctionArgType::Raw(s) => f.write_str(s)?,
6779 }
6780 }
6781 f.write_str(") RETURNS ")?;
6782 match &self.returns {
6783 FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6784 FunctionReturn::Void => f.write_str("VOID")?,
6785 FunctionReturn::Type(t) => write!(f, "{t}")?,
6786 FunctionReturn::Other(s) => f.write_str(s)?,
6787 }
6788 write!(f, " LANGUAGE {} AS $$", self.language)?;
6789 match &self.body {
6790 FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6791 FunctionBody::Raw(s) => f.write_str(s)?,
6792 }
6793 f.write_str("$$")
6794 }
6795}
6796
6797impl fmt::Display for PlPgSqlBlock {
6798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6799 if !self.declarations.is_empty() {
6800 f.write_str("DECLARE\n")?;
6801 for d in &self.declarations {
6802 write!(f, " {} ", quote_ident(&d.name))?;
6803 match &d.ty {
6804 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6805 FunctionArgType::Raw(s) => f.write_str(s)?,
6806 }
6807 if let Some(e) = &d.default {
6808 write!(f, " := {e}")?;
6809 }
6810 f.write_str(";\n")?;
6811 }
6812 }
6813 f.write_str("BEGIN\n")?;
6814 for stmt in &self.statements {
6815 writeln!(f, " {stmt};")?;
6816 }
6817 // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6818 // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6819 // parsed block through it — so every exception handler a function
6820 // declared was thrown away AT STORE TIME. The block executed fine while
6821 // it was still an AST (a DO block never round-trips through text), which
6822 // is why only functions and triggers lost theirs.
6823 if !self.exception_handlers.is_empty() {
6824 f.write_str("EXCEPTION\n")?;
6825 for h in &self.exception_handlers {
6826 writeln!(f, " WHEN {} THEN", h.conditions.join(" OR "))?;
6827 for stmt in &h.body {
6828 writeln!(f, " {stmt};")?;
6829 }
6830 }
6831 }
6832 f.write_str("END")
6833 }
6834}
6835
6836impl fmt::Display for PlPgSqlStmt {
6837 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6838 match self {
6839 Self::Assign { target, value } => write!(f, "{target} := {value}"),
6840 Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6841 Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6842 Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6843 Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6844 Self::Return(t) => match t {
6845 ReturnTarget::New => f.write_str("RETURN NEW"),
6846 ReturnTarget::Old => f.write_str("RETURN OLD"),
6847 ReturnTarget::Null => f.write_str("RETURN NULL"),
6848 ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6849 },
6850 Self::If {
6851 branches,
6852 else_branch,
6853 } => {
6854 for (i, (cond, body)) in branches.iter().enumerate() {
6855 if i == 0 {
6856 write!(f, "IF {cond} THEN ")?;
6857 } else {
6858 write!(f, " ELSIF {cond} THEN ")?;
6859 }
6860 for (j, s) in body.iter().enumerate() {
6861 if j > 0 {
6862 f.write_str("; ")?;
6863 }
6864 write!(f, "{s}")?;
6865 }
6866 }
6867 if !else_branch.is_empty() {
6868 f.write_str(" ELSE ")?;
6869 for (j, s) in else_branch.iter().enumerate() {
6870 if j > 0 {
6871 f.write_str("; ")?;
6872 }
6873 write!(f, "{s}")?;
6874 }
6875 }
6876 f.write_str(" END IF")
6877 }
6878 Self::Raise {
6879 level,
6880 message,
6881 args,
6882 } => {
6883 let lvl = match level {
6884 RaiseLevel::Notice => "NOTICE",
6885 RaiseLevel::Warning => "WARNING",
6886 RaiseLevel::Info => "INFO",
6887 RaiseLevel::Log => "LOG",
6888 RaiseLevel::Debug => "DEBUG",
6889 RaiseLevel::Exception => "EXCEPTION",
6890 };
6891 write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6892 for a in args {
6893 write!(f, ", {a}")?;
6894 }
6895 Ok(())
6896 }
6897 Self::EmbeddedSql(s) => write!(f, "{s}"),
6898 Self::Assert { condition, message } => {
6899 write!(f, "ASSERT {condition}")?;
6900 if let Some(m) = message {
6901 write!(f, ", {m}")?;
6902 }
6903 Ok(())
6904 }
6905 Self::While { condition, body } => {
6906 writeln!(f, "WHILE {condition} LOOP")?;
6907 for s in body {
6908 writeln!(f, " {s};")?;
6909 }
6910 f.write_str("END LOOP")
6911 }
6912 Self::ForRange {
6913 var,
6914 start,
6915 end,
6916 reverse,
6917 body,
6918 } => {
6919 write!(f, "FOR {var} IN ")?;
6920 if *reverse {
6921 f.write_str("REVERSE ")?;
6922 }
6923 writeln!(f, "{start}..{end} LOOP")?;
6924 for s in body {
6925 writeln!(f, " {s};")?;
6926 }
6927 f.write_str("END LOOP")
6928 }
6929 Self::Loop { body } => {
6930 writeln!(f, "LOOP")?;
6931 for s in body {
6932 writeln!(f, " {s};")?;
6933 }
6934 f.write_str("END LOOP")
6935 }
6936 Self::Exit { when } => {
6937 f.write_str("EXIT")?;
6938 if let Some(c) = when {
6939 write!(f, " WHEN {c}")?;
6940 }
6941 Ok(())
6942 }
6943 Self::Continue { when } => {
6944 f.write_str("CONTINUE")?;
6945 if let Some(c) = when {
6946 write!(f, " WHEN {c}")?;
6947 }
6948 Ok(())
6949 }
6950 Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
6951 Self::ForQuery { var, query, body } => {
6952 writeln!(f, "FOR {var} IN ({query}) LOOP")?;
6953 for s in body {
6954 writeln!(f, " {s};")?;
6955 }
6956 f.write_str("END LOOP")
6957 }
6958 Self::ForExecute {
6959 var,
6960 sql_expr,
6961 body,
6962 } => {
6963 writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
6964 for s in body {
6965 writeln!(f, " {s};")?;
6966 }
6967 f.write_str("END LOOP")
6968 }
6969 }
6970 }
6971}
6972
6973impl fmt::Display for AssignTarget {
6974 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6975 match self {
6976 Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
6977 Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
6978 Self::Local(n) => f.write_str(n),
6979 }
6980 }
6981}
6982
6983impl fmt::Display for CreateTriggerStatement {
6984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6985 f.write_str("CREATE ")?;
6986 if self.or_replace {
6987 f.write_str("OR REPLACE ")?;
6988 }
6989 write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
6990 match self.timing {
6991 TriggerTiming::Before => f.write_str("BEFORE")?,
6992 TriggerTiming::After => f.write_str("AFTER")?,
6993 TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
6994 }
6995 for (i, e) in self.events.iter().enumerate() {
6996 if i == 0 {
6997 f.write_str(" ")?;
6998 } else {
6999 f.write_str(" OR ")?;
7000 }
7001 match e {
7002 TriggerEvent::Insert => f.write_str("INSERT")?,
7003 TriggerEvent::Update => {
7004 f.write_str("UPDATE")?;
7005 if !self.update_columns.is_empty() {
7006 f.write_str(" OF ")?;
7007 for (j, col) in self.update_columns.iter().enumerate() {
7008 if j > 0 {
7009 f.write_str(", ")?;
7010 }
7011 f.write_str("e_ident(col))?;
7012 }
7013 }
7014 }
7015 TriggerEvent::Delete => f.write_str("DELETE")?,
7016 TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
7017 }
7018 }
7019 write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
7020 match self.for_each {
7021 TriggerForEach::Row => f.write_str("ROW")?,
7022 TriggerForEach::Statement => f.write_str("STATEMENT")?,
7023 }
7024 write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
7025 }
7026}
7027
7028impl fmt::Display for CreateIndexStatement {
7029 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7030 if self.is_unique {
7031 f.write_str("CREATE UNIQUE INDEX ")?;
7032 } else {
7033 f.write_str("CREATE INDEX ")?;
7034 }
7035 if self.if_not_exists {
7036 f.write_str("IF NOT EXISTS ")?;
7037 }
7038 write!(
7039 f,
7040 "{} ON {} ",
7041 quote_ident(&self.name),
7042 quote_ident(&self.table)
7043 )?;
7044 match self.method {
7045 IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
7046 IndexMethod::Brin => f.write_str("USING brin ")?,
7047 IndexMethod::Gin => f.write_str("USING gin ")?,
7048 IndexMethod::BTree => {}
7049 }
7050 if let Some(expr) = &self.expression {
7051 write!(f, "({})", expr)?;
7052 } else if self.extra_columns.is_empty() {
7053 // v7.15.0 — preserve operator class on round-trip
7054 // (`(col opclass)`) so WAL replay reconstructs the
7055 // engine-routing intent (e.g. `gin_trgm_ops` →
7056 // trigram-GIN build path).
7057 if let Some(op) = &self.opclass {
7058 write!(f, "({} {})", quote_ident(&self.column), op)?;
7059 } else {
7060 write!(f, "({})", quote_ident(&self.column))?;
7061 }
7062 } else {
7063 // v7.9.14 — multi-column key. Emit each column quoted
7064 // so the round-tripped form re-parses to identical AST.
7065 f.write_str("(")?;
7066 write!(f, "{}", quote_ident(&self.column))?;
7067 for c in &self.extra_columns {
7068 write!(f, ", {}", quote_ident(c))?;
7069 }
7070 f.write_str(")")?;
7071 }
7072 if !self.included_columns.is_empty() {
7073 f.write_str(" INCLUDE (")?;
7074 for (i, c) in self.included_columns.iter().enumerate() {
7075 if i > 0 {
7076 f.write_str(", ")?;
7077 }
7078 write!(f, "{}", quote_ident(c))?;
7079 }
7080 f.write_str(")")?;
7081 }
7082 if let Some(pred) = &self.partial_predicate {
7083 write!(f, " WHERE {}", pred)?;
7084 }
7085 Ok(())
7086 }
7087}
7088
7089impl fmt::Display for CreateTableStatement {
7090 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7091 f.write_str("CREATE TABLE ")?;
7092 if self.if_not_exists {
7093 f.write_str("IF NOT EXISTS ")?;
7094 }
7095 write!(f, "{}", quote_ident(&self.name))?;
7096 // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
7097 // no column list and no constraints; the table inherits its
7098 // columns from the parent at engine-DDL time.
7099 if let Some(spec) = &self.partition_of {
7100 write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
7101 return match &spec.bounds {
7102 PartitionOfBoundsAst::Range { lower, upper } => {
7103 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7104 }
7105 PartitionOfBoundsAst::List { values } => {
7106 f.write_str("FOR VALUES IN (")?;
7107 for (i, v) in values.iter().enumerate() {
7108 if i > 0 {
7109 f.write_str(", ")?;
7110 }
7111 write!(f, "{}", v)?;
7112 }
7113 f.write_str(")")
7114 }
7115 PartitionOfBoundsAst::Hash { modulus, remainder } => {
7116 write!(
7117 f,
7118 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7119 modulus, remainder
7120 )
7121 }
7122 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7123 };
7124 }
7125 f.write_str(" (")?;
7126 for (i, col) in self.columns.iter().enumerate() {
7127 if i > 0 {
7128 f.write_str(", ")?;
7129 }
7130 write!(f, "{col}")?;
7131 }
7132 // v7.6.0 — render FK constraints in table-level form, after
7133 // the column list. WAL replay round-trips through Display, so
7134 // every FK must serialise here for replay to reconstruct the
7135 // schema bit-for-bit.
7136 for fk in &self.foreign_keys {
7137 f.write_str(", ")?;
7138 write!(f, "{fk}")?;
7139 }
7140 // v7.13.0 — render table-level constraints (PRIMARY KEY /
7141 // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
7142 // column-level UNIQUE / CHECK get lifted to this list at
7143 // parse time, so emitting only here avoids double-counting.
7144 for tc in &self.table_constraints {
7145 f.write_str(", ")?;
7146 write!(f, "{tc}")?;
7147 }
7148 f.write_str(")")?;
7149 // v7.37.6-B — partition-parent suffix renders after the
7150 // closing column-list paren, before the optional MySQL
7151 // table-options tail (which Display doesn't currently emit).
7152 if let Some(spec) = &self.partition_by {
7153 f.write_str(" PARTITION BY ")?;
7154 match spec.kind {
7155 PartitionKindAst::Range => f.write_str("RANGE ")?,
7156 PartitionKindAst::List => f.write_str("LIST ")?,
7157 PartitionKindAst::Hash => f.write_str("HASH ")?,
7158 }
7159 f.write_str("(")?;
7160 for (i, col) in spec.key_columns.iter().enumerate() {
7161 if i > 0 {
7162 f.write_str(", ")?;
7163 }
7164 f.write_str("e_ident(col))?;
7165 }
7166 f.write_str(")")?;
7167 }
7168 Ok(())
7169 }
7170}
7171
7172fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
7173 match t {
7174 AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
7175 AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
7176 write!(f, "REPLICA IDENTITY USING INDEX {index}")
7177 }
7178 AlterTableTarget::Inherit { parent, detach } => {
7179 if *detach {
7180 write!(f, "NO INHERIT {parent}")
7181 } else {
7182 write!(f, "INHERIT {parent}")
7183 }
7184 }
7185 AlterTableTarget::SetHotTierBytes(n) => {
7186 write!(f, "SET hot_tier_bytes = {n}")
7187 }
7188 AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
7189 AlterTableTarget::DropForeignKey { name, if_exists } => {
7190 f.write_str("DROP CONSTRAINT ")?;
7191 if *if_exists {
7192 f.write_str("IF EXISTS ")?;
7193 }
7194 write!(f, "{}", quote_ident(name))
7195 }
7196 AlterTableTarget::DropIndex { name, if_exists } => {
7197 f.write_str("DROP INDEX ")?;
7198 if *if_exists {
7199 f.write_str("IF EXISTS ")?;
7200 }
7201 write!(f, "{}", quote_ident(name))
7202 }
7203 AlterTableTarget::ModifyColumn {
7204 column,
7205 rename_to,
7206 definition,
7207 position,
7208 } => {
7209 if let Some(new) = rename_to {
7210 write!(
7211 f,
7212 "CHANGE COLUMN {} {} {}",
7213 quote_ident(column),
7214 quote_ident(new),
7215 definition.ty
7216 )?;
7217 } else {
7218 write!(f, "MODIFY COLUMN {} {}", quote_ident(column), definition.ty)?;
7219 }
7220 if !definition.nullable {
7221 f.write_str(" NOT NULL")?;
7222 }
7223 write_column_position(f, position.as_ref())
7224 }
7225 AlterTableTarget::RenameIndex { old, new } => {
7226 write!(
7227 f,
7228 "RENAME INDEX {} TO {}",
7229 quote_ident(old),
7230 quote_ident(new)
7231 )
7232 }
7233 AlterTableTarget::SetTableAutoIncrement(n) => write!(f, "AUTO_INCREMENT = {n}"),
7234 AlterTableTarget::SetEngine(name) => write!(f, "ENGINE = {name}"),
7235 AlterTableTarget::ConvertToCharacterSet { charset, collate } => {
7236 write!(f, "CONVERT TO CHARACTER SET {charset}")?;
7237 if let Some(c) = collate {
7238 write!(f, " COLLATE {c}")?;
7239 }
7240 Ok(())
7241 }
7242 AlterTableTarget::AddColumn {
7243 column,
7244 if_not_exists,
7245 position,
7246 } => {
7247 f.write_str("ADD COLUMN ")?;
7248 if *if_not_exists {
7249 f.write_str("IF NOT EXISTS ")?;
7250 }
7251 write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
7252 if !column.nullable {
7253 f.write_str(" NOT NULL")?;
7254 }
7255 if let Some(d) = &column.default {
7256 write!(f, " DEFAULT {d}")?;
7257 }
7258 if column.auto_increment {
7259 f.write_str(" AUTO_INCREMENT")?;
7260 }
7261 if column.is_primary_key {
7262 f.write_str(" PRIMARY KEY")?;
7263 }
7264 Ok(())
7265 }
7266 AlterTableTarget::AlterColumnType {
7267 column,
7268 new_type,
7269 using,
7270 collation,
7271 } => {
7272 write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
7273 if let Some((_, name)) = collation {
7274 write!(f, " COLLATE {}", quote_ident(name))?;
7275 }
7276 if let Some(u) = using {
7277 write!(f, " USING {u}")?;
7278 }
7279 Ok(())
7280 }
7281 AlterTableTarget::DropColumn {
7282 column,
7283 if_exists,
7284 cascade,
7285 } => {
7286 f.write_str("DROP COLUMN ")?;
7287 if *if_exists {
7288 f.write_str("IF EXISTS ")?;
7289 }
7290 write!(f, "{}", quote_ident(column))?;
7291 if *cascade {
7292 f.write_str(" CASCADE")?;
7293 }
7294 Ok(())
7295 }
7296 AlterTableTarget::AddTableConstraint(tc) => {
7297 write!(f, "ADD {tc}")
7298 }
7299 AlterTableTarget::ValidateConstraint { name } => {
7300 write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
7301 }
7302 AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
7303 AlterTableTarget::ClusterOn { index } => match index {
7304 Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
7305 None => f.write_str("SET WITHOUT CLUSTER"),
7306 },
7307 AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
7308 // Round-trip-safe spelling: re-parsing this form lowers
7309 // back to SetColumnAutoIncrement (the nextval default is
7310 // how pg_dump says "serial").
7311 let seq = seq_name
7312 .clone()
7313 .unwrap_or_else(|| alloc::format!("{column}_seq"));
7314 write!(
7315 f,
7316 "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
7317 quote_ident(column)
7318 )
7319 }
7320 AlterTableTarget::RenameColumn { old, new } => {
7321 write!(
7322 f,
7323 "RENAME COLUMN {} TO {}",
7324 quote_ident(old),
7325 quote_ident(new)
7326 )
7327 }
7328 AlterTableTarget::RenameConstraint { old, new } => {
7329 write!(
7330 f,
7331 "RENAME CONSTRAINT {} TO {}",
7332 quote_ident(old),
7333 quote_ident(new)
7334 )
7335 }
7336 AlterTableTarget::RenameTable { new } => {
7337 write!(f, "RENAME TO {}", quote_ident(new))
7338 }
7339 AlterTableTarget::SetTriggerEnabled { which, enabled } => {
7340 f.write_str(if *enabled {
7341 "ENABLE TRIGGER "
7342 } else {
7343 "DISABLE TRIGGER "
7344 })?;
7345 match which {
7346 TriggerSelector::All => f.write_str("ALL"),
7347 TriggerSelector::Named(n) => f.write_str("e_ident(n)),
7348 }
7349 }
7350 AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
7351 (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
7352 (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
7353 (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
7354 (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
7355 (None, None) => Ok(()),
7356 },
7357 AlterTableTarget::AttachPartition { child, bounds } => {
7358 write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
7359 match bounds {
7360 PartitionOfBoundsAst::Range { lower, upper } => {
7361 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7362 }
7363 PartitionOfBoundsAst::List { values } => {
7364 f.write_str("FOR VALUES IN (")?;
7365 for (i, v) in values.iter().enumerate() {
7366 if i > 0 {
7367 f.write_str(", ")?;
7368 }
7369 write!(f, "{}", v)?;
7370 }
7371 f.write_str(")")
7372 }
7373 PartitionOfBoundsAst::Hash { modulus, remainder } => {
7374 write!(
7375 f,
7376 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7377 modulus, remainder
7378 )
7379 }
7380 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7381 }
7382 }
7383 AlterTableTarget::DetachPartition {
7384 child,
7385 concurrently,
7386 finalize,
7387 } => {
7388 write!(f, "DETACH PARTITION {}", quote_ident(child))?;
7389 if *concurrently {
7390 f.write_str(" CONCURRENTLY")?;
7391 }
7392 if *finalize {
7393 f.write_str(" FINALIZE")?;
7394 }
7395 Ok(())
7396 }
7397 AlterTableTarget::AlterColumnSetDefault {
7398 column,
7399 default_expr,
7400 } => write!(
7401 f,
7402 "ALTER COLUMN {} SET DEFAULT {}",
7403 quote_ident(column),
7404 default_expr
7405 ),
7406 AlterTableTarget::AlterColumnDropDefault { column } => {
7407 write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
7408 }
7409 AlterTableTarget::AlterColumnSetNotNull { column } => {
7410 write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
7411 }
7412 AlterTableTarget::AlterColumnDropNotNull { column } => {
7413 write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
7414 }
7415 AlterTableTarget::AlterColumnRestart { column, with } => {
7416 write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
7417 if let Some(n) = with {
7418 write!(f, " WITH {n}")?;
7419 }
7420 Ok(())
7421 }
7422 AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
7423 write!(
7424 f,
7425 "ALTER COLUMN {} DROP EXPRESSION{}",
7426 quote_ident(column),
7427 if *if_exists { " IF EXISTS" } else { "" }
7428 )
7429 }
7430 AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
7431 write!(
7432 f,
7433 "ALTER COLUMN {} DROP IDENTITY{}",
7434 quote_ident(column),
7435 if *if_exists { " IF EXISTS" } else { "" }
7436 )
7437 }
7438 AlterTableTarget::AlterColumnSetExpression { column, expr } => {
7439 write!(
7440 f,
7441 "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
7442 quote_ident(column)
7443 )
7444 }
7445 }
7446}
7447
7448impl fmt::Display for TableConstraint {
7449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7450 match self {
7451 Self::PrimaryKey { name, columns, .. } => {
7452 if let Some(n) = name {
7453 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7454 }
7455 f.write_str("PRIMARY KEY (")?;
7456 for (i, c) in columns.iter().enumerate() {
7457 if i > 0 {
7458 f.write_str(", ")?;
7459 }
7460 f.write_str("e_ident(c))?;
7461 }
7462 f.write_str(")")
7463 }
7464 Self::Unique {
7465 name,
7466 columns,
7467 nulls_not_distinct,
7468 ..
7469 } => {
7470 if let Some(n) = name {
7471 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7472 }
7473 f.write_str("UNIQUE ")?;
7474 if *nulls_not_distinct {
7475 f.write_str("NULLS NOT DISTINCT ")?;
7476 }
7477 f.write_str("(")?;
7478 for (i, c) in columns.iter().enumerate() {
7479 if i > 0 {
7480 f.write_str(", ")?;
7481 }
7482 f.write_str("e_ident(c))?;
7483 }
7484 f.write_str(")")
7485 }
7486 Self::Check {
7487 name,
7488 expr,
7489 not_valid,
7490 } => {
7491 if let Some(n) = name {
7492 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7493 }
7494 write!(f, "CHECK ({expr})")?;
7495 if *not_valid {
7496 write!(f, " NOT VALID")?;
7497 }
7498 Ok(())
7499 }
7500 Self::Index { name, columns } => {
7501 f.write_str("KEY ")?;
7502 if let Some(n) = name {
7503 write!(f, "{} ", quote_ident(n))?;
7504 }
7505 f.write_str("(")?;
7506 for (i, c) in columns.iter().enumerate() {
7507 if i > 0 {
7508 f.write_str(", ")?;
7509 }
7510 f.write_str("e_ident(c))?;
7511 }
7512 f.write_str(")")
7513 }
7514 Self::FulltextIndex { name, columns } => {
7515 // Mysqldump emits `FULLTEXT KEY name (cols)` —
7516 // Display rounds back to that shape so dump
7517 // replay reproduces the input verbatim.
7518 f.write_str("FULLTEXT KEY ")?;
7519 if let Some(n) = name {
7520 write!(f, "{} ", quote_ident(n))?;
7521 }
7522 f.write_str("(")?;
7523 for (i, c) in columns.iter().enumerate() {
7524 if i > 0 {
7525 f.write_str(", ")?;
7526 }
7527 f.write_str("e_ident(c))?;
7528 }
7529 f.write_str(")")
7530 }
7531 Self::Exclude {
7532 name,
7533 method,
7534 elements,
7535 } => {
7536 if let Some(n) = name {
7537 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7538 }
7539 f.write_str("EXCLUDE ")?;
7540 if let Some(m) = method {
7541 write!(f, "USING {m} ")?;
7542 }
7543 f.write_str("(")?;
7544 for (i, (col, op)) in elements.iter().enumerate() {
7545 if i > 0 {
7546 f.write_str(", ")?;
7547 }
7548 write!(f, "{} WITH {op}", quote_ident(col))?;
7549 }
7550 f.write_str(")")
7551 }
7552 }
7553 }
7554}
7555
7556impl fmt::Display for ForeignKeyConstraint {
7557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7558 if let Some(name) = &self.name {
7559 write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7560 }
7561 f.write_str("FOREIGN KEY (")?;
7562 for (i, c) in self.columns.iter().enumerate() {
7563 if i > 0 {
7564 f.write_str(", ")?;
7565 }
7566 f.write_str("e_ident(c))?;
7567 }
7568 write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7569 if !self.parent_columns.is_empty() {
7570 f.write_str(" (")?;
7571 for (i, c) in self.parent_columns.iter().enumerate() {
7572 if i > 0 {
7573 f.write_str(", ")?;
7574 }
7575 f.write_str("e_ident(c))?;
7576 }
7577 f.write_str(")")?;
7578 }
7579 // Only render non-default actions to keep Display output
7580 // close to user input. SPG's default is RESTRICT (matches
7581 // SQL spec).
7582 if self.on_delete != FkAction::Restrict {
7583 write!(f, " ON DELETE {}", self.on_delete)?;
7584 }
7585 if self.on_update != FkAction::Restrict {
7586 write!(f, " ON UPDATE {}", self.on_update)?;
7587 }
7588 Ok(())
7589 }
7590}
7591
7592impl fmt::Display for FkAction {
7593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7594 match self {
7595 Self::Restrict => f.write_str("RESTRICT"),
7596 Self::Cascade => f.write_str("CASCADE"),
7597 Self::SetNull => f.write_str("SET NULL"),
7598 Self::SetDefault => f.write_str("SET DEFAULT"),
7599 Self::NoAction => f.write_str("NO ACTION"),
7600 }
7601 }
7602}
7603
7604impl fmt::Display for ColumnDef {
7605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7606 // v7.30.1 (mailrs round-24 class audit) — the type position
7607 // must re-parse to the same ColumnDef: a user-defined type
7608 // reference and the MySQL inline ENUM / SET value lists all
7609 // lower `ty` to Text, so rendering `ty` lost them.
7610 write!(f, "{}", quote_ident(&self.name))?;
7611 if let Some(ut) = &self.user_type_ref {
7612 write!(f, " {}", quote_ident(ut))?;
7613 } else if let Some(variants) = &self.inline_enum_variants {
7614 write_variant_list(f, "ENUM", variants)?;
7615 } else if let Some(variants) = &self.inline_set_variants {
7616 write_variant_list(f, "SET", variants)?;
7617 } else {
7618 write!(f, " {}", self.ty)?;
7619 }
7620 if self.is_unsigned {
7621 f.write_str(" UNSIGNED")?;
7622 }
7623 // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7624 // DDL. Only emits when non-default so the typical output
7625 // stays unchanged.
7626 match self.collation {
7627 Collation::Binary => {}
7628 Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7629 }
7630 if let Some(d) = &self.default {
7631 write!(f, " DEFAULT {d}")?;
7632 }
7633 if self.auto_increment {
7634 f.write_str(" AUTO_INCREMENT")?;
7635 }
7636 if !self.nullable {
7637 f.write_str(" NOT NULL")?;
7638 }
7639 // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7640 // is NOT lifted to a table-level constraint at parse time
7641 // (unlike UNIQUE / CHECK), so the WAL round trip of a
7642 // prepared CREATE TABLE silently dropped the primary key.
7643 if self.is_primary_key {
7644 f.write_str(" PRIMARY KEY")?;
7645 }
7646 // The parser accepts only CURRENT_TIMESTAMP here (stored as
7647 // now()), so that spelling is the lossless round trip.
7648 if self.on_update_runtime.is_some() {
7649 f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7650 }
7651 // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7652 // replay reconstructs the computed-column declaration. The
7653 // expression sits inside a single set of parens; STORED is
7654 // the only variant the parser accepts.
7655 if let Some(gen_expr) = &self.generated_stored_expr {
7656 write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7657 }
7658 Ok(())
7659 }
7660}
7661
7662/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7663/// types (MySQL flavour; `ty` is Text underneath).
7664fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7665 write!(f, " {kw}(")?;
7666 for (i, v) in variants.iter().enumerate() {
7667 if i > 0 {
7668 f.write_str(", ")?;
7669 }
7670 write!(f, "'{}'", v.replace('\'', "''"))?;
7671 }
7672 f.write_str(")")
7673}
7674
7675impl fmt::Display for InsertStatement {
7676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7677 write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7678 if let Some(cols) = &self.columns {
7679 f.write_str(" (")?;
7680 for (i, c) in cols.iter().enumerate() {
7681 if i > 0 {
7682 f.write_str(", ")?;
7683 }
7684 f.write_str("e_ident(c))?;
7685 }
7686 f.write_str(")")?;
7687 }
7688 // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7689 // skipping the VALUES list (mailrs round-5 G4).
7690 if let Some(sel) = &self.select_source {
7691 write!(f, " {sel}")?;
7692 } else {
7693 f.write_str(" VALUES ")?;
7694 for (ri, row) in self.rows.iter().enumerate() {
7695 if ri > 0 {
7696 f.write_str(", ")?;
7697 }
7698 f.write_str("(")?;
7699 for (i, v) in row.iter().enumerate() {
7700 if i > 0 {
7701 f.write_str(", ")?;
7702 }
7703 write!(f, "{v}")?;
7704 }
7705 f.write_str(")")?;
7706 }
7707 }
7708 // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7709 // Display round trip: WAL persistence renders the bind-final
7710 // AST through this impl, and a replayed bare INSERT turns a
7711 // legal upsert no-op into a UNIQUE violation that refuses to
7712 // open the catalog.
7713 if let Some(oc) = &self.on_conflict {
7714 write!(f, " {oc}")?;
7715 }
7716 write_returning(self.returning.as_deref(), f)?;
7717 Ok(())
7718 }
7719}
7720
7721/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7722/// parser produced, so the AST→SQL round trip preserves upsert
7723/// semantics (WAL replay depends on it).
7724impl fmt::Display for OnConflictClause {
7725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7726 f.write_str("ON CONFLICT")?;
7727 if let Some(name) = &self.constraint_name {
7728 write!(f, " ON CONSTRAINT {name}")?;
7729 }
7730 if !self.target_columns.is_empty() {
7731 f.write_str(" (")?;
7732 for (i, c) in self.target_columns.iter().enumerate() {
7733 if i > 0 {
7734 f.write_str(", ")?;
7735 }
7736 f.write_str("e_ident(c))?;
7737 }
7738 f.write_str(")")?;
7739 }
7740 if let Some(w) = &self.index_where {
7741 write!(f, " WHERE {w}")?;
7742 }
7743 match &self.action {
7744 OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7745 OnConflictAction::Update {
7746 assignments,
7747 where_,
7748 } => {
7749 f.write_str(" DO UPDATE SET ")?;
7750 for (i, (col, expr)) in assignments.iter().enumerate() {
7751 if i > 0 {
7752 f.write_str(", ")?;
7753 }
7754 write!(f, "{} = {expr}", quote_ident(col))?;
7755 }
7756 if let Some(w) = where_ {
7757 write!(f, " WHERE {w}")?;
7758 }
7759 Ok(())
7760 }
7761 }
7762 }
7763}
7764
7765/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7766/// tail for the three DML Display impls.
7767fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7768 let Some(items) = ret else {
7769 return Ok(());
7770 };
7771 f.write_str(" RETURNING ")?;
7772 for (i, item) in items.iter().enumerate() {
7773 if i > 0 {
7774 f.write_str(", ")?;
7775 }
7776 write!(f, "{item}")?;
7777 }
7778 Ok(())
7779}
7780
7781impl fmt::Display for UpdateStatement {
7782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7783 write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7784 for (i, (col, expr)) in self.assignments.iter().enumerate() {
7785 if i > 0 {
7786 f.write_str(", ")?;
7787 }
7788 write!(f, "{} = {expr}", quote_ident(col))?;
7789 }
7790 if let Some(w) = &self.where_ {
7791 write!(f, " WHERE {w}")?;
7792 }
7793 // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7794 if let Some(ol) = self.order_limit.as_deref() {
7795 if !ol.order_by.is_empty() {
7796 f.write_str(" ORDER BY ")?;
7797 for (i, o) in ol.order_by.iter().enumerate() {
7798 if i > 0 {
7799 f.write_str(", ")?;
7800 }
7801 write!(f, "{}", o.expr)?;
7802 if o.desc {
7803 f.write_str(" DESC")?;
7804 }
7805 match o.nulls_first {
7806 Some(true) => f.write_str(" NULLS FIRST")?,
7807 Some(false) => f.write_str(" NULLS LAST")?,
7808 None => {}
7809 }
7810 }
7811 }
7812 if let Some(n) = ol.limit {
7813 write!(f, " LIMIT {n}")?;
7814 }
7815 }
7816 write_returning(self.returning.as_deref(), f)?;
7817 Ok(())
7818 }
7819}
7820
7821impl fmt::Display for DeleteStatement {
7822 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7823 write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7824 if let Some(w) = &self.where_ {
7825 write!(f, " WHERE {w}")?;
7826 }
7827 write_returning(self.returning.as_deref(), f)?;
7828 Ok(())
7829 }
7830}
7831
7832impl fmt::Display for CteBody {
7833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7834 match self {
7835 Self::Select(s) => write!(f, "{s}"),
7836 Self::Insert(s) => write!(f, "{s}"),
7837 Self::Update(s) => write!(f, "{s}"),
7838 Self::Delete(s) => write!(f, "{s}"),
7839 Self::Merge(s) => write!(f, "{s}"),
7840 }
7841 }
7842}
7843
7844impl fmt::Display for MergeStatement {
7845 // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7846 // (it round-trips for the cases tests cover, not for
7847 // round-tripping every edge of the surface).
7848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7849 fmt_with_clause(&self.ctes, f)?;
7850 f.write_str("MERGE INTO ")?;
7851 write!(f, "{}", quote_ident(&self.target))?;
7852 if let Some(a) = &self.target_alias {
7853 write!(f, " {}", quote_ident(a))?;
7854 }
7855 f.write_str(" USING ")?;
7856 if let Some(sub) = &self.source_select {
7857 write!(f, "({sub})")?;
7858 } else {
7859 write!(f, "{}", quote_ident(&self.source))?;
7860 }
7861 if let Some(a) = &self.source_alias {
7862 write!(f, " {}", quote_ident(a))?;
7863 }
7864 if !self.source_column_aliases.is_empty() {
7865 f.write_str("(")?;
7866 for (i, c) in self.source_column_aliases.iter().enumerate() {
7867 if i > 0 {
7868 f.write_str(", ")?;
7869 }
7870 write!(f, "{}", quote_ident(c))?;
7871 }
7872 f.write_str(")")?;
7873 }
7874 write!(f, " ON {}", self.on)?;
7875 for clause in &self.clauses {
7876 f.write_str(" WHEN ")?;
7877 f.write_str(match clause.matched {
7878 MergeMatched::Matched => "MATCHED",
7879 MergeMatched::NotMatched => "NOT MATCHED",
7880 MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7881 })?;
7882 if let Some(c) = &clause.condition {
7883 write!(f, " AND {c}")?;
7884 }
7885 f.write_str(" THEN ")?;
7886 match &clause.action {
7887 MergeAction::Insert { columns, values } => {
7888 f.write_str("INSERT ")?;
7889 // A column list is optional (round 146): the bare
7890 // `INSERT VALUES (…)` form maps positionally.
7891 if !columns.is_empty() {
7892 f.write_str("(")?;
7893 for (i, c) in columns.iter().enumerate() {
7894 if i > 0 {
7895 f.write_str(", ")?;
7896 }
7897 write!(f, "{}", quote_ident(c))?;
7898 }
7899 f.write_str(") ")?;
7900 }
7901 f.write_str("VALUES (")?;
7902 for (i, v) in values.iter().enumerate() {
7903 if i > 0 {
7904 f.write_str(", ")?;
7905 }
7906 write!(f, "{v}")?;
7907 }
7908 f.write_str(")")?;
7909 }
7910 MergeAction::Update { assignments } => {
7911 f.write_str("UPDATE SET ")?;
7912 for (i, (c, e)) in assignments.iter().enumerate() {
7913 if i > 0 {
7914 f.write_str(", ")?;
7915 }
7916 write!(f, "{} = {e}", quote_ident(c))?;
7917 }
7918 }
7919 MergeAction::Delete => f.write_str("DELETE")?,
7920 MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7921 }
7922 }
7923 if let Some(items) = &self.returning {
7924 f.write_str(" RETURNING ")?;
7925 for (i, it) in items.iter().enumerate() {
7926 if i > 0 {
7927 f.write_str(", ")?;
7928 }
7929 write!(f, "{it}")?;
7930 }
7931 }
7932 Ok(())
7933 }
7934}
7935
7936/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
7937/// carry a CTE list and must round-trip it identically.
7938fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
7939 if ctes.is_empty() {
7940 return Ok(());
7941 }
7942 f.write_str("WITH ")?;
7943 if ctes.iter().any(|c| c.recursive) {
7944 f.write_str("RECURSIVE ")?;
7945 }
7946 for (i, cte) in ctes.iter().enumerate() {
7947 if i > 0 {
7948 f.write_str(", ")?;
7949 }
7950 f.write_str("e_ident(&cte.name))?;
7951 if !cte.column_overrides.is_empty() {
7952 f.write_str(" (")?;
7953 for (ci, c) in cte.column_overrides.iter().enumerate() {
7954 if ci > 0 {
7955 f.write_str(", ")?;
7956 }
7957 f.write_str("e_ident(c))?;
7958 }
7959 f.write_str(")")?;
7960 }
7961 write!(f, " AS ({})", cte.body)?;
7962 }
7963 f.write_str(" ")
7964}
7965
7966impl fmt::Display for SelectStatement {
7967 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7968 // v7.30.1 (mailrs round-24 class audit) — the WITH clause
7969 // must survive the round trip; a CTE-using statement
7970 // re-parsed without it references undefined tables.
7971 fmt_with_clause(&self.ctes, f)?;
7972 write_bare_select(self, f)?;
7973 for (kind, peer) in &self.unions {
7974 f.write_str(match kind {
7975 UnionKind::Distinct => " UNION ",
7976 UnionKind::All => " UNION ALL ",
7977 UnionKind::Intersect => " INTERSECT ",
7978 UnionKind::IntersectAll => " INTERSECT ALL ",
7979 UnionKind::Except => " EXCEPT ",
7980 UnionKind::ExceptAll => " EXCEPT ALL ",
7981 })?;
7982 write_bare_select(peer, f)?;
7983 }
7984 if !self.order_by.is_empty() {
7985 f.write_str(" ORDER BY ")?;
7986 for (i, o) in self.order_by.iter().enumerate() {
7987 if i > 0 {
7988 f.write_str(", ")?;
7989 }
7990 write!(f, "{}", o.expr)?;
7991 if o.desc {
7992 f.write_str(" DESC")?;
7993 }
7994 match o.nulls_first {
7995 Some(true) => f.write_str(" NULLS FIRST")?,
7996 Some(false) => f.write_str(" NULLS LAST")?,
7997 None => {}
7998 }
7999 }
8000 }
8001 // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
8002 // exists in the FETCH FIRST spelling; rendering it as LIMIT
8003 // dropped the tie-extension semantics on replay. The parser
8004 // accepts OFFSET before FETCH, so keep that order here.
8005 if self.limit_with_ties {
8006 if let Some(o) = &self.offset {
8007 write!(f, " OFFSET {o}")?;
8008 }
8009 if let Some(n) = &self.limit {
8010 write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
8011 }
8012 } else {
8013 if let Some(n) = &self.limit {
8014 write!(f, " LIMIT {n}")?;
8015 }
8016 if let Some(o) = &self.offset {
8017 write!(f, " OFFSET {o}")?;
8018 }
8019 }
8020 Ok(())
8021 }
8022}
8023
8024fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8025 f.write_str("SELECT ")?;
8026 if s.distinct {
8027 f.write_str("DISTINCT ")?;
8028 }
8029 write_bare_select_body(s, f)
8030}
8031
8032fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8033 for (i, item) in s.items.iter().enumerate() {
8034 if i > 0 {
8035 f.write_str(", ")?;
8036 }
8037 write!(f, "{item}")?;
8038 }
8039 if let Some(t) = &s.from {
8040 write!(f, " FROM {t}")?;
8041 }
8042 if let Some(e) = &s.where_ {
8043 write!(f, " WHERE {e}")?;
8044 }
8045 if let Some(gs) = &s.group_by {
8046 f.write_str(" GROUP BY ")?;
8047 for (i, g) in gs.iter().enumerate() {
8048 if i > 0 {
8049 f.write_str(", ")?;
8050 }
8051 write!(f, "{g}")?;
8052 }
8053 } else if s.group_by_all {
8054 // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
8055 // shortcut parses to group_by: None + this flag; dropping
8056 // it turned an aggregate query into a bare projection on
8057 // re-parse.
8058 f.write_str(" GROUP BY ALL")?;
8059 }
8060 if let Some(h) = &s.having {
8061 write!(f, " HAVING {h}")?;
8062 }
8063 Ok(())
8064}
8065
8066impl fmt::Display for SelectItem {
8067 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8068 match self {
8069 Self::Wildcard => f.write_str("*"),
8070 Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
8071 Self::Expr { expr, alias } => {
8072 write!(f, "{expr}")?;
8073 if let Some(a) = alias {
8074 write!(f, " AS {}", quote_ident(a))?;
8075 }
8076 Ok(())
8077 }
8078 }
8079 }
8080}
8081
8082impl fmt::Display for FromClause {
8083 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8084 write!(f, "{}", self.primary)?;
8085 for j in &self.joins {
8086 match j.kind {
8087 JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
8088 JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
8089 JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
8090 JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
8091 JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
8092 JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
8093 }
8094 if let Some(on) = &j.on {
8095 write!(f, " ON {on}")?;
8096 }
8097 }
8098 Ok(())
8099 }
8100}
8101
8102/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
8103/// for NESTED). Kept close to the parser's grammar so it re-parses.
8104fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
8105 for (i, c) in cols.iter().enumerate() {
8106 if i > 0 {
8107 f.write_str(", ")?;
8108 }
8109 match c {
8110 JsonTableColumn::Ordinality { name } => {
8111 write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
8112 }
8113 JsonTableColumn::Nested { path, columns } => {
8114 write!(f, "NESTED PATH '{path}' COLUMNS (")?;
8115 fmt_json_table_columns(f, columns)?;
8116 f.write_str(")")?;
8117 }
8118 JsonTableColumn::Regular {
8119 name,
8120 ty,
8121 path,
8122 exists,
8123 format_json,
8124 wrapper,
8125 on_empty,
8126 on_error,
8127 } => {
8128 write!(f, "{} {ty}", quote_ident(name))?;
8129 if *format_json {
8130 f.write_str(" FORMAT JSON")?;
8131 }
8132 if *exists {
8133 write!(f, " EXISTS PATH '{path}'")?;
8134 } else {
8135 write!(f, " PATH '{path}'")?;
8136 }
8137 if *wrapper {
8138 f.write_str(" WITH WRAPPER")?;
8139 }
8140 if let JsonTableOnBehavior::Error = on_empty {
8141 f.write_str(" ERROR ON EMPTY")?;
8142 } else if let JsonTableOnBehavior::Default(e) = on_empty {
8143 write!(f, " DEFAULT {e} ON EMPTY")?;
8144 }
8145 if let JsonTableOnBehavior::Error = on_error {
8146 f.write_str(" ERROR ON ERROR")?;
8147 } else if let JsonTableOnBehavior::Default(e) = on_error {
8148 write!(f, " DEFAULT {e} ON ERROR")?;
8149 }
8150 }
8151 }
8152 }
8153 Ok(())
8154}
8155
8156impl fmt::Display for TableRef {
8157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8158 // v7.30.1 (mailrs round-24 class audit) — the dynamic
8159 // table-ref shapes must round-trip: rendering only the
8160 // (synthetic) name turned LATERAL / unnest() /
8161 // generate_series() into references to nonexistent tables
8162 // on re-parse.
8163 // v7.39 (round 205) — JSON_TABLE round-trips through Display
8164 // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
8165 if let Some(jt) = &self.json_table {
8166 write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
8167 if !jt.passing.is_empty() {
8168 f.write_str(" PASSING ")?;
8169 for (i, (n, e)) in jt.passing.iter().enumerate() {
8170 if i > 0 {
8171 f.write_str(", ")?;
8172 }
8173 write!(f, "{e} AS {}", quote_ident(n))?;
8174 }
8175 }
8176 f.write_str(" COLUMNS (")?;
8177 fmt_json_table_columns(f, &jt.columns)?;
8178 f.write_str(")")?;
8179 if let Some(a) = &self.alias {
8180 write!(f, " AS {}", quote_ident(a))?;
8181 }
8182 return Ok(());
8183 }
8184 if let Some(inner) = &self.lateral_subquery {
8185 write!(f, "LATERAL ({inner})")?;
8186 if let Some(a) = &self.alias {
8187 write!(f, " AS {}", quote_ident(a))?;
8188 // v7.37 D.28 — a derived table on the lateral_subquery channel
8189 // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
8190 // lowers here). Rendering the alias without the column list lost
8191 // the column names on re-parse (a view body round-trips through
8192 // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
8193 if !self.unnest_column_aliases.is_empty() {
8194 f.write_str(" (")?;
8195 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8196 if i > 0 {
8197 f.write_str(", ")?;
8198 }
8199 f.write_str("e_ident(c))?;
8200 }
8201 f.write_str(")")?;
8202 }
8203 }
8204 return Ok(());
8205 }
8206 if let Some(expr) = &self.unnest_expr {
8207 write!(f, "UNNEST({expr})")?;
8208 if let Some(a) = &self.alias {
8209 write!(f, " AS {}", quote_ident(a))?;
8210 if !self.unnest_column_aliases.is_empty() {
8211 f.write_str(" (")?;
8212 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8213 if i > 0 {
8214 f.write_str(", ")?;
8215 }
8216 f.write_str("e_ident(c))?;
8217 }
8218 f.write_str(")")?;
8219 }
8220 }
8221 return Ok(());
8222 }
8223 // 7.38.1 S5.1 — a FROM-position table function must re-render
8224 // as the CALL, not its bare name: ARRAY(subquery) desugars by
8225 // re-parsing the subquery's canonical text, and a dropped
8226 // argument list turned `pg_options_to_table(x)` into a
8227 // relation lookup that does not exist.
8228 if let Some(call) = &self.table_fn_call {
8229 let (fn_name, args) = call.as_ref();
8230 write!(f, "{fn_name}(")?;
8231 for (i, a) in args.iter().enumerate() {
8232 if i > 0 {
8233 f.write_str(", ")?;
8234 }
8235 write!(f, "{a}")?;
8236 }
8237 f.write_str(")")?;
8238 if let Some(a) = &self.alias {
8239 write!(f, " AS {}", quote_ident(a))?;
8240 if !self.unnest_column_aliases.is_empty() {
8241 f.write_str("(")?;
8242 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8243 if i > 0 {
8244 f.write_str(", ")?;
8245 }
8246 write!(f, "{}", quote_ident(c))?;
8247 }
8248 f.write_str(")")?;
8249 }
8250 }
8251 return Ok(());
8252 }
8253 if let Some(args) = &self.generate_series_args {
8254 f.write_str("generate_series(")?;
8255 for (i, a) in args.iter().enumerate() {
8256 if i > 0 {
8257 f.write_str(", ")?;
8258 }
8259 write!(f, "{a}")?;
8260 }
8261 f.write_str(")")?;
8262 if let Some(a) = &self.alias {
8263 write!(f, " AS {}", quote_ident(a))?;
8264 }
8265 return Ok(());
8266 }
8267 write!(f, "{}", quote_ident(&self.name))?;
8268 if let Some(seg) = self.as_of_segment {
8269 write!(f, " AS OF SEGMENT {seg}")?;
8270 }
8271 if let Some(a) = &self.alias {
8272 write!(f, " AS {}", quote_ident(a))?;
8273 }
8274 Ok(())
8275 }
8276}
8277
8278impl fmt::Display for ColumnName {
8279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8280 if let Some(q) = &self.qualifier {
8281 write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
8282 } else {
8283 write!(f, "{}", quote_ident(&self.name))
8284 }
8285 }
8286}
8287
8288/// v7.39 (round 311) — render the left spine of an AND / OR chain
8289/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
8290/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
8291/// SAME operator flattens; anything else is an ordinary operand.
8292fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
8293 if let Expr::Binary {
8294 lhs,
8295 op: inner,
8296 rhs,
8297 } = e
8298 && *inner == op
8299 {
8300 write_bool_chain(f, lhs, op)?;
8301 return write!(f, " {op} {rhs}");
8302 }
8303 write!(f, "{e}")
8304}
8305
8306/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
8307/// form `pg_get_constraintdef(oid, true)` and friends return.
8308///
8309/// The default [`fmt::Display`] parenthesises every operator node, which
8310/// is what PG's non-pretty deparse does and what makes the text
8311/// round-trip. Pretty drops the pairs the grammar can put back, and the
8312/// rule is NOT plain precedence minimisation — measured against PG 18.4
8313/// across 37 shapes:
8314///
8315/// * the boolean layer follows precedence (NOT > AND > OR): an OR
8316/// under an AND keeps its parens, an AND under an OR does not, and a
8317/// comparison under any of them does not (`NOT a > 1`);
8318/// * an associative chain flattens completely, even where the source
8319/// nested it to the right (`a AND (b AND c)` prints as one chain);
8320/// * but an operand of a comparison or arithmetic operator keeps its
8321/// parens whenever it is itself an operator expression — so
8322/// `(a + b) > 10` and `(- a) + b`, even though precedence alone
8323/// would not require either. A cast, function call, column or
8324/// literal in that position does not (`a::text = t`,
8325/// `length(code) > 2`); a cast counts as compound exactly when the
8326/// thing it casts is (`((a + b)::text) = t`).
8327///
8328/// Anything outside that layer defers to `Display`, which is never
8329/// wrong — only more parenthesised than PG would print.
8330#[must_use]
8331pub fn pretty_expr(e: &Expr) -> String {
8332 let mut out = String::new();
8333 write_pretty(&mut out, e, PrettyParent::None, false, false);
8334 out
8335}
8336
8337/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
8338/// writes it.
8339///
8340/// MariaDB names the offending expression in its out-of-range message
8341/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
8342/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
8343/// MySQL client, for a cast the client had just written the other way.
8344#[must_use]
8345pub fn pretty_expr_mysql(e: &Expr) -> String {
8346 let mut out = String::new();
8347 write_pretty(&mut out, e, PrettyParent::None, false, true);
8348 out
8349}
8350
8351/// v7.39 (round 505) — how strongly an expression suggests its own column
8352/// name. A cast keeps its argument's name only when that name is STRONG;
8353/// otherwise the cast reports the type it casts to.
8354///
8355/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
8356/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
8357/// itself `text` — so `case` and a function name cannot be the same kind of
8358/// answer, even though a bare `CASE …` does report `case`.
8359#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8360enum NameStrength {
8361 /// Nothing to go on — PG reports `?column?`.
8362 None,
8363 /// A name, but one a cast overrides: `case`, or a type name.
8364 Weak,
8365 /// A name a cast keeps: a column, or the function that produced it.
8366 Strong,
8367}
8368
8369/// v7.39 (round 505) — the column name PG18 gives a projected expression
8370/// that carries no `AS` alias. `None` means `?column?`.
8371///
8372/// SPG used to print the parsed expression back out, which matched neither
8373/// oracle and made name-keyed row access miss on both wires:
8374///
8375/// | query | PG18 | SPG (before) |
8376/// |--------------|------------|--------------|
8377/// | `upper(s)` | `upper` | `upper(s)` |
8378/// | `a+b` | `?column?` | `(a + b)` |
8379/// | `'lit'` | `?column?` | `'lit'` |
8380/// | `CASE …` | `case` | `CASE WHEN (a = 1) THEN …` |
8381///
8382/// Every rule below is one of those measurements, taken with `\gdesc`
8383/// against PG18: a call is named for its function, a cast recurses into its
8384/// argument and falls back to the type, a scalar subquery takes the name of
8385/// the column it selects, and operators have no name at all.
8386#[must_use]
8387pub fn figure_column_name(expr: &Expr) -> Option<String> {
8388 let (name, _) = figure_name_inner(expr);
8389 name
8390}
8391
8392/// The name a function reports, which is not always the name SPG parsed it
8393/// under: `count(*)` is held as `count_star` so the star arity survives the
8394/// AST, and that internal spelling must not reach a client. PG18 reports
8395/// `count`.
8396fn canonical_function_name(name: &str) -> String {
8397 match name {
8398 "count_star" => "count".to_string(),
8399 other => other.to_ascii_lowercase(),
8400 }
8401}
8402
8403/// v7.38.7 — a cast target's `pg_type.typname`, for the name a cast
8404/// reports when its operand has none of its own. Only the spellings that
8405/// differ from what the user writes need an entry; everything else is
8406/// already its own typname.
8407fn cast_target_typname(target: &CastTarget) -> String {
8408 let written = target.to_string().to_ascii_lowercase();
8409 let base = written.strip_suffix("[]").unwrap_or(&written);
8410 let mapped = match base {
8411 "bigint" => "int8",
8412 "integer" | "int" => "int4",
8413 "smallint" => "int2",
8414 "boolean" => "bool",
8415 "double precision" => "float8",
8416 "real" => "float4",
8417 "character varying" => "varchar",
8418 "character" => "bpchar",
8419 "timestamp with time zone" => "timestamptz",
8420 "timestamp without time zone" => "timestamp",
8421 "time without time zone" => "time",
8422 "decimal" => "numeric",
8423 other => other,
8424 };
8425 if written.ends_with("[]") {
8426 alloc::format!("_{mapped}")
8427 } else {
8428 String::from(mapped)
8429 }
8430}
8431
8432fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
8433 let strong = |n: String| (Some(n), NameStrength::Strong);
8434 match expr {
8435 // A column keeps its own name, qualifier and all discarded:
8436 // `lbl.a` reports `a`.
8437 Expr::Column(c) => strong(c.name.clone()),
8438 // Calls are named for the function. This covers the shapes that
8439 // only LOOK like syntax — `EXTRACT(year FROM …)` reports
8440 // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
8441 // because PG resolves them to functions before naming them.
8442 Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
8443 strong(canonical_function_name(name))
8444 }
8445 Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
8446 Expr::Extract { .. } => strong("extract".to_string()),
8447 Expr::Exists { .. } => strong("exists".to_string()),
8448 Expr::Array(_) => strong("array".to_string()),
8449 // `(expr).field` is named for the field, as a column would be.
8450 Expr::FieldAccess { field, .. } => strong(field.clone()),
8451 // A cast prefers its argument's name and settles for the type:
8452 // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
8453 Expr::Cast {
8454 expr: inner,
8455 target,
8456 } => match figure_name_inner(inner) {
8457 (Some(n), NameStrength::Strong) => strong(n),
8458 // v7.38.7 — the fallback is the target type's INTERNAL name,
8459 // which is what PG reports: `SELECT 7::bigint` is `int8`, not
8460 // the `bigint` the user typed. Measured on PG18 alongside
8461 // `CAST(7 AS bigint)`, which answers `int8` too.
8462 _ => (Some(cast_target_typname(target)), NameStrength::Weak),
8463 },
8464 // A scalar subquery reports whatever its single output column
8465 // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
8466 Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
8467 // `CASE …` names itself, but weakly — a cast around it wins.
8468 Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
8469 // A literal that carries its own type names itself for that type:
8470 // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
8471 // reports nothing. Weak, like any other type name.
8472 Expr::Literal(Literal::Interval { .. }) => {
8473 (Some("interval".to_string()), NameStrength::Weak)
8474 }
8475 // A wrapper that adds no name of its own.
8476 Expr::Variadic(inner) => figure_name_inner(inner),
8477 Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
8478 // Everything else — operators, comparisons, IS NULL, LIKE, IN,
8479 // literals, placeholders — reports `?column?`.
8480 _ => (None, NameStrength::None),
8481 }
8482}
8483
8484/// The name a scalar subquery's single projected column reports.
8485fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
8486 match sel.items.as_slice() {
8487 [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
8488 [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
8489 _ => (None, NameStrength::None),
8490 }
8491}
8492
8493/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
8494fn pretty_prec(e: &Expr) -> u8 {
8495 match e {
8496 Expr::Binary { op, .. } => match op {
8497 // v7.39 (round 407) — this deparse ladder mirrors the parser's:
8498 // OR < XOR < AND < NOT < comparison < additive < multiplicative.
8499 // XOR (MySQL-only) sits between OR and AND, so AND and everything
8500 // above shifted +1 to open rung 2 for it.
8501 BinOp::Or => 1,
8502 BinOp::LogicalXor => 2,
8503 BinOp::And => 3,
8504 BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
8505 BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
8506 // Everything else in this enum is a comparison-shaped
8507 // operator; they share one level, as in the grammar.
8508 _ => 5,
8509 },
8510 Expr::Unary { op, .. } => match op {
8511 UnOp::Not => 4,
8512 UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
8513 },
8514 _ => u8::MAX,
8515 }
8516}
8517
8518/// Is this node an operator expression — the thing an arithmetic or
8519/// comparison parent keeps parentheses around? A cast inherits the
8520/// answer from what it casts.
8521fn pretty_is_compound(e: &Expr) -> bool {
8522 match e {
8523 Expr::Binary { .. } | Expr::Unary { .. } => true,
8524 Expr::Cast { expr, .. } => pretty_is_compound(expr),
8525 _ => false,
8526 }
8527}
8528
8529/// `parent` describes the enclosing operator: its binding power, and
8530/// whether it is a comparison (which keeps parens around any operator
8531/// operand) or a NOT (which keeps them at equal power too).
8532#[derive(Clone, Copy, PartialEq)]
8533enum PrettyParent {
8534 /// Nothing encloses this node.
8535 None,
8536 /// A comparison-shaped operator: an operator operand always keeps
8537 /// its parens, whatever precedence would allow.
8538 Comparison,
8539 /// Arithmetic / concatenation: precedence decides.
8540 Arith(u8),
8541 /// A boolean connective: precedence decides.
8542 Bool(u8),
8543 /// `NOT`: precedence decides, but equal power still needs parens so
8544 /// `NOT (NOT a > 1)` does not collapse.
8545 Not,
8546}
8547
8548fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8549 let prec = pretty_prec(e);
8550 let is_unary_sign = matches!(
8551 e,
8552 Expr::Unary {
8553 op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8554 ..
8555 }
8556 );
8557 let needs = match parent {
8558 PrettyParent::None => false,
8559 PrettyParent::Comparison => pretty_is_compound(e),
8560 // A sign always keeps its parens under an operator — PG writes
8561 // `(- a) + b` even though precedence would not require it.
8562 PrettyParent::Arith(p) => {
8563 is_unary_sign
8564 || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8565 && (prec < p || (prec == p && is_rhs)))
8566 }
8567 PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8568 PrettyParent::Not => {
8569 matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8570 }
8571 };
8572 if needs {
8573 out.push('(');
8574 }
8575 match e {
8576 Expr::Binary { lhs, op, rhs } => {
8577 let child = match op {
8578 BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8579 BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8580 PrettyParent::Arith(prec)
8581 }
8582 _ => PrettyParent::Comparison,
8583 };
8584 write_pretty(out, lhs, child, false, mysql);
8585 out.push(' ');
8586 out.push_str(&alloc::format!("{op}"));
8587 out.push(' ');
8588 // AND / OR are associative, so an explicitly right-nested
8589 // chain still prints as one chain.
8590 let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8591 write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8592 }
8593 Expr::Unary { op, expr } => match op {
8594 UnOp::Not => {
8595 out.push_str("NOT ");
8596 write_pretty(out, expr, PrettyParent::Not, false, mysql);
8597 }
8598 UnOp::Neg => {
8599 out.push_str("- ");
8600 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8601 }
8602 UnOp::Plus => {
8603 out.push_str("+ ");
8604 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8605 }
8606 UnOp::BitNot => {
8607 out.push('~');
8608 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8609 }
8610 },
8611 Expr::Cast { expr, target } => {
8612 if mysql {
8613 // MySQL's own spelling, which is what its error messages
8614 // quote back.
8615 out.push_str("cast(");
8616 write_pretty(out, expr, PrettyParent::None, false, mysql);
8617 out.push_str(&alloc::format!(
8618 " as {})",
8619 target.to_string().to_lowercase()
8620 ));
8621 } else {
8622 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8623 out.push_str(&alloc::format!("::{target}"));
8624 }
8625 }
8626 Expr::IsNull { expr, negated } => {
8627 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8628 out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8629 }
8630 other => out.push_str(&alloc::format!("{other}")),
8631 }
8632 if needs {
8633 out.push(')');
8634 }
8635}
8636
8637const fn pretty_prec_not() -> u8 {
8638 // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8639 // when the XOR insertion shifted the deparse ladder up by one).
8640 4
8641}
8642
8643impl fmt::Display for Expr {
8644 #[allow(clippy::too_many_lines)]
8645 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8646 match self {
8647 Self::Literal(l) => write!(f, "{l}"),
8648 Self::Column(c) => write!(f, "{c}"),
8649 Self::Placeholder(n) => write!(f, "${n}"),
8650 // Round-trips as the spelling PG's docs lead with.
8651 Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8652 Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8653 // Round-trips with the name quoted, which is how PG spells a
8654 // collation everywhere: `"en_US.utf8"`, `"C"`.
8655 Self::Collate { expr, collation } => {
8656 write!(f, "{expr} COLLATE {}", quote_ident(collation))
8657 }
8658 // v7.39 (round 311) — an AND / OR chain that nests to the
8659 // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8660 // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8661 // its parentheses, because that is a different grouping as
8662 // written. Both halves measured against PG 18.4's deparse,
8663 // which flattens a same-operator left chain at parse time and
8664 // leaves `a AND (b AND c)` alone.
8665 Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8666 f.write_str("(")?;
8667 write_bool_chain(f, lhs, *op)?;
8668 write!(f, " {op} {rhs}")?;
8669 f.write_str(")")
8670 }
8671 Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8672 Self::Unary { op, expr } => match op {
8673 UnOp::Not => write!(f, "(NOT {expr})"),
8674 // A space after the sign, as PG's deparse writes it.
8675 UnOp::Neg => write!(f, "(- {expr})"),
8676 UnOp::Plus => write!(f, "(+ {expr})"),
8677 UnOp::BitNot => write!(f, "(~{expr})"),
8678 },
8679 // The OPERAND carries the parentheses, not the cast:
8680 // `(a)::text`, `((a + b))::text`. PG words it this way, and
8681 // it is what keeps `a::text = t` from reading as a cast of
8682 // the comparison.
8683 Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8684 Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8685 Self::AggregateOrdered {
8686 call,
8687 order_by,
8688 distinct,
8689 filter,
8690 } => {
8691 let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8692 for (i, o) in order_by.iter().enumerate() {
8693 if i > 0 {
8694 f.write_str(", ")?;
8695 }
8696 write!(f, "{}", o.expr)?;
8697 if o.desc {
8698 f.write_str(" DESC")?;
8699 }
8700 match o.nulls_first {
8701 Some(true) => f.write_str(" NULLS FIRST")?,
8702 Some(false) => f.write_str(" NULLS LAST")?,
8703 None => {}
8704 }
8705 }
8706 Ok(())
8707 };
8708 // Ordered-set aggregates (`percentile_cont(f) WITHIN
8709 // GROUP (ORDER BY x)`) render the in-parens args as the
8710 // direct argument and the sort spec under WITHIN GROUP —
8711 // not as an in-argument ORDER BY.
8712 let ordered_set = matches!(
8713 call.as_ref(),
8714 Expr::FunctionCall { name, .. }
8715 if matches!(
8716 name.to_ascii_lowercase().as_str(),
8717 "percentile_cont" | "percentile_disc" | "mode"
8718 )
8719 );
8720 if ordered_set {
8721 write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8722 fmt_order_by(f)?;
8723 f.write_str(")")?;
8724 } else {
8725 // `name([DISTINCT ]args [ORDER BY …])` — peel the
8726 // inner call's parens to splice modifiers.
8727 let inner = alloc::format!("{call}");
8728 let body = inner.strip_suffix(')').unwrap_or(&inner);
8729 let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8730 write!(f, "{head}(")?;
8731 if *distinct {
8732 f.write_str("DISTINCT ")?;
8733 }
8734 write!(f, "{args_part}")?;
8735 if !order_by.is_empty() {
8736 f.write_str(" ORDER BY ")?;
8737 fmt_order_by(f)?;
8738 }
8739 f.write_str(")")?;
8740 }
8741 if let Some(cond) = filter {
8742 write!(f, " FILTER (WHERE {cond})")?;
8743 }
8744 Ok(())
8745 }
8746 Self::IsNull { expr, negated } => {
8747 if *negated {
8748 write!(f, "({expr} IS NOT NULL)")
8749 } else {
8750 write!(f, "({expr} IS NULL)")
8751 }
8752 }
8753 Self::BoolTest {
8754 expr,
8755 value,
8756 negated,
8757 } => {
8758 let word = match value {
8759 Some(true) => "TRUE",
8760 Some(false) => "FALSE",
8761 None => "UNKNOWN",
8762 };
8763 if *negated {
8764 write!(f, "({expr} IS NOT {word})")
8765 } else {
8766 write!(f, "({expr} IS {word})")
8767 }
8768 }
8769 Self::FunctionCall { name, args } => {
8770 write!(f, "{name}(")?;
8771 for (i, a) in args.iter().enumerate() {
8772 if i > 0 {
8773 f.write_str(", ")?;
8774 }
8775 write!(f, "{a}")?;
8776 }
8777 f.write_str(")")
8778 }
8779 Self::Like {
8780 expr,
8781 pattern,
8782 negated,
8783 case_insensitive,
8784 } => {
8785 let op = match (negated, case_insensitive) {
8786 (false, false) => "LIKE",
8787 (true, false) => "NOT LIKE",
8788 (false, true) => "ILIKE",
8789 (true, true) => "NOT ILIKE",
8790 };
8791 write!(f, "({expr} {op} {pattern})")
8792 }
8793 Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8794 Self::WindowFunction {
8795 name,
8796 args,
8797 partition_by,
8798 order_by,
8799 frame,
8800 null_treatment,
8801 filter,
8802 } => {
8803 write!(f, "{name}(")?;
8804 for (i, a) in args.iter().enumerate() {
8805 if i > 0 {
8806 f.write_str(", ")?;
8807 }
8808 write!(f, "{a}")?;
8809 }
8810 f.write_str(")")?;
8811 // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8812 // OVER; it round-trips so a window body's Display re-parses.
8813 if let Some(cond) = filter {
8814 write!(f, " FILTER (WHERE {cond})")?;
8815 }
8816 // v7.30.1 (mailrs round-24 class audit) — IGNORE
8817 // NULLS sits between the arg list and OVER; dropping
8818 // it reverted replayed queries to RESPECT NULLS.
8819 if matches!(null_treatment, NullTreatment::Ignore) {
8820 f.write_str(" IGNORE NULLS")?;
8821 }
8822 f.write_str(" OVER (")?;
8823 if !partition_by.is_empty() {
8824 f.write_str("PARTITION BY ")?;
8825 for (i, p) in partition_by.iter().enumerate() {
8826 if i > 0 {
8827 f.write_str(", ")?;
8828 }
8829 write!(f, "{p}")?;
8830 }
8831 }
8832 if !order_by.is_empty() {
8833 if !partition_by.is_empty() {
8834 f.write_str(" ")?;
8835 }
8836 f.write_str("ORDER BY ")?;
8837 for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8838 if i > 0 {
8839 f.write_str(", ")?;
8840 }
8841 write!(f, "{e}")?;
8842 if *desc {
8843 f.write_str(" DESC")?;
8844 }
8845 match nulls_first {
8846 Some(true) => f.write_str(" NULLS FIRST")?,
8847 Some(false) => f.write_str(" NULLS LAST")?,
8848 None => {}
8849 }
8850 }
8851 }
8852 if let Some(fr) = frame {
8853 if !partition_by.is_empty() || !order_by.is_empty() {
8854 f.write_str(" ")?;
8855 }
8856 let k = match fr.kind {
8857 FrameKind::Rows => "ROWS",
8858 FrameKind::Range => "RANGE",
8859 FrameKind::Groups => "GROUPS",
8860 };
8861 if let Some(end) = &fr.end {
8862 write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8863 } else {
8864 write!(f, "{k} {}", fr.start)?;
8865 }
8866 }
8867 f.write_str(")")
8868 }
8869 Self::ScalarSubquery(s) => write!(f, "({s})"),
8870 Self::Exists { subquery, negated } => {
8871 if *negated {
8872 write!(f, "NOT EXISTS ({subquery})")
8873 } else {
8874 write!(f, "EXISTS ({subquery})")
8875 }
8876 }
8877 Self::InSubquery {
8878 expr,
8879 subquery,
8880 negated,
8881 } => {
8882 if *negated {
8883 write!(f, "({expr} NOT IN ({subquery}))")
8884 } else {
8885 write!(f, "({expr} IN ({subquery}))")
8886 }
8887 }
8888 Self::RowInSubquery {
8889 row,
8890 subquery,
8891 negated,
8892 } => {
8893 write!(f, "(")?;
8894 for (i, e) in row.iter().enumerate() {
8895 if i > 0 {
8896 write!(f, ", ")?;
8897 }
8898 write!(f, "{e}")?;
8899 }
8900 let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8901 write!(f, "{kw}{subquery})")
8902 }
8903 Self::RowCmpSubquery { row, op, subquery } => {
8904 write!(f, "(")?;
8905 for (i, e) in row.iter().enumerate() {
8906 if i > 0 {
8907 write!(f, ", ")?;
8908 }
8909 write!(f, "{e}")?;
8910 }
8911 write!(f, ") {op} ({subquery})")
8912 }
8913 Self::InList {
8914 expr,
8915 list,
8916 negated,
8917 } => {
8918 let kw = if *negated { " NOT IN (" } else { " IN (" };
8919 write!(f, "({expr}{kw}")?;
8920 for (i, e) in list.iter().enumerate() {
8921 if i > 0 {
8922 f.write_str(", ")?;
8923 }
8924 write!(f, "{e}")?;
8925 }
8926 f.write_str("))")
8927 }
8928 Self::Array(items) => {
8929 f.write_str("ARRAY[")?;
8930 for (i, e) in items.iter().enumerate() {
8931 if i > 0 {
8932 f.write_str(", ")?;
8933 }
8934 write!(f, "{e}")?;
8935 }
8936 f.write_str("]")
8937 }
8938 Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
8939 Self::ArraySlice { target, lo, hi } => {
8940 write!(f, "({target}[")?;
8941 if let Some(l) = lo {
8942 write!(f, "{l}")?;
8943 }
8944 write!(f, ":")?;
8945 if let Some(h) = hi {
8946 write!(f, "{h}")?;
8947 }
8948 write!(f, "])")
8949 }
8950 Self::AnyAll {
8951 expr,
8952 op,
8953 array,
8954 is_any,
8955 } => {
8956 let kw = if *is_any { "ANY" } else { "ALL" };
8957 write!(f, "({expr} {op} {kw}({array}))")
8958 }
8959 Self::Case {
8960 operand,
8961 branches,
8962 else_branch,
8963 } => {
8964 f.write_str("CASE")?;
8965 if let Some(op) = operand {
8966 write!(f, " {op}")?;
8967 }
8968 for (w, t) in branches {
8969 write!(f, " WHEN {w} THEN {t}")?;
8970 }
8971 if let Some(e) = else_branch {
8972 write!(f, " ELSE {e}")?;
8973 }
8974 f.write_str(" END")
8975 }
8976 }
8977 }
8978}
8979
8980/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
8981/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
8982pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
8983 use alloc::string::ToString;
8984 if scale == 0 {
8985 return alloc::format!("{unscaled}");
8986 }
8987 let neg = unscaled < 0;
8988 let digits = alloc::format!("{}", unscaled.unsigned_abs());
8989 let scale = scale as usize;
8990 let (int_part, frac_part) = if digits.len() > scale {
8991 (
8992 digits[..digits.len() - scale].to_string(),
8993 digits[digits.len() - scale..].to_string(),
8994 )
8995 } else {
8996 ("0".to_string(), alloc::format!("{digits:0>scale$}"))
8997 };
8998 alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
8999}
9000
9001/// A single-quoted SQL string, with an embedded quote doubled.
9002fn write_quoted(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
9003 f.write_str("'")?;
9004 for c in s.chars() {
9005 if c == '\'' {
9006 f.write_str("''")?;
9007 } else {
9008 write!(f, "{c}")?;
9009 }
9010 }
9011 f.write_str("'")
9012}
9013
9014impl fmt::Display for Literal {
9015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9016 match self {
9017 Self::Integer(n) => write!(f, "{n}"),
9018 Self::Float(x) => {
9019 let s = format!("{x}");
9020 // Default Display for an integral f64 (e.g. 1.0) emits "1",
9021 // which would round-trip back to Integer. Force a dot.
9022 if s.contains('.') || s.contains('e') || s.contains('E') {
9023 f.write_str(&s)
9024 } else {
9025 write!(f, "{s}.0")
9026 }
9027 }
9028 Self::Numeric { unscaled, scale } => {
9029 // Render the exact decimal `unscaled / 10^scale`, preserving
9030 // scale (trailing zeros) — round-trips to the same literal.
9031 f.write_str(&render_exact_decimal(*unscaled, *scale))
9032 }
9033 Self::NumericBig(s) => f.write_str(s),
9034 // Printed exactly as the text form was, so a reader cannot
9035 // tell whether the constant was decoded or not.
9036 Self::Timestamp { text, .. } | Self::Date { text, .. } => write_quoted(f, text),
9037 Self::String(s) => write_quoted(f, s),
9038 Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
9039 Self::Null => f.write_str("NULL"),
9040 // PG external array form. Display round-trip re-enters
9041 // through the column-typed text coerce, same as pgwire.
9042 Self::TextArray(items) => {
9043 f.write_str("'{")?;
9044 for (i, it) in items.iter().enumerate() {
9045 if i > 0 {
9046 f.write_str(",")?;
9047 }
9048 match it {
9049 None => f.write_str("NULL")?,
9050 Some(s) => {
9051 f.write_str("\"")?;
9052 for c in s.chars() {
9053 match c {
9054 // array-element escapes
9055 '"' | '\\' => write!(f, "\\{c}")?,
9056 // the OUTER wrapper is a SQL string
9057 // literal — embedded quotes must
9058 // double, or the rendered form
9059 // (WAL replay parses it back) is
9060 // invalid SQL
9061 '\'' => f.write_str("''")?,
9062 _ => write!(f, "{c}")?,
9063 }
9064 }
9065 f.write_str("\"")?;
9066 }
9067 }
9068 }
9069 f.write_str("}'")
9070 }
9071 Self::IntArray(items) => {
9072 f.write_str("'{")?;
9073 for (i, it) in items.iter().enumerate() {
9074 if i > 0 {
9075 f.write_str(",")?;
9076 }
9077 match it {
9078 None => f.write_str("NULL")?,
9079 Some(n) => write!(f, "{n}")?,
9080 }
9081 }
9082 f.write_str("}'")
9083 }
9084 Self::BigIntArray(items) => {
9085 f.write_str("'{")?;
9086 for (i, it) in items.iter().enumerate() {
9087 if i > 0 {
9088 f.write_str(",")?;
9089 }
9090 match it {
9091 None => f.write_str("NULL")?,
9092 Some(n) => write!(f, "{n}")?,
9093 }
9094 }
9095 f.write_str("}'")
9096 }
9097 Self::Vector(v) => {
9098 f.write_str("[")?;
9099 for (i, x) in v.iter().enumerate() {
9100 if i > 0 {
9101 f.write_str(", ")?;
9102 }
9103 let s = format!("{x}");
9104 // Mirror Float Display: force a dot so re-parse stays
9105 // numerically literal.
9106 if s.contains('.') || s.contains('e') || s.contains('E') {
9107 f.write_str(&s)?;
9108 } else {
9109 write!(f, "{s}.0")?;
9110 }
9111 }
9112 f.write_str("]")
9113 }
9114 Self::Interval { text, .. } => {
9115 f.write_str("INTERVAL '")?;
9116 for c in text.chars() {
9117 if c == '\'' {
9118 f.write_str("''")?;
9119 } else {
9120 write!(f, "{c}")?;
9121 }
9122 }
9123 f.write_str("'")
9124 }
9125 }
9126 }
9127}
9128
9129impl fmt::Display for BinOp {
9130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9131 f.write_str(match self {
9132 Self::Or => "OR",
9133 Self::And => "AND",
9134 Self::Eq => "=",
9135 Self::NotEq => "<>",
9136 Self::IsDistinctFrom => "IS DISTINCT FROM",
9137 Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
9138 Self::IntDiv => "DIV",
9139 Self::Lt => "<",
9140 Self::LtEq => "<=",
9141 Self::Gt => ">",
9142 Self::GtEq => ">=",
9143 Self::Add => "+",
9144 Self::Sub => "-",
9145 Self::Mul => "*",
9146 Self::Div => "/",
9147 Self::Mod => "%",
9148 Self::L2Distance => "<->",
9149 Self::GeomParallel => "?||",
9150 Self::OverLeft => "&<",
9151 Self::OverRight => "&>",
9152 Self::GeomPerp => "?-|",
9153 Self::GeomSameAs => "~=",
9154 Self::ClosestPoint => "##",
9155 Self::GeomHoriz => "?-",
9156 Self::InnerProduct => "<#>",
9157 Self::CosineDistance => "<=>",
9158 Self::Concat => "||",
9159 Self::BitOr => "|",
9160 Self::BitAnd => "&",
9161 Self::BitXor => "#",
9162 Self::LogicalXor => "xor",
9163 Self::JsonGet => "->",
9164 Self::JsonGetText => "->>",
9165 Self::JsonGetPath => "#>",
9166 Self::JsonGetPathText => "#>>",
9167 Self::JsonContains => "@>",
9168 Self::JsonPathExists => "@?",
9169 Self::JsonContainedBy => "<@",
9170 Self::JsonKeyExists => "?",
9171 Self::JsonKeysAny => "?|",
9172 Self::JsonKeysAll => "?&",
9173 Self::JsonDeletePath => "#-",
9174 Self::TsMatch => "@@",
9175 Self::InetContainedBy => "<<",
9176 Self::InetContainedByEq => "<<=",
9177 Self::InetContains => ">>",
9178 Self::InetContainsEq => ">>=",
9179 Self::InetOverlap => "&&",
9180 Self::Intersects => "?#",
9181 Self::IsBelow => "<^",
9182 Self::IsAbove => ">^",
9183 Self::PatternLt => "~<~",
9184 Self::PatternLtEq => "~<=~",
9185 Self::PatternGt => "~>~",
9186 Self::PatternGtEq => "~>=~",
9187 })
9188 }
9189}
9190
9191/// Quote `s` as a PG double-quoted identifier when required (keyword,
9192/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
9193/// Otherwise return it as-is. Returns an owned `String` to keep the call site
9194/// uniform.
9195pub(crate) fn quote_ident(s: &str) -> String {
9196 let needs_quote = match s.chars().next() {
9197 None => true,
9198 Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
9199 _ => {
9200 s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
9201 || s.chars().any(|c| c.is_ascii_uppercase())
9202 || is_keyword(s)
9203 }
9204 };
9205 if !needs_quote {
9206 return s.to_string();
9207 }
9208 let mut out = String::with_capacity(s.len() + 2);
9209 out.push('"');
9210 for c in s.chars() {
9211 if c == '"' {
9212 out.push_str("\"\"");
9213 } else {
9214 out.push(c);
9215 }
9216 }
9217 out.push('"');
9218 out
9219}
9220
9221fn is_keyword(s: &str) -> bool {
9222 matches!(
9223 &*s.to_ascii_lowercase(),
9224 "select"
9225 | "from"
9226 | "where"
9227 | "as"
9228 | "null"
9229 | "true"
9230 | "false"
9231 | "and"
9232 | "or"
9233 | "not"
9234 | "create"
9235 | "table"
9236 | "insert"
9237 | "into"
9238 | "values"
9239 | "index"
9240 | "on"
9241 | "begin"
9242 | "commit"
9243 | "rollback"
9244 | "is"
9245 | "between"
9246 | "in"
9247 | "like"
9248 | "group"
9249 | "distinct"
9250 | "union"
9251 | "all"
9252 | "join"
9253 | "inner"
9254 | "left"
9255 | "cross"
9256 | "outer"
9257 | "default"
9258 | "savepoint"
9259 | "release"
9260 | "to"
9261 | "having"
9262 | "show"
9263 | "extract"
9264 | "offset"
9265 | "asc"
9266 | "desc"
9267 | "interval"
9268 )
9269}
9270
9271#[cfg(test)]
9272mod tests {
9273 use super::*;
9274 use alloc::vec;
9275
9276 #[test]
9277 fn integer_literal_renders_without_dot() {
9278 assert_eq!(Literal::Integer(42).to_string(), "42");
9279 }
9280
9281 #[test]
9282 fn integral_float_keeps_dot() {
9283 assert_eq!(Literal::Float(1.0).to_string(), "1.0");
9284 assert_eq!(Literal::Float(1.5).to_string(), "1.5");
9285 assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
9286 }
9287
9288 #[test]
9289 fn string_literal_doubles_quote() {
9290 assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
9291 }
9292
9293 #[test]
9294 fn bool_and_null_render_uppercase() {
9295 assert_eq!(Literal::Bool(true).to_string(), "TRUE");
9296 assert_eq!(Literal::Bool(false).to_string(), "FALSE");
9297 assert_eq!(Literal::Null.to_string(), "NULL");
9298 }
9299
9300 #[test]
9301 fn binary_op_always_parenthesised() {
9302 let e = Expr::Binary {
9303 lhs: Box::new(Expr::Literal(Literal::Integer(1))),
9304 op: BinOp::Add,
9305 rhs: Box::new(Expr::Literal(Literal::Integer(2))),
9306 };
9307 assert_eq!(e.to_string(), "(1 + 2)");
9308 }
9309
9310 #[test]
9311 fn select_star_from_table() {
9312 let s = SelectStatement {
9313 locking: None,
9314 items: vec![SelectItem::Wildcard],
9315 from: Some(FromClause {
9316 primary: TableRef {
9317 name: "users".into(),
9318 alias: None,
9319 only: false,
9320 as_of_segment: None,
9321 unnest_expr: None,
9322 unnest_column_aliases: Vec::new(),
9323 with_ordinality: false,
9324 generate_series_args: None,
9325 lateral_subquery: None,
9326 jsonb_each_text_arg: None,
9327 table_fn_call: None,
9328 rows_from: None,
9329 json_table: None,
9330 scalar_fn_item: false,
9331 },
9332 joins: vec![],
9333 }),
9334 where_: None,
9335 group_by: None,
9336 group_by_all: false,
9337 having: None,
9338 unions: vec![],
9339 order_by: Vec::new(),
9340 limit: None,
9341 offset: None,
9342 limit_with_ties: false,
9343 window_check_exprs: Vec::new(),
9344 distinct: false,
9345 distinct_on: Vec::new(),
9346 ctes: vec![],
9347 };
9348 assert_eq!(s.to_string(), "SELECT * FROM users");
9349 }
9350
9351 #[test]
9352 fn quote_ident_for_uppercase_and_keyword() {
9353 assert_eq!(quote_ident("foo"), "foo");
9354 assert_eq!(quote_ident("Foo"), "\"Foo\"");
9355 assert_eq!(quote_ident("select"), "\"select\"");
9356 assert_eq!(quote_ident(""), "\"\"");
9357 assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
9358 }
9359}