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.39.11 — each extra column's `ASC` / `DESC` / `NULLS FIRST`
2401 /// / `NULLS LAST`, positionally aligned with `extra_columns`. The
2402 /// parser used to discard these, so a composite index's direction
2403 /// survived only on the leading column and `pg_get_indexdef`
2404 /// rendered `(a, b DESC)` back as `(a, b)`.
2405 pub extra_orders: Vec<IndexColumnOrder>,
2406 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
2407 /// enforces uniqueness on the indexed key (combined with the
2408 /// `partial_predicate` filter — only rows where the predicate
2409 /// evaluates truthy enter the uniqueness check). Standard SQL
2410 /// and PG's canonical way to express conditional uniqueness.
2411 /// mailrs K1.
2412 pub is_unique: bool,
2413 /// v7.15.0 — operator class on the leading column, when the
2414 /// CREATE INDEX named one (`(col vector_cosine_ops)` shape).
2415 /// Lower-cased. Most opclasses are still informational; the
2416 /// engine routes on `gin_trgm_ops` specifically to build a
2417 /// trigram-shingle GIN over a TEXT column, and otherwise
2418 /// keeps the current "accepted and discarded" behaviour for
2419 /// pg_dump compatibility.
2420 pub opclass: Option<String>,
2421 /// r1038 — the access method as WRITTEN, lower-cased; `None` when
2422 /// there was no `USING` clause.
2423 ///
2424 /// `method` cannot answer this: `gist` / `spgist` / `hash` all become
2425 /// `IndexMethod::BTree` so PG schemas naming an AM SPG has no
2426 /// implementation for still load. That degradation is deliberate, but
2427 /// it loses the name — and the operator-class check needs it, both to
2428 /// look the class up under the AM the user actually named and to say
2429 /// which AM it was missing from, the way PG's message does.
2430 pub method_name: Option<String>,
2431}
2432
2433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2434pub enum IndexMethod {
2435 /// Default — B-tree over `IndexKey`. Used for equality / range
2436 /// lookups on scalar columns.
2437 BTree,
2438 /// `USING hnsw` — NSW graph for kNN over a vector column.
2439 Hnsw,
2440 /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
2441 /// metadata that records (min_key, max_key) for each page in a
2442 /// cold-tier segment, on the indexed column. The optimizer
2443 /// can use these summaries to skip pages whose range does NOT
2444 /// overlap a query's WHERE predicate. BRIN indexes carry no
2445 /// in-memory data — the summaries live in the segment v2
2446 /// envelope's sidecar. Created via the standard
2447 /// `CREATE INDEX … USING brin (col)` syntax.
2448 Brin,
2449 /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
2450 /// column. Posting lists map `lexeme word` → row locators; the
2451 /// planner uses them to narrow `WHERE col @@ tsquery` to the
2452 /// candidate rows whose vectors contain a matching term, then
2453 /// re-evaluates the full `@@` semantics on each candidate.
2454 /// Replaces the v7.9.26b `USING gin` → BTree fallback that
2455 /// silently degraded to a full scan at query time.
2456 Gin,
2457}
2458
2459/// v7.39 (round 531) — `LIKE <table> [ {INCLUDING|EXCLUDING} <opt> ]*`
2460/// inside a CREATE TABLE column list.
2461///
2462/// The source table's shape can only be read from the catalog, so the
2463/// parser records the clause and the engine expands it. `at` is how many
2464/// explicit columns preceded it: PG keeps the written order, so
2465/// `CREATE TABLE k (x int, LIKE t)` puts `x` first.
2466#[derive(Debug, Clone, PartialEq)]
2467pub struct LikeSpec {
2468 pub source: String,
2469 pub at: usize,
2470 pub options: LikeOptions,
2471 /// v7.40.0 — MySQL's `CREATE TABLE b LIKE a` keeps the source's
2472 /// index names (`PRIMARY`, `ks`); PostgreSQL's
2473 /// `CREATE TABLE b (LIKE a INCLUDING ALL)` renames the copies after
2474 /// the new table (`lb_pkey`, `lb_s_idx`). Both measured. The
2475 /// spelling says which engine's rule applies.
2476 pub keep_index_names: bool,
2477}
2478
2479/// Which properties `LIKE` carries over. A bare `LIKE` copies names,
2480/// types and NOT NULL and nothing else — measured on PG18, where a
2481/// copied generated column becomes a plain one and a copied identity
2482/// column loses its identity.
2483#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2484pub struct LikeOptions {
2485 pub defaults: bool,
2486 pub constraints: bool,
2487 pub identity: bool,
2488 pub generated: bool,
2489 pub indexes: bool,
2490 pub comments: bool,
2491}
2492
2493#[derive(Debug, Clone, PartialEq)]
2494pub struct CreateTableStatement {
2495 /// v7.39 (round 436) — `CREATE TEMPORARY TABLE`. The table lives in the
2496 /// creating session's own namespace: it shadows a permanent table of the
2497 /// same name, other sessions never see it, and it is dropped when the
2498 /// session ends. A `bool` here lands in the struct's existing padding.
2499 pub temporary: bool,
2500 pub name: String,
2501 /// v7.39 — the `ENGINE=` a MySQL dump names. Consumed and discarded
2502 /// before, so `ENGINE=NONSUCH` built a table where MySQL 9.7.2
2503 /// answers `ERROR 1286`, and `sql_mode` claimed
2504 /// `NO_ENGINE_SUBSTITUTION` while doing it.
2505 pub engine: Option<String>,
2506 /// v7.40.0 — the `AUTO_INCREMENT=N` table option: the next value
2507 /// the table hands out. It was consumed and dropped, so the first
2508 /// row of a table declared `AUTO_INCREMENT=100` got 1 where MySQL
2509 /// 9.7.2 gives it 100 — and `SHOW CREATE TABLE`, which reproduces
2510 /// the option from the counter, round-tripped a different number.
2511 pub auto_increment: Option<i64>,
2512 pub columns: Vec<ColumnDef>,
2513 /// v7.39 (round 531) — the `LIKE` clauses in the column list, in
2514 /// the order written. Empty for a table that has none.
2515 pub like_specs: Vec<LikeSpec>,
2516 /// v7.39 (round 645) — `CREATE TABLE c (…) INHERITS (p1, p2)`.
2517 /// Empty for a table that inherits from nothing. Order matters:
2518 /// the child takes each parent's columns in this order before its
2519 /// own, and a parent's position here is its `pg_inherits.inhseqno`.
2520 pub inherits: Vec<String>,
2521 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
2522 /// table name already exists, instead of raising `DuplicateTable`.
2523 pub if_not_exists: bool,
2524 /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
2525 /// constraints. Column-level `REFERENCES` (single-column inline
2526 /// form) is normalised into this vec at parse time so the engine
2527 /// sees one uniform list.
2528 pub foreign_keys: Vec<ForeignKeyConstraint>,
2529 /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
2530 /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
2531 /// Engine resolves each into a BTree index named after the
2532 /// constraint's leading column at CREATE TABLE time; INSERT
2533 /// path enforces composite uniqueness via row scan on the
2534 /// leading column index.
2535 pub table_constraints: Vec<TableConstraint>,
2536 /// v7.37.6-B(sentori Epic 2 P0)— `PARTITION BY <strategy>
2537 /// (key_col)` declarative partition-parent suffix. `Some` ⇒
2538 /// the engine creates a parent table whose own rows stay
2539 /// empty and routes INSERT/SELECT through children. Mutually
2540 /// exclusive with `partition_of` (parser enforces).
2541 pub partition_by: Option<PartitionBySpec>,
2542 /// v7.37.6-B — `PARTITION OF <parent> { FOR VALUES FROM (a)
2543 /// TO (b) | DEFAULT }` child-table declaration. `Some` ⇒
2544 /// the table inherits its column list from `parent` (the
2545 /// parser rejects an explicit column list when this is set);
2546 /// engine routes child rows back to the parent at INSERT.
2547 pub partition_of: Option<PartitionOfSpec>,
2548}
2549
2550/// v7.37.6-B — `PARTITION BY <kind> (key_columns…)` parent suffix.
2551/// v7.37.6-B only RANGE is recognised; the enum keeps space for
2552/// future LIST / HASH without breaking the public AST shape.
2553#[derive(Debug, Clone, PartialEq)]
2554pub struct PartitionBySpec {
2555 pub kind: PartitionKindAst,
2556 /// One or more ident references into the parent's column list.
2557 /// v7.37.6-B contracts a single TIMESTAMPTZ key; multi-key
2558 /// RANGE is a phase-2 extension. Parser allows ≥1 to keep the
2559 /// shape PG-compatible.
2560 pub key_columns: Vec<String>,
2561}
2562
2563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2564pub enum PartitionKindAst {
2565 Range,
2566 /// v7.37.16 (16.1) — `PARTITION BY LIST (key)`. Child uses
2567 /// `FOR VALUES IN (lit, lit, …)`.
2568 List,
2569 /// v7.37.16 (16.2) — `PARTITION BY HASH (key)`. Child uses
2570 /// `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2571 Hash,
2572}
2573
2574/// v7.37.6-B — `PARTITION OF <parent> <bounds>` child suffix.
2575/// Bounds is either a half-open range (`FOR VALUES FROM (a) TO (b)`)
2576/// or the catch-all `DEFAULT` partition.
2577#[derive(Debug, Clone, PartialEq)]
2578pub struct PartitionOfSpec {
2579 pub parent_name: String,
2580 pub bounds: PartitionOfBoundsAst,
2581}
2582
2583#[derive(Debug, Clone, PartialEq)]
2584pub enum PartitionOfBoundsAst {
2585 /// `FOR VALUES FROM (lower) TO (upper)`. `Expr` is ~144 bytes
2586 /// (lits include vector bodies), so we box both bounds to keep
2587 /// the variant size in line with `Default` for clippy and to
2588 /// minimise per-statement footprint when the partition shape
2589 /// isn't in use.
2590 Range {
2591 lower: Box<Expr>,
2592 upper: Box<Expr>,
2593 },
2594 /// v7.37.16 (16.1) — `FOR VALUES IN (lit [, lit, …])`. Each
2595 /// expr resolves to a typed literal at child-create time.
2596 List {
2597 values: Vec<Expr>,
2598 },
2599 /// v7.37.16 (16.2) — `FOR VALUES WITH (MODULUS m, REMAINDER r)`.
2600 /// PG enforces `0 ≤ r < m`; m must be positive.
2601 Hash {
2602 modulus: u32,
2603 remainder: u32,
2604 },
2605 Default,
2606}
2607
2608/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
2609/// column list. Either a composite PRIMARY KEY or a UNIQUE
2610/// (single- or multi-column).
2611#[derive(Debug, Clone, PartialEq)]
2612pub enum TableConstraint {
2613 /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
2614 /// referenced column. Engine builds a BTree index named
2615 /// `<table>_pkey` and enforces composite uniqueness on INSERT.
2616 PrimaryKey {
2617 name: Option<String>,
2618 columns: Vec<String>,
2619 /// v7.39 (round 711) — `[NOT] DEFERRABLE [INITIALLY DEFERRED]`.
2620 /// Round 621 consumed the clauses; these carry them.
2621 deferrable: bool,
2622 initially_deferred: bool,
2623 },
2624 /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
2625 /// named `<table>_<leading_col>_key` (single-column) or
2626 /// `<table>_<leading_col>_<…>_key` (composite) and enforces
2627 /// uniqueness on INSERT.
2628 Unique {
2629 name: Option<String>,
2630 columns: Vec<String>,
2631 /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
2632 /// G10). PG 15+ flips the NULL handling so any number of
2633 /// NULL rows collide on the constraint. Default is
2634 /// `false` (NULLS DISTINCT, standard SQL behaviour).
2635 nulls_not_distinct: bool,
2636 /// v7.39 (round 711) — see PrimaryKey.
2637 deferrable: bool,
2638 initially_deferred: bool,
2639 /// v7.40.0 — MySQL's per-column index prefix on a
2640 /// `UNIQUE KEY k (b(4))`, aligned with `columns`. Unlike a
2641 /// plain KEY's, this one CHANGES what the constraint accepts:
2642 /// MySQL rejects two rows sharing the first four characters.
2643 /// Empty for every PostgreSQL spelling.
2644 prefix_lengths: Vec<Option<u32>>,
2645 },
2646 /// v7.13.0 — `CHECK (<expr>)` table-level constraint
2647 /// (mailrs round-5 G3). Column-level inline CHECKs fold into
2648 /// this same variant at parse time. Engine evaluates the
2649 /// predicate against each INSERT/UPDATE candidate row; a
2650 /// false / NULL result rejects the mutation.
2651 /// v7.39 (round 652) — `not_valid` carries the `NOT VALID` suffix.
2652 /// PG adds such a constraint without scanning the existing rows: new
2653 /// rows are checked, the ones already there are grandfathered in, and
2654 /// `pg_constraint.convalidated` reads `f` until `VALIDATE CONSTRAINT`
2655 /// scans and flips it. pg_dump emits the suffix for exactly those, so
2656 /// validating them on restore would refuse a dump PG itself produced.
2657 Check {
2658 name: Option<String>,
2659 expr: Expr,
2660 not_valid: bool,
2661 },
2662 /// v7.39 (round 210) — `EXCLUDE [USING <method>] (<col> WITH <op>
2663 /// [, …])`: no two rows may satisfy `(r.c1 op1 s.c1) AND …` for
2664 /// every element (the booking/scheduling non-overlap constraint,
2665 /// `EXCLUDE USING gist (during WITH &&)`). `method` is the index
2666 /// AM name (gist/spgist/btree — informational in Phase 0; the O(n)
2667 /// enforcement doesn't build the index yet). Each element pairs a
2668 /// column name with an operator spelling (`&&`, `=`, `@>`, …).
2669 Exclude {
2670 name: Option<String>,
2671 method: Option<String>,
2672 elements: Vec<(String, String)>,
2673 },
2674 /// v7.15.0 — MySQL `KEY name (cols)` / `INDEX name (cols)`
2675 /// non-unique secondary-index declaration inline in CREATE
2676 /// TABLE. Engine builds a BTree index on the leading column
2677 /// (composite columns parse but only the leading column is
2678 /// honoured at v7.15 — matches the existing
2679 /// `CreateIndexStatement::extra_columns` semantics). Useful
2680 /// for `mysql/blog`-style schemas that lean on routine
2681 /// secondary indexes for ORM lookups.
2682 Index {
2683 name: Option<String>,
2684 columns: Vec<String>,
2685 /// v7.40.0 — MySQL's per-column index prefix, `KEY k (b(4))`,
2686 /// positionally aligned with `columns`. `None` for a column
2687 /// written without one, which is every PostgreSQL index key.
2688 ///
2689 /// It was skipped by the parser and dropped, so the declaration
2690 /// was accepted and the index built over the whole column with
2691 /// nothing recording that a prefix had been asked for —
2692 /// `SHOW INDEX` then reported `Sub_part` NULL and
2693 /// `SHOW CREATE TABLE` printed `(b)` where MySQL 9.7.2 prints
2694 /// `(b(4))`.
2695 prefix_lengths: Vec<Option<u32>>,
2696 },
2697 /// v7.17.0 Phase 2.2 — MySQL `FULLTEXT KEY/INDEX [name]
2698 /// (cols)` inline declaration. Pre-v7.17 the parser
2699 /// silently dropped these so MyISAM-imported FULLTEXT
2700 /// indexes vanished; v7.17 routes them through the
2701 /// existing tsvector-GIN engine path so MATCH AGAINST
2702 /// queries get a real inverted index instead of falling
2703 /// back to a full scan. Multi-column FULLTEXT KEYs build
2704 /// one GIN per column at v7.17 (per-column posting lists);
2705 /// the leading column drives query planning.
2706 FulltextIndex {
2707 name: Option<String>,
2708 columns: Vec<String>,
2709 },
2710}
2711
2712#[derive(Debug, Clone, PartialEq)]
2713#[allow(clippy::struct_excessive_bools)] // grammar-driven; each flag maps to a distinct PG column-constraint keyword
2714pub struct ColumnDef {
2715 pub name: String,
2716 pub ty: ColumnTypeName,
2717 pub nullable: bool,
2718 /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
2719 /// evaluates this once (with an empty row) and caches the resulting
2720 /// `Value` on the column schema.
2721 pub default: Option<Expr>,
2722 /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
2723 /// per such column and fills the slot when INSERT leaves it
2724 /// unbound (omitted from a column-list INSERT or explicitly NULL).
2725 pub auto_increment: bool,
2726 /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
2727 /// migration follow-up F1. Implies `NOT NULL`. Engine creates
2728 /// an implicit BTree index named `<table>_pkey` over this
2729 /// column at CREATE TABLE time, satisfying the parent-side
2730 /// index requirement for any FOREIGN KEY pointing at it.
2731 pub is_primary_key: bool,
2732 /// v7.13.0 — inline `UNIQUE` column constraint
2733 /// (mailrs round-5 G2). The CREATE TABLE handler folds this
2734 /// into a single-column `TableConstraint::Unique` so the
2735 /// engine path stays uniform with table-level UNIQUE.
2736 pub is_unique: bool,
2737 /// v7.38 (read01 P4.19) — `UNIQUE NULLS NOT DISTINCT` (PG 15+) on the
2738 /// inline column constraint: treat NULL keys as equal so only one NULL
2739 /// is allowed. Ignored unless `is_unique`. Folded into the table-level
2740 /// `TableConstraint::Unique { nulls_not_distinct }`.
2741 pub unique_nulls_not_distinct: bool,
2742 /// v7.39 (round 711) — `DEFERRABLE [INITIALLY DEFERRED]` written on the
2743 /// inline PK/UNIQUE column constraint. Consumed since round 621; carried
2744 /// since this round so the fold into the table-level constraint keeps it.
2745 pub constraint_deferrable: bool,
2746 pub constraint_initially_deferred: bool,
2747 /// v7.13.0 — inline `CHECK (<expr>)` column constraint
2748 /// (mailrs round-5 G3). Stored alongside the column so the
2749 /// CREATE TABLE handler can fold these into table-level
2750 /// CHECK constraints. Multiple inline CHECKs on the same
2751 /// column are concatenated with AND at the table level.
2752 pub check: Option<Expr>,
2753 /// v7.17.0 Phase 1.4 — user-defined type reference. When the
2754 /// parser sees an unknown column-type ident (anything not in
2755 /// the built-in `parse_column_type_name` table), it sets
2756 /// `ty = ColumnTypeName::Text` and records the original name
2757 /// here. The engine resolves at CREATE TABLE time: if a
2758 /// catalog enum/domain with this name exists, the column is
2759 /// bound to it (label-checked on INSERT for enums; CHECK-
2760 /// constrained for domains); otherwise the CREATE TABLE
2761 /// errors with "unknown type".
2762 pub user_type_ref: Option<String>,
2763 /// v7.17.0 Phase 2.1 — MySQL-style `ON UPDATE
2764 /// CURRENT_TIMESTAMP` column attribute. When set, an
2765 /// UPDATE that does NOT explicitly bind this column
2766 /// overrides the new value with `now()` (engine clock).
2767 /// Pre-v7.17 SPG silently accepted the syntax and never
2768 /// fired the override — `updated_at` columns from mysqldump
2769 /// stayed pinned at their initial DEFAULT forever, an
2770 /// audit Tier-S silent-failure. Generalised as a stored
2771 /// expression source so future shapes (`ON UPDATE
2772 /// CURRENT_TIMESTAMP(6)`, `ON UPDATE LOCALTIMESTAMP`) reuse
2773 /// the same field; v7.17 only accepts CURRENT_TIMESTAMP.
2774 pub on_update_runtime: Option<Expr>,
2775 /// v7.17.0 Phase 2.5 — text collation derived from the
2776 /// post-fix `COLLATE <name>` clause (and / or the table-level
2777 /// `COLLATE=<name>` for MySQL dumps that don't repeat it
2778 /// per column). Pre-2.5 SPG accepted the clause and
2779 /// discarded the name, leaving every column byte-compared
2780 /// — a Tier-S silent failure when the customer expected
2781 /// `_ci` / `case_insensitive` semantics. Parser normalises
2782 /// the raw collation name into the variants in `Collation`.
2783 /// Default `Binary` preserves the legacy compare path.
2784 pub collation: Collation,
2785 /// v7.39 (round 370, M4 P4a) — whether `collation` came from an
2786 /// explicit `COLLATE <name>` clause rather than the default. Under the
2787 /// MySQL dialect a text column with NO explicit clause takes the
2788 /// folding default collation, while an explicit `COLLATE utf8mb4_bin`
2789 /// stays byte-wise — and both resolve to `Collation::Binary`, so this
2790 /// flag is the only thing that tells them apart.
2791 pub collation_explicit: bool,
2792 /// v7.39 (round 676) — the collation name AS WRITTEN, because
2793 /// `collation` above cannot carry it: `Collation` is a two-variant
2794 /// MySQL enum and `from_collation_name` folds `C`, `POSIX`, `en_US` and
2795 /// `default` all into `Binary`. `pg_attribute.attcollation` needs to
2796 /// tell them apart.
2797 pub collation_name: Option<String>,
2798 /// v7.17.0 Phase 4.4 — MySQL `UNSIGNED` modifier flag. Pre-
2799 /// 4.4 SPG accepted and discarded the keyword, leaving
2800 /// negative values silently accepted on a column the
2801 /// customer declared `INT UNSIGNED NOT NULL`. Now: the engine
2802 /// rejects negative INSERT / UPDATE values on UNSIGNED int
2803 /// columns. SPG widening to `u64`-shaped storage is out of
2804 /// v7.17 scope; the upper bound remains the signed-type max
2805 /// (i64::MAX for BIGINT UNSIGNED), which still strictly
2806 /// exceeds what every mailrs / Rails app actually uses.
2807 pub is_unsigned: bool,
2808 /// v7.17.0 Phase 3.P0-36 — MySQL inline `ENUM('a','b','c')`
2809 /// value list captured at parse time. When `Some`, the parser
2810 /// recognised `ENUM(...)` in the type slot; the engine
2811 /// validates INSERT cells against this list at
2812 /// column_def_to_schema time and persists the variants on
2813 /// `ColumnSchema.inline_enum_variants`. None for all
2814 /// non-ENUM columns.
2815 pub inline_enum_variants: Option<Vec<String>>,
2816 /// v7.17.0 Phase 3.P0-37 — MySQL inline `SET('a','b','c')`
2817 /// value list. Distinct from ENUM (subset semantics rather
2818 /// than pick-one). None for all non-SET columns.
2819 pub inline_set_variants: Option<Vec<String>>,
2820 /// v7.37.7(sentori Epic 3 P1)— `GENERATED ALWAYS AS (<expr>)
2821 /// STORED` computed-column source. When `Some`, the engine
2822 /// stores the Display-form of the parsed expression on
2823 /// `ColumnSchema.generated_stored_expr` at CREATE TABLE time
2824 /// and re-evaluates the expression against every INSERT /
2825 /// UPDATE candidate row, overwriting whatever the caller
2826 /// supplied for this column. Boxed to keep `ColumnDef` from
2827 /// blowing past the `large_enum_variant` clippy ceiling
2828 /// (`Expr` widens with vector literals).
2829 pub generated_stored_expr: Option<Box<Expr>>,
2830 /// v7.38 (read01) — `GENERATED ALWAYS AS IDENTITY` (as opposed to
2831 /// `GENERATED BY DEFAULT AS IDENTITY`). Both flavours set
2832 /// `auto_increment`; this additionally marks the ALWAYS one, whose
2833 /// explicit INSERT value PG rejects ("cannot insert a non-DEFAULT
2834 /// value into column …") unless the INSERT carries `OVERRIDING SYSTEM
2835 /// VALUE`. Only meaningful when the column is also an identity column.
2836 pub identity_always: bool,
2837 /// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2838 /// integer width (TINYINT / MEDIUMINT), captured before the type
2839 /// collapses to SmallInt / Int. The engine copies it to
2840 /// `ColumnSchema.mysql_int_width` at CREATE TABLE time so the write
2841 /// path can enforce the real range. None for every other column and
2842 /// under the PG dialect.
2843 pub mysql_int_width: Option<MysqlIntWidth>,
2844 /// v7.39 (round 424, type-fidelity epic) — the declared MySQL
2845 /// fractional-seconds precision of a temporal column (`DATETIME(3)` is
2846 /// `Some(3)`; a bare `DATETIME` / `TIME` / `TIMESTAMP` is `Some(0)`,
2847 /// MySQL's default). The engine copies it to `ColumnSchema.mysql_fsp` at
2848 /// CREATE TABLE time so the write path can truncate and the render path
2849 /// can pad. None under the PG dialect, where temporal columns keep full
2850 /// microseconds.
2851 pub mysql_fsp: Option<u8>,
2852 /// v7.39.2 — the column was written `TIMESTAMP` rather than
2853 /// `DATETIME` in a MySQL session. The engine copies it to
2854 /// `ColumnSchema.mysql_declared_timestamp` at CREATE TABLE.
2855 pub mysql_declared_timestamp: bool,
2856 /// v7.39.3 — a MySQL `FLOAT(m,d)` / `DOUBLE(m,d)` pair, copied to
2857 /// `ColumnSchema.mysql_float_md` at CREATE TABLE.
2858 pub mysql_float_md: Option<(u8, u8)>,
2859}
2860
2861/// v7.17.0 Phase 2.5 — text collation classification surfaced
2862/// from the SQL parser. Mirrors `spg_storage::Collation`; the
2863/// engine bridges between the two at CREATE TABLE time.
2864///
2865/// Recognised collation-name patterns (case-insensitive):
2866/// * `case_insensitive`, `*_ci`, `*_ai_ci`, `nocase` → CaseInsensitive
2867/// * Everything else (`C`, `POSIX`, `default`,
2868/// `pg_catalog.default`, `*_cs`, `*_bin`, unknown names) → Binary
2869#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2870pub enum Collation {
2871 Binary,
2872 CaseInsensitive,
2873}
2874
2875/// v7.39 (round 386, type-fidelity epic P1) — the declared MySQL narrow
2876/// integer width for a column whose `ColumnTypeName` is too wide to carry
2877/// it: `TINYINT` collapses to `SmallInt`, `MEDIUMINT` to `Int`. Mirrors
2878/// `spg_storage::MysqlIntWidth`; the engine bridges the two at CREATE
2879/// TABLE time. Only recorded under the MySQL dialect.
2880#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2881pub enum MysqlIntWidth {
2882 Tiny,
2883 Small,
2884 Medium,
2885 Int,
2886 /// v7.39 (round 471, epic P4b) — `BIGINT UNSIGNED`.
2887 Big,
2888}
2889
2890#[allow(clippy::derivable_impls)]
2891impl Default for Collation {
2892 fn default() -> Self {
2893 Self::Binary
2894 }
2895}
2896
2897impl Collation {
2898 /// Classify a `COLLATE <name>` ident into one of the supported
2899 /// variants. Empty / unknown names fall back to `Binary` —
2900 /// matches the pre-2.5 silent-accept behaviour for snapshots
2901 /// that load through but don't actually depend on the
2902 /// collation semantics.
2903 #[must_use]
2904 pub fn from_collation_name(name: &str) -> Self {
2905 let lc = name.trim().to_ascii_lowercase();
2906 // Strip any quotes / schema-qualifier the parser left on
2907 // (e.g. `pg_catalog.default`).
2908 let bare = lc
2909 .trim_matches(|c: char| c == '"' || c == '\'')
2910 .rsplit('.')
2911 .next()
2912 .unwrap_or("");
2913 if bare.is_empty() {
2914 return Self::Binary;
2915 }
2916 if bare == "case_insensitive" || bare == "nocase" {
2917 return Self::CaseInsensitive;
2918 }
2919 // MySQL `_ci` suffix (covers `utf8mb4_general_ci`,
2920 // `utf8mb4_unicode_ci`, `utf8mb4_0900_ai_ci`, …).
2921 if bare.ends_with("_ci") {
2922 return Self::CaseInsensitive;
2923 }
2924 Self::Binary
2925 }
2926}
2927
2928/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
2929/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
2930/// parse into this shape — the column-level form has a single-entry
2931/// `columns` / `parent_columns`.
2932#[derive(Debug, Clone, PartialEq)]
2933pub struct ForeignKeyConstraint {
2934 /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
2935 /// today but parses + stores it so a future ALTER TABLE DROP
2936 /// CONSTRAINT can target by name (v7.6.8).
2937 pub name: Option<String>,
2938 /// Local columns participating in the FK (≥ 1).
2939 pub columns: Vec<String>,
2940 /// Referenced parent table.
2941 pub parent_table: String,
2942 /// Referenced parent columns. Must have the same arity as
2943 /// `columns`; engine validates parent has a PK / UNIQUE index
2944 /// on exactly this column set (v7.6.1).
2945 pub parent_columns: Vec<String>,
2946 /// `ON DELETE` action. Defaults to `Restrict` if absent.
2947 pub on_delete: FkAction,
2948 /// `ON UPDATE` action. Defaults to `Restrict` if absent.
2949 pub on_update: FkAction,
2950 /// v7.38 (read01, T29) — `MATCH {SIMPLE | FULL}`. Defaults to `Simple`.
2951 pub match_type: MatchType,
2952 /// v7.39 (round 288) — `[NOT] DEFERRABLE`. Parsed since v7.17 and
2953 /// dropped on the floor, so a constraint declared DEFERRABLE was
2954 /// enforced immediately and a circular-FK migration could not load.
2955 pub deferrable: bool,
2956 /// `INITIALLY DEFERRED` — the check moves to COMMIT unless
2957 /// `SET CONSTRAINTS … IMMEDIATE` pulls it forward.
2958 pub initially_deferred: bool,
2959}
2960
2961/// v7.38 (read01, T29) — FK `MATCH` type. SIMPLE (default) skips the check when
2962/// ANY referencing column is NULL; FULL requires all-or-none NULL (a mixed-NULL
2963/// key errors). PARTIAL is parse-rejected (PG does not implement it either).
2964#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2965pub enum MatchType {
2966 #[default]
2967 Simple,
2968 Full,
2969}
2970
2971/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
2972#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2973pub enum FkAction {
2974 /// Reject the parent mutation if any child row references it.
2975 /// SQL spec default; SPG default when no clause is given.
2976 Restrict,
2977 /// Recursively propagate the parent's delete / update to the
2978 /// child rows. Same TX.
2979 Cascade,
2980 /// Set the child FK column(s) to NULL. Requires the FK columns
2981 /// to be NULL-able.
2982 SetNull,
2983 /// Set the child FK column(s) to their declared DEFAULT.
2984 /// Requires the child column(s) to have DEFAULT.
2985 SetDefault,
2986 /// SQL spec `NO ACTION` (deferred check). SPG treats this as
2987 /// `Restrict` because the single-writer model has no deferred
2988 /// constraint window; the keyword is accepted for compatibility.
2989 NoAction,
2990}
2991
2992/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
2993/// optional `USING <encoding>` clause; omitting it keeps the
2994/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
2995/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
2996/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
2997/// binary16 (2× compression, ~3 decimal digits of precision).
2998#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2999pub enum VecEncoding {
3000 /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
3001 /// uncompressed `vector` type wire / storage layout.
3002 #[default]
3003 F32,
3004 /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
3005 /// `spg_storage::quantize::Sq8Vector` for the math + recall
3006 /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
3007 /// dim ≥ 32).
3008 Sq8,
3009 /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
3010 /// per-element. DDL keyword `HALF` (pgvector convention).
3011 /// Bit-exact dequantise to f32 at the storage layer; no
3012 /// rerank pass needed for kNN search.
3013 F16,
3014}
3015
3016impl fmt::Display for VecEncoding {
3017 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3018 match self {
3019 Self::F32 => f.write_str("F32"),
3020 Self::Sq8 => f.write_str("SQ8"),
3021 // pgvector convention: DDL keyword is `HALF`, not `F16`.
3022 Self::F16 => f.write_str("HALF"),
3023 }
3024 }
3025}
3026
3027/// SQL-level type names. The mapping to the storage runtime's `DataType`
3028/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
3029#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3030pub enum ColumnTypeName {
3031 /// v7.39 (round 291) — PG's `name`, the identifier type its
3032 /// catalogs use. `CREATE TABLE t (a name)` is legal SQL that SPG
3033 /// answered `type "name" does not exist` to.
3034 Name,
3035 /// v7.39 (round 640) — PG's transaction-id types. `xid` is the
3036 /// 32-bit wrapping counter the row header carries; `xid8` is the
3037 /// 64-bit monotonic one. `CREATE TABLE t (a xid)` is legal SQL that
3038 /// SPG answered `type "xid" does not exist` to.
3039 Xid,
3040 Xid8,
3041 /// v7.39 (round 667) — `OID`. `XID` was already a column type here
3042 /// and `OID` was not, so `CREATE TABLE t(o OID)` answered
3043 /// `type "oid" does not exist` while `t(x XID)` built fine.
3044 Oid,
3045 SmallInt,
3046 Int,
3047 BigInt,
3048 Float,
3049 /// v7.39 (round 269) — `REAL` / `FLOAT4` / `FLOAT(1..24)`: 32-bit
3050 /// IEEE. It used to map to [`Self::Float`] on the theory that a
3051 /// wider float is harmless, but the width is observable: a `real`
3052 /// column holding 0.1 stored the f64 0.1, so `r = 0.1::real`
3053 /// answered false where PG answers true.
3054 Real,
3055 Text,
3056 /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
3057 Varchar(u32),
3058 /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
3059 Char(u32),
3060 Bool,
3061 /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
3062 /// `USING <encoding>` clause; omitting it surfaces as
3063 /// `encoding = VecEncoding::F32` (the pre-v6 default).
3064 Vector {
3065 dim: u32,
3066 encoding: VecEncoding,
3067 },
3068 /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
3069 /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
3070 /// v7.39 (round 271) — scale widened to u16 alongside the value's.
3071 /// v7.39 (round 272) — precision too: PG's runs to 1000.
3072 /// v7.39 (round 273) — the DECLARED scale is signed (-1000..=1000);
3073 /// a negative one rounds to tens / hundreds. A VALUE's display scale
3074 /// stays unsigned.
3075 Numeric(u16, i16),
3076 /// `DATE` — calendar day, no time-of-day component.
3077 Date,
3078 /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
3079 /// precision.
3080 Timestamp,
3081 /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
3082 /// stores all timestamps as UTC microseconds-since-epoch and
3083 /// does not carry per-row offset (PG's internal representation
3084 /// is the same — TZ is a display convention). The distinction
3085 /// from `TIMESTAMP` exists for the PG-wire layer to advertise
3086 /// OID 1184 so sqlx-style clients decode into
3087 /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
3088 Timestamptz,
3089 /// v4.9 `JSON` — text-backed JSON document. No parse-time
3090 /// validation; the engine round-trips the literal verbatim.
3091 /// PG OID 114 on the wire.
3092 Json,
3093 /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
3094 /// PG OID 3802 on the wire so sqlx-style binary-typed clients
3095 /// decode without a custom type registration.
3096 Jsonb,
3097 /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
3098 /// Literal forms (decoded by the engine at coercion time):
3099 /// - PG hex form: `'\xDEADBEEF'`
3100 /// - Escape form: `'foo\\000bar'` (backslash octal triples)
3101 Bytes,
3102 /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
3103 /// OID 1009. Literal forms accepted by the parser:
3104 /// - `ARRAY['a', 'b', NULL]`
3105 /// - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
3106 /// form at coerce time)
3107 TextArray,
3108 /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
3109 /// 1007. Same literal forms as TEXT[] (substituting integer
3110 /// elements).
3111 IntArray,
3112 /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
3113 /// OID 1016.
3114 BigIntArray,
3115 /// v7.40.0 `OID[]` — single-dimension oid array. PG wire OID
3116 /// 1028.
3117 ///
3118 /// `DataType::OidArray` and its value, codec tag, wire encoding
3119 /// and every naming surface have existed since v7.39 (round 694);
3120 /// what was missing was only the DDL spelling, so
3121 /// `CREATE TABLE t (c oid[])` answered `Oid[] not yet supported`
3122 /// while PostgreSQL 18.6 accepts it. Capability present, routing
3123 /// absent — the same shape as this repository's other hand-kept
3124 /// lists.
3125 OidArray,
3126 /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
3127 /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
3128 /// external form). G-CRIT-3.
3129 TsVector,
3130 /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
3131 /// wire OID 3615.
3132 TsQuery,
3133 /// v7.17.0 `UUID` — 128-bit identifier. PG wire OID 2950.
3134 /// Literal input accepts canonical hyphenated, unhyphenated,
3135 /// uppercase, and `{...}`-braced forms; display normalises to
3136 /// canonical lowercase 8-4-4-4-12. The drop-in PG surface for
3137 /// Django / Rails / Hibernate `id UUID PRIMARY KEY DEFAULT
3138 /// gen_random_uuid()`.
3139 Uuid,
3140 /// v7.17.0 Phase 3.P0-32 `TIME` (without time zone) — i64
3141 /// microseconds since 00:00:00. PG wire OID 1083. Literal
3142 /// input is `'HH:MM:SS'` with an optional `.fraction` suffix
3143 /// (6-digit microsecond precision). Display normalises to
3144 /// the canonical `HH:MM:SS[.ffffff]`.
3145 Time,
3146 /// v7.17.0 Phase 3.P0-33 MySQL `YEAR` — u16 in range
3147 /// 1901..=2155 plus the zero-year sentinel 0. No dedicated
3148 /// PG OID; advertised as INT4 on the wire. Display always
3149 /// 4 digits zero-padded.
3150 Year,
3151 /// v7.17.0 Phase 3.P0-34 PG `TIME WITH TIME ZONE` (TIMETZ) —
3152 /// i64 us since 00:00:00 (local) + i32 offset_secs from UTC.
3153 /// Wire OID 1266. Literal input is `'HH:MM:SS[.ffffff]±HH[:MM]'`.
3154 /// Offset range: ±14 hours.
3155 TimeTz,
3156 /// v7.17.0 Phase 3.P0-35 PG `MONEY` — i64 cents
3157 /// (locale-independent storage). Wire OID 790. Literal input
3158 /// accepts `$N.NN`, `$N,NNN.NN`, bare integer (treated as
3159 /// major units), optional leading `-`. Display: en_US locale.
3160 Money,
3161 /// v7.17.0 Phase 3.P0-38 PG range types. Pair stores the
3162 /// element kind tag (Int4 / Int8 / Num / Ts / TsTz / Date)
3163 /// — the engine bridges to `DataType::Range(RangeKind)`.
3164 Range(RangeKindAst),
3165 /// v7.17.0 Phase 3.P0-39 PG `hstore` extension type — flat
3166 /// `text => text` map with NULL value support.
3167 Hstore,
3168 /// v7.17.0 Phase 3.P0-40 — 2D arrays for INT / TEXT / BIGINT.
3169 IntArray2D,
3170 BigIntArray2D,
3171 TextArray2D,
3172 /// v7.39 (read01 round 75) — `bool[][]`.
3173 BoolArray2D,
3174 /// v7.37.5 β-P2 — `INTERVAL` as a column type. Storage is the
3175 /// three-field {months, days, micros} struct (PG-byte-equal),
3176 /// catalog tag 34, FILE_VERSION 48+. Wire OID 1186. Prior to
3177 /// β-P2 `INTERVAL` was runtime-only — literal in expression
3178 /// position but rejected at CREATE TABLE.
3179 Interval,
3180 /// v7.37.5 β-P4 — `INTERVAL[]` — single-dimension array of
3181 /// INTERVAL. Wire OID 1187 (`_interval`). Catalog tag 35.
3182 /// PG external form quotes each non-NULL element because
3183 /// interval text contains spaces / colons
3184 /// (`{"1 day","24:00:00",NULL}`).
3185 IntervalArray,
3186 /// v7.37.5 γ — full PG array-of-scalar family. Each variant
3187 /// mirrors a scalar `ColumnTypeName` that already existed.
3188 BoolArray,
3189 SmallIntArray,
3190 FloatArray,
3191 NumericArray,
3192 DateArray,
3193 TimestampArray,
3194 TimestamptzArray,
3195 UuidArray,
3196 JsonArray,
3197 JsonbArray,
3198 BytesArray,
3199 VarcharArray,
3200 CharArray,
3201 /// v7.40.0 — five array spellings PG 18.6 accepts at
3202 /// `CREATE TABLE` and SPG refused at the type name. The
3203 /// element types were all present; only the `[]` step was.
3204 RealArray,
3205 TimeArray,
3206 TimeTzArray,
3207 InetArray,
3208 XmlArray,
3209 /// v7.37.5 δ — PG 14+ multirange types. Same wrapper pattern
3210 /// as `Range(RangeKindAst)` — one column type variant covers
3211 /// all six builtin multiranges, kind pins the element type.
3212 /// Wire OIDs in pgwire.
3213 Multirange(RangeKindAst),
3214 /// v7.37.5 ε — PG geometry scalar family. Each maps one-to-
3215 /// one to a PG type: point/lseg/path/box/polygon/line/circle.
3216 /// Wire OIDs in pgwire.
3217 Point,
3218 Lseg,
3219 Path,
3220 PgBox,
3221 Polygon,
3222 Line,
3223 Circle,
3224 /// v7.37.5 ζ-A — PG network / bit / xml / "char" / money[].
3225 Inet,
3226 Cidr,
3227 Macaddr,
3228 Macaddr8,
3229 /// v7.39 (round 281) — `BIT(n)`; `0` = no typmod (PG: `bit(1)`).
3230 Bit(u32),
3231 /// v7.39 (round 281) — `BIT VARYING(n)`; `0` = unbounded.
3232 BitVarying(u32),
3233 Xml,
3234 Char1,
3235 MoneyArray,
3236}
3237
3238/// v7.17.0 Phase 3.P0-38 — PG range element kind. Mirrors
3239/// `spg_storage::RangeKind`; we keep it spg-sql-local so the AST
3240/// crate doesn't depend on storage. Bridged at engine boundary.
3241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
3242pub enum RangeKindAst {
3243 Int4,
3244 Int8,
3245 Num,
3246 Ts,
3247 TsTz,
3248 Date,
3249}
3250
3251impl fmt::Display for ColumnTypeName {
3252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3253 match self {
3254 Self::SmallInt => f.write_str("SMALLINT"),
3255 Self::Int => f.write_str("INT"),
3256 Self::BigInt => f.write_str("BIGINT"),
3257 Self::Float => f.write_str("FLOAT"),
3258 Self::Real => f.write_str("REAL"),
3259 Self::Text => f.write_str("TEXT"),
3260 Self::Name => f.write_str("name"),
3261 Self::Xid => f.write_str("xid"),
3262 Self::Xid8 => f.write_str("xid8"),
3263 Self::Oid => f.write_str("oid"),
3264 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
3265 Self::Char(n) => write!(f, "CHAR({n})"),
3266 Self::Bool => f.write_str("BOOL"),
3267 Self::Vector { dim, encoding } => match encoding {
3268 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
3269 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
3270 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
3271 },
3272 Self::Json => f.write_str("JSON"),
3273 Self::Jsonb => f.write_str("JSONB"),
3274 Self::Bytes => f.write_str("BYTEA"),
3275 Self::TextArray => f.write_str("TEXT[]"),
3276 Self::IntArray => f.write_str("INT[]"),
3277 Self::BigIntArray => f.write_str("BIGINT[]"),
3278 Self::OidArray => f.write_str("oid[]"),
3279 Self::TsVector => f.write_str("TSVECTOR"),
3280 Self::TsQuery => f.write_str("TSQUERY"),
3281 Self::Uuid => f.write_str("UUID"),
3282 Self::Numeric(p, s) => {
3283 if *s == 0 {
3284 write!(f, "NUMERIC({p})")
3285 } else {
3286 write!(f, "NUMERIC({p}, {s})")
3287 }
3288 }
3289 Self::Date => f.write_str("DATE"),
3290 Self::Timestamp => f.write_str("TIMESTAMP"),
3291 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
3292 Self::Time => f.write_str("TIME"),
3293 Self::Year => f.write_str("YEAR"),
3294 Self::TimeTz => f.write_str("TIMETZ"),
3295 Self::Money => f.write_str("MONEY"),
3296 Self::Range(k) => f.write_str(match k {
3297 RangeKindAst::Int4 => "INT4RANGE",
3298 RangeKindAst::Int8 => "INT8RANGE",
3299 RangeKindAst::Num => "NUMRANGE",
3300 RangeKindAst::Ts => "TSRANGE",
3301 RangeKindAst::TsTz => "TSTZRANGE",
3302 RangeKindAst::Date => "DATERANGE",
3303 }),
3304 Self::Hstore => f.write_str("HSTORE"),
3305 Self::Interval => f.write_str("INTERVAL"),
3306 Self::IntervalArray => f.write_str("INTERVAL[]"),
3307 Self::BoolArray => f.write_str("BOOL[]"),
3308 Self::SmallIntArray => f.write_str("SMALLINT[]"),
3309 Self::FloatArray => f.write_str("FLOAT[]"),
3310 Self::NumericArray => f.write_str("NUMERIC[]"),
3311 Self::DateArray => f.write_str("DATE[]"),
3312 Self::TimestampArray => f.write_str("TIMESTAMP[]"),
3313 Self::TimestamptzArray => f.write_str("TIMESTAMPTZ[]"),
3314 Self::UuidArray => f.write_str("UUID[]"),
3315 Self::JsonArray => f.write_str("JSON[]"),
3316 Self::JsonbArray => f.write_str("JSONB[]"),
3317 Self::BytesArray => f.write_str("BYTEA[]"),
3318 Self::VarcharArray => f.write_str("VARCHAR[]"),
3319 Self::CharArray => f.write_str("CHAR[]"),
3320 Self::RealArray => f.write_str("REAL[]"),
3321 Self::TimeArray => f.write_str("TIME[]"),
3322 Self::TimeTzArray => f.write_str("TIMETZ[]"),
3323 Self::InetArray => f.write_str("INET[]"),
3324 Self::XmlArray => f.write_str("XML[]"),
3325 Self::Multirange(k) => f.write_str(match k {
3326 RangeKindAst::Int4 => "INT4MULTIRANGE",
3327 RangeKindAst::Int8 => "INT8MULTIRANGE",
3328 RangeKindAst::Num => "NUMMULTIRANGE",
3329 RangeKindAst::Ts => "TSMULTIRANGE",
3330 RangeKindAst::TsTz => "TSTZMULTIRANGE",
3331 RangeKindAst::Date => "DATEMULTIRANGE",
3332 }),
3333 Self::Point => f.write_str("POINT"),
3334 Self::Lseg => f.write_str("LSEG"),
3335 Self::Path => f.write_str("PATH"),
3336 Self::PgBox => f.write_str("BOX"),
3337 Self::Polygon => f.write_str("POLYGON"),
3338 Self::Line => f.write_str("LINE"),
3339 Self::Circle => f.write_str("CIRCLE"),
3340 Self::Inet => f.write_str("INET"),
3341 Self::Cidr => f.write_str("CIDR"),
3342 Self::Macaddr => f.write_str("MACADDR"),
3343 Self::Macaddr8 => f.write_str("MACADDR8"),
3344 Self::Bit(0) => f.write_str("BIT"),
3345 Self::Bit(n) => write!(f, "BIT({n})"),
3346 Self::BitVarying(0) => f.write_str("VARBIT"),
3347 Self::BitVarying(n) => write!(f, "VARBIT({n})"),
3348 Self::Xml => f.write_str("XML"),
3349 Self::Char1 => f.write_str("\"char\""),
3350 Self::MoneyArray => f.write_str("MONEY[]"),
3351 Self::IntArray2D => f.write_str("INT[][]"),
3352 Self::BigIntArray2D => f.write_str("BIGINT[][]"),
3353 Self::TextArray2D => f.write_str("TEXT[][]"),
3354 Self::BoolArray2D => f.write_str("BOOL[][]"),
3355 }
3356 }
3357}
3358
3359/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
3360/// engine evaluates `expr` per matched row in the table's row order
3361/// and rewrites cells in place. Indexed columns are dropped + re-
3362/// inserted into the affected B-tree on each row change.
3363/// v7.39 (round 413) — the boxed payload for MySQL's `ORDER BY [LIMIT]`
3364/// tail on a DML statement. Boxed off the statement struct so the PG-only
3365/// common path stays at its pre-r413 size (see the round-305 nesting-stack
3366/// lesson). v7.39 (round 431+1) — DELETE carries the identical clause with
3367/// the identical meaning, so both share this one payload rather than each
3368/// growing its own.
3369#[derive(Debug, Clone, PartialEq)]
3370pub struct DmlOrderLimit {
3371 pub order_by: Vec<OrderBy>,
3372 pub limit: Option<u32>,
3373}
3374
3375/// v7.39 (round 533) — what `UPDATE … FROM src WHERE cond` was lowered
3376/// FROM, kept so the engine can finish the job.
3377///
3378/// The parser rewrites the statement onto correlated subqueries, and it
3379/// can only classify a QUALIFIED leaf: deciding whether an unqualified
3380/// name belongs to the target or to a source needs their column lists,
3381/// which parse time does not have. Carrying the clause lets the engine
3382/// — which has the catalog — resolve the rest.
3383#[derive(Debug, Clone, PartialEq)]
3384pub struct UpdateFromSources {
3385 pub from: FromClause,
3386 pub sub_where: Option<Expr>,
3387}
3388
3389#[derive(Debug, Clone, PartialEq)]
3390pub struct UpdateStatement {
3391 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3392 /// level UPDATE. Empty for a plain UPDATE.
3393 pub ctes: Vec<Cte>,
3394 pub table: String,
3395 /// v7.39 (round 646) — `UPDATE ONLY t` / `DELETE FROM ONLY t`: apply
3396 /// to `t`'s own rows and not to anything that descends from it.
3397 ///
3398 /// Round 644 taught the FROM clause the keyword and left DML behind
3399 /// because it needed a field here, and this struct carries a warning
3400 /// that round 413 measured widening it in place overflowing the
3401 /// parser's nesting stack. That warning was about `from_sources`, a
3402 /// struct wide enough to need boxing; a `bool` lands in the padding
3403 /// already present — same as `CreateTableStatement::temporary`.
3404 ///
3405 /// It also earns its keep beyond the spelling: the inheritance
3406 /// fan-out needs a way to say "the parent's own rows" as a
3407 /// statement, or running one on the parent recurses forever.
3408 pub only: bool,
3409 /// v7.39 (round 241) — `UPDATE t [AS] alias SET …`: the name the
3410 /// statement's expressions refer to the target row by. PG allows the
3411 /// bare spelling here (unlike INSERT, which requires AS).
3412 pub alias: Option<String>,
3413 pub assignments: Vec<(String, Expr)>,
3414 /// v7.39 (round 533) — boxed: round 413 measured that widening this
3415 /// struct in place overflows the parser's nesting stack.
3416 pub from_sources: Option<alloc::boxed::Box<UpdateFromSources>>,
3417 pub where_: Option<Expr>,
3418 /// v7.39 (round 413) — MySQL's `UPDATE … [ORDER BY … [LIMIT n]]`:
3419 /// mutate the first `limit` rows in the given order. PG has no such
3420 /// clause; the parser accepts it only under the MySQL dialect. Boxed
3421 /// so a PG UPDATE (the common case) grows this struct by ONE pointer,
3422 /// not `Vec<OrderBy> + Option<u32>` — a naked add tipped the parser's
3423 /// 512 KiB nesting stack under a full workspace test (round 305 kin).
3424 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3425 /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
3426 /// clause (legacy CommandComplete path). Some = engine
3427 /// evaluates the projection over each mutated row and
3428 /// streams the result as a Rows QueryResult.
3429 pub returning: Option<Vec<SelectItem>>,
3430}
3431
3432/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
3433/// from the active catalog and prunes them from every index.
3434#[derive(Debug, Clone, PartialEq)]
3435pub struct DeleteStatement {
3436 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3437 /// level DELETE. Empty for a plain DELETE.
3438 pub ctes: Vec<Cte>,
3439 pub table: String,
3440 /// v7.39 (round 646) — `DELETE FROM ONLY t`, the sibling of `UpdateStatement::only`: apply
3441 /// to `t`'s own rows and not to anything that descends from it.
3442 ///
3443 /// Round 644 taught the FROM clause the keyword and left DML behind
3444 /// because it needed a field here, and this struct carries a warning
3445 /// that round 413 measured widening it in place overflowing the
3446 /// parser's nesting stack. That warning was about `from_sources`, a
3447 /// struct wide enough to need boxing; a `bool` lands in the padding
3448 /// already present — same as `CreateTableStatement::temporary`.
3449 ///
3450 /// It also earns its keep beyond the spelling: the inheritance
3451 /// fan-out needs a way to say "the parent's own rows" as a
3452 /// statement, or running one on the parent recurses forever.
3453 pub only: bool,
3454 /// v7.39 (round 241) — `DELETE FROM t [AS] alias USING …`: the name
3455 /// the WHERE / RETURNING expressions refer to the target row by.
3456 pub alias: Option<String>,
3457 pub where_: Option<Expr>,
3458 /// v7.39 (round 432) — MySQL's `DELETE … [ORDER BY … [LIMIT n]]`, the
3459 /// batched-cleanup idiom. Same clause and same meaning as the UPDATE
3460 /// form (round 413), so it shares that payload — and it is boxed for
3461 /// the same reason: a naked `Vec<OrderBy> + Option<u32>` on a DML
3462 /// statement tipped the parser's 512 KiB nesting stack.
3463 pub order_limit: Option<alloc::boxed::Box<DmlOrderLimit>>,
3464 /// v7.9.4 — `RETURNING <projection>`.
3465 pub returning: Option<Vec<SelectItem>>,
3466}
3467
3468/// v7.17.0 Phase 3.P0-42 — SQL:2003 / PG 15+ MERGE statement.
3469/// One WHEN clause fires per source row depending on whether the
3470/// `on` condition matched any target row(s); the executor walks
3471/// `clauses` in declaration order and fires the first whose
3472/// `matched` kind and optional `condition` are both satisfied.
3473#[derive(Debug, Clone, PartialEq)]
3474pub struct MergeStatement {
3475 /// v7.39 (read01 round 149) — leading `WITH <cte> [, …]` (PG 15 allows
3476 /// a WITH clause on MERGE; `WITH RECURSIVE` is rejected at parse, as
3477 /// in PG). Each CTE materialises before the merge runs and its alias
3478 /// resolves as a source relation.
3479 pub ctes: Vec<Cte>,
3480 pub target: String,
3481 pub target_alias: Option<String>,
3482 pub source: String,
3483 pub source_alias: Option<String>,
3484 /// v7.37 D.44 — `USING (SELECT …) alias` subquery source. When present,
3485 /// the engine materialises this SELECT for the source rows and `source`
3486 /// is empty; the alias (required by PG for a subquery source) is in
3487 /// `source_alias`. `None` = plain `USING <table>` (source names a table).
3488 pub source_select: Option<Box<SelectStatement>>,
3489 /// v7.39 (round 768, F31-D5) — `USING (VALUES …) s(id, v)`: the
3490 /// positional column-alias list after the source alias. Empty when
3491 /// the statement carries none; the engine renames the materialised
3492 /// source columns positionally (PG's rule).
3493 pub source_column_aliases: Vec<String>,
3494 pub on: Expr,
3495 pub clauses: Vec<MergeWhenClause>,
3496 /// v7.39 (read01 round 130) — PG17+ `MERGE … RETURNING <projection>`.
3497 /// The projection may use `merge_action()`, `OLD.*`/`NEW.*`, and the
3498 /// target/source aliases. `None` = no RETURNING (the common form).
3499 pub returning: Option<Vec<SelectItem>>,
3500}
3501
3502#[derive(Debug, Clone, PartialEq)]
3503pub struct MergeWhenClause {
3504 pub matched: MergeMatched,
3505 /// Optional `AND <expr>` filter — when present, the clause
3506 /// only fires for the source rows whose match-pair satisfies
3507 /// the predicate.
3508 pub condition: Option<Expr>,
3509 pub action: MergeAction,
3510}
3511
3512#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3513pub enum MergeMatched {
3514 Matched,
3515 /// `WHEN NOT MATCHED [BY TARGET]` — a source row with no matching
3516 /// target row (the classic insert branch).
3517 NotMatched,
3518 /// v7.39 (round 146, PG17) — `WHEN NOT MATCHED BY SOURCE`: a TARGET
3519 /// row no source row matches. Actions are UPDATE / DELETE / DO
3520 /// NOTHING only (INSERT is a syntax error, as in PG).
3521 NotMatchedBySource,
3522}
3523
3524#[derive(Debug, Clone, PartialEq)]
3525pub enum MergeAction {
3526 /// `INSERT (cols) VALUES (vals)`. SPG v7.17 requires the
3527 /// explicit column list (the bare `INSERT VALUES (vals)`
3528 /// shape lands later).
3529 Insert {
3530 columns: Vec<String>,
3531 values: Vec<Expr>,
3532 },
3533 /// `UPDATE SET col = expr [, …]` — applied to every matched
3534 /// target row for the firing source row.
3535 Update { assignments: Vec<(String, Expr)> },
3536 /// `DELETE` — drop every matched target row.
3537 Delete,
3538 /// `DO NOTHING` — explicit no-op (the SQL standard accepts
3539 /// the clause and SPG mirrors so a customer-side MERGE that
3540 /// uses it for branch-control doesn't error).
3541 DoNothing,
3542}
3543
3544#[derive(Debug, Clone, PartialEq)]
3545pub struct InsertStatement {
3546 /// v7.37.43-T4.4 — leading `WITH cte AS (…)` clauses on a top-
3547 /// level INSERT (writable CTE outer body). Empty for a plain
3548 /// INSERT. PG semantics: each CTE materialises before the
3549 /// outer INSERT runs, sharing the same transaction.
3550 pub ctes: Vec<Cte>,
3551 pub table: String,
3552 /// v7.39 (round 240) — `INSERT INTO t AS alias`: the alias the ON
3553 /// CONFLICT DO UPDATE expressions (and RETURNING) refer to the target
3554 /// row by. PG requires the AS keyword in this position.
3555 pub alias: Option<String>,
3556 /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
3557 /// `None`, every tuple is positional and must match the table arity.
3558 /// When `Some`, the engine maps each tuple slot to the named column and
3559 /// fills the rest with NULL (must be nullable).
3560 pub columns: Option<Vec<String>>,
3561 /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
3562 /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
3563 /// `select_source` is `Some` (the engine builds rows from the
3564 /// inner SELECT result set instead).
3565 pub rows: Vec<Vec<Expr>>,
3566 /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
3567 /// round-5 G4). When present, `rows` is empty and the engine
3568 /// materialises the SELECT result, coerces each output tuple to
3569 /// the target column types, and inserts as a single batch.
3570 pub select_source: Option<Box<SelectStatement>>,
3571 /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
3572 /// upsert clause. None = legacy INSERT (conflict raises a
3573 /// DuplicateKey error). mailrs migration blocker #2.
3574 pub on_conflict: Option<OnConflictClause>,
3575 /// v7.9.4 — `RETURNING <projection>`.
3576 pub returning: Option<Vec<SelectItem>>,
3577 /// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` clause
3578 /// between the column list and VALUES. Governs how explicitly-supplied
3579 /// values interact with `GENERATED … AS IDENTITY` columns:
3580 /// * `None` — default. A `GENERATED ALWAYS` identity column rejects
3581 /// an explicit non-DEFAULT value; a `BY DEFAULT` one accepts it.
3582 /// * `System` — override the ALWAYS restriction: the explicit value
3583 /// is used verbatim, as for a `BY DEFAULT` column.
3584 /// * `User` — ignore any explicit value on a `BY DEFAULT` identity
3585 /// column and generate from the sequence instead (no effect on
3586 /// non-identity columns).
3587 pub overriding: Overriding,
3588 /// v7.39 (round 434) — the statement was spelled `INSERT IGNORE`.
3589 /// Round 406 lowered that to `ON CONFLICT DO NOTHING`, which covers the
3590 /// key-conflict half of MySQL's IGNORE. The other half is that IGNORE
3591 /// also downgrades per-VALUE errors to coercions (out-of-range clamps,
3592 /// over-long strings truncate, a non-numeric string becomes 0, a NULL
3593 /// into a NOT NULL column becomes the type's default), and the engine
3594 /// cannot recover that intent from the conflict clause alone. A plain
3595 /// `bool` lands in this struct's existing padding, so the AST does not
3596 /// grow — measured, per the round-305 / 413 nesting-stack lesson.
3597 pub mysql_ignore: bool,
3598}
3599
3600/// v7.38 (read01) — `OVERRIDING { SYSTEM | USER } VALUE` on an INSERT.
3601#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3602pub enum Overriding {
3603 /// No `OVERRIDING` clause.
3604 #[default]
3605 None,
3606 /// `OVERRIDING SYSTEM VALUE`.
3607 System,
3608 /// `OVERRIDING USER VALUE`.
3609 User,
3610}
3611
3612/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
3613#[derive(Debug, Clone, PartialEq)]
3614pub struct OnConflictClause {
3615 /// Local columns that identify the conflict (must match a
3616 /// UNIQUE / PRIMARY KEY index on the target table). Empty
3617 /// list means the user wrote `ON CONFLICT DO …` without a
3618 /// target — the engine arbitrates on every unique constraint
3619 /// (round 240).
3620 pub target_columns: Vec<String>,
3621 /// v7.39 (round 240) — the index predicate after the target list
3622 /// (`ON CONFLICT (col) WHERE pred DO …`). PG uses it to infer a
3623 /// PARTIAL unique index; SPG's conflict arbiters are full indexes,
3624 /// which satisfy any predicate, so it is parsed and carried but not
3625 /// consulted (recorded residual: partial-unique-index arbiters).
3626 pub index_where: Option<Expr>,
3627 /// v7.37.17 (17.6 siblings) — `ON CONFLICT ON CONSTRAINT
3628 /// <name>`: the pg_dump conflict-target form. The engine
3629 /// resolves the name to the constraint's columns.
3630 pub constraint_name: Option<String>,
3631 /// v7.39 (round 240) — true when this clause was LOWERED from MySQL's
3632 /// `ON DUPLICATE KEY UPDATE` / `REPLACE INTO`, whose bare-target DO
3633 /// UPDATE is legal (MySQL watches every unique key); PG's own bare
3634 /// `ON CONFLICT DO UPDATE` is refused (42601).
3635 pub mysql_lowered: bool,
3636 /// The action on conflict.
3637 pub action: OnConflictAction,
3638}
3639
3640/// v7.9.7 — action on conflict.
3641#[derive(Debug, Clone, PartialEq)]
3642pub enum OnConflictAction {
3643 /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
3644 /// silently skips conflicting ones.
3645 Nothing,
3646 /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
3647 /// may reference `EXCLUDED.col` to read the incoming row's
3648 /// value (engine wires `EXCLUDED` as a virtual table).
3649 Update {
3650 assignments: Vec<(String, Expr)>,
3651 where_: Option<Expr>,
3652 },
3653}
3654
3655/// v7.39 (round 293, E3 Phase 1) — a row-locking clause.
3656///
3657/// `spg-sql` cannot depend on `spg-engine`, so the strengths and
3658/// policies are spelled again here and mapped at the engine boundary.
3659/// v7.39 — the modes `BEGIN` / `START TRANSACTION` / `SET TRANSACTION`
3660/// / `SET SESSION CHARACTERISTICS` accept. `read_only` used to be parsed
3661/// and dropped on the floor, so `BEGIN READ ONLY` opened an ordinary
3662/// read-write transaction and every write in it was accepted.
3663///
3664/// `None` on either field means the statement did not name that mode, so
3665/// the session default applies — which is not the same as naming the
3666/// default explicitly.
3667#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3668pub struct TransactionModes {
3669 pub isolation: Option<IsolationLevel>,
3670 /// `Some(true)` = READ ONLY, `Some(false)` = READ WRITE.
3671 pub read_only: Option<bool>,
3672}
3673
3674/// v7.39 — what a read-only transaction refuses, and what PG calls it.
3675///
3676/// SPG did not enforce read-only transactions at all: `BEGIN READ ONLY;
3677/// INSERT …` answered `INSERT 0 1` and committed, and
3678/// `default_transaction_read_only = on` changed nothing. Both GUCs were
3679/// in the inventory, so a session could set one, read it back, and be
3680/// told it held a guarantee nothing was enforcing. Applications open
3681/// read-only transactions as a SAFETY measure — a reporting connection,
3682/// a read-only leg in a pool, a "this path must not write" discipline —
3683/// so accepting the writes is the worst possible answer.
3684///
3685/// `Some(tag)` means refuse with PG's message, `cannot execute {tag} in
3686/// a read-only transaction` (SQLSTATE 25006). Every tag below was read
3687/// back from PostgreSQL 18.6 by running the statement inside
3688/// `BEGIN READ ONLY`, one statement per transaction so no error could be
3689/// attributed to the wrong line.
3690///
3691/// Several answers were not what one would guess, which is why they were
3692/// measured rather than reasoned:
3693///
3694/// * `CREATE TEMP TABLE` is REFUSED, tagged `CREATE TABLE`.
3695/// * `NOTIFY`, `LISTEN` and `REINDEX` are ALLOWED.
3696/// * `PREPARE` of an INSERT is ALLOWED — only the EXECUTE writes.
3697/// * `UPDATE … WHERE false`, which changes nothing, is still REFUSED:
3698/// the verb decides, not the row count.
3699/// * `GRANT`, `COMMENT ON` and `SELECT … FOR SHARE` are all REFUSED.
3700///
3701/// The match is exhaustive on purpose. A new statement cannot be added
3702/// without deciding here whether it writes, which is the failure this
3703/// repository keeps meeting: one member of a family gets handled and its
3704/// siblings quietly do not.
3705impl Statement {
3706 #[must_use]
3707 pub fn read_only_violation_tag(&self) -> Option<&'static str> {
3708 match self {
3709 // v7.39.9 — MySQL's RENAME TABLE is DDL, refused read-only
3710 // for the same reason ALTER TABLE … RENAME TO is.
3711 Self::RenameTables(_) => Some("RENAME TABLE"),
3712 // ---- writes rows -------------------------------------------
3713 Self::Insert { .. } => Some("INSERT"),
3714 Self::Update { .. } => Some("UPDATE"),
3715 Self::Delete { .. } => Some("DELETE"),
3716 Self::Merge { .. } => Some("MERGE"),
3717 Self::Truncate { .. } => Some("TRUNCATE TABLE"),
3718 Self::CopyFromFile { .. } => Some("COPY FROM"),
3719
3720 // A SELECT that takes row locks writes lock state, and PG
3721 // names the strength it was asked for.
3722 Self::Select(sel) => sel.locking.as_ref().map(|l| match l.strength {
3723 LockStrength::Update => "SELECT FOR UPDATE",
3724 LockStrength::NoKeyUpdate => "SELECT FOR NO KEY UPDATE",
3725 LockStrength::Share => "SELECT FOR SHARE",
3726 LockStrength::KeyShare => "SELECT FOR KEY SHARE",
3727 }),
3728
3729 // ---- changes the catalog -----------------------------------
3730 Self::CreateTable { .. } => Some("CREATE TABLE"),
3731 Self::DropTable { .. } => Some("DROP TABLE"),
3732 Self::AlterTable { .. } => Some("ALTER TABLE"),
3733 Self::CreateIndex { .. } => Some("CREATE INDEX"),
3734 Self::DropIndex { .. } => Some("DROP INDEX"),
3735 Self::AlterIndex { .. } => Some("ALTER INDEX"),
3736 Self::CreateView { .. } => Some("CREATE VIEW"),
3737 Self::DropView { .. } => Some("DROP VIEW"),
3738 Self::CreateMaterializedView { .. } => Some("CREATE MATERIALIZED VIEW"),
3739 Self::RefreshMaterializedView { .. } => Some("REFRESH MATERIALIZED VIEW"),
3740 Self::DropMaterializedView { .. } => Some("DROP MATERIALIZED VIEW"),
3741 Self::CreateSequence { .. } => Some("CREATE SEQUENCE"),
3742 Self::AlterSequence { .. } => Some("ALTER SEQUENCE"),
3743 Self::DropSequence { .. } => Some("DROP SEQUENCE"),
3744 Self::CreateType { .. } => Some("CREATE TYPE"),
3745 Self::DropType { .. } => Some("DROP TYPE"),
3746 Self::AlterTypeAddValue { .. } | Self::AlterTypeRenameValue { .. } => {
3747 Some("ALTER TYPE")
3748 }
3749 Self::CreateDomain { .. } => Some("CREATE DOMAIN"),
3750 Self::AlterDomain { .. } => Some("ALTER DOMAIN"),
3751 Self::DropDomain { .. } => Some("DROP DOMAIN"),
3752 Self::CreateSchema { .. } => Some("CREATE SCHEMA"),
3753 Self::DropSchema { .. } => Some("DROP SCHEMA"),
3754 Self::CreateFunction { .. } => Some("CREATE FUNCTION"),
3755 Self::DropFunction { .. } => Some("DROP FUNCTION"),
3756 Self::CreateTrigger { .. } => Some("CREATE TRIGGER"),
3757 Self::DropTrigger { .. } => Some("DROP TRIGGER"),
3758 Self::CreateRule { .. } => Some("CREATE RULE"),
3759 Self::DropRule { .. } => Some("DROP RULE"),
3760 Self::CreateExtension { .. } => Some("CREATE EXTENSION"),
3761 Self::CreateStatistics { .. } => Some("CREATE STATISTICS"),
3762 Self::DropStatistics { .. } => Some("DROP STATISTICS"),
3763 Self::DropAggregate { .. } => Some("DROP AGGREGATE"),
3764 Self::CommentOn { .. } => Some("COMMENT"),
3765 Self::DropDatabase { .. } => Some("DROP DATABASE"),
3766 Self::CreatePublication { .. } => Some("CREATE PUBLICATION"),
3767 Self::DropPublication { .. } => Some("DROP PUBLICATION"),
3768 Self::CreateSubscription { .. } => Some("CREATE SUBSCRIPTION"),
3769 Self::DropSubscription { .. } => Some("DROP SUBSCRIPTION"),
3770
3771 // ---- changes roles / permissions ---------------------------
3772 Self::CreateUser { .. } => Some("CREATE ROLE"),
3773 Self::DropUser { .. } => Some("DROP ROLE"),
3774 Self::AlterRolePassword { .. } | Self::SetDbRoleSetting { .. } => Some("ALTER ROLE"),
3775 Self::Grant { .. } => Some("GRANT"),
3776 Self::Revoke { .. } => Some("REVOKE"),
3777 Self::CreatePolicy { .. } => Some("CREATE POLICY"),
3778 Self::AlterPolicy { .. } => Some("ALTER POLICY"),
3779 Self::DropPolicy { .. } => Some("DROP POLICY"),
3780 Self::AlterSystem { .. } => Some("ALTER SYSTEM"),
3781
3782 // ---- SPG's own writers -------------------------------------
3783 // Rewrites cold-tier segments on disk. PG has no equivalent to
3784 // ask, so the test is what it does, not what it is called.
3785 Self::CompactColdSegments => Some("COMPACT COLD SEGMENTS"),
3786
3787 // ---- allowed -----------------------------------------------
3788 // Reads, transaction control, session state, cursors, and the
3789 // maintenance statements PG itself permits. `REINDEX` really is
3790 // allowed in a read-only transaction (measured), which is why
3791 // `Maintain` is here.
3792 //
3793 // `Prepare`, `Execute`, `Call` and `DoBlock` are allowed at
3794 // this level for the reason PG allows them: the write inside
3795 // is refused when it runs, by this same check. Measured:
3796 // `PREPARE p AS INSERT …` succeeds; `DO $$ … INSERT … $$`
3797 // fails with `cannot execute INSERT`.
3798 Self::Explain { .. }
3799 | Self::CopyTo { .. }
3800 | Self::CopyToFile { .. }
3801 | Self::Analyze { .. }
3802 | Self::Maintain { .. }
3803 | Self::Vacuum { .. }
3804 | Self::Begin { .. }
3805 | Self::Commit
3806 | Self::Rollback
3807 | Self::Savepoint { .. }
3808 | Self::RollbackToSavepoint { .. }
3809 | Self::ReleaseSavepoint { .. }
3810 | Self::PrepareTransaction { .. }
3811 | Self::SetTransaction { .. }
3812 | Self::SetConstraints { .. }
3813 | Self::SetParameter { .. }
3814 | Self::SetParameterList { .. }
3815 | Self::SetUserVars { .. }
3816 | Self::SetRole { .. }
3817 | Self::ResetParameter { .. }
3818 | Self::ShowParameter { .. }
3819 | Self::Discard { .. }
3820 | Self::Prepare { .. }
3821 | Self::Execute { .. }
3822 | Self::Deallocate { .. }
3823 | Self::Call { .. }
3824 | Self::DoBlock { .. }
3825 | Self::DeclareCursor { .. }
3826 | Self::FetchCursor { .. }
3827 | Self::MoveCursor { .. }
3828 | Self::CloseCursor { .. }
3829 | Self::Listen { .. }
3830 | Self::Notify { .. }
3831 | Self::Unlisten { .. }
3832 | Self::Kill { .. }
3833 | Self::WaitForWalPosition { .. }
3834 | Self::ValidateOnly { .. }
3835 | Self::NoOpPreventedInTransaction { .. }
3836 | Self::Empty
3837 | Self::ShowTables
3838 | Self::ShowDatabases
3839 | Self::UseDatabase(_)
3840 | Self::ShowCreateTable { .. }
3841 | Self::ShowIndexes { .. }
3842 | Self::ShowStatus
3843 | Self::ShowVariables
3844 | Self::ShowVariablesLike { .. }
3845 | Self::ShowProcesslist
3846 | Self::ShowColumns { .. }
3847 | Self::ShowUsers
3848 | Self::ShowPublications
3849 | Self::ShowSubscriptions => None,
3850 }
3851 }
3852}
3853
3854#[derive(Debug, Clone, PartialEq, Eq)]
3855pub struct LockingClause {
3856 pub strength: LockStrength,
3857 /// `FOR UPDATE OF t1, t2` — empty means every relation in the FROM.
3858 pub of_tables: Vec<String>,
3859 pub policy: LockWait,
3860}
3861
3862/// PG's four tuple-lock strengths, weakest first.
3863#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3864pub enum LockStrength {
3865 KeyShare,
3866 Share,
3867 NoKeyUpdate,
3868 Update,
3869}
3870
3871/// What to do when the row is already locked.
3872#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
3873pub enum LockWait {
3874 /// Block until it is free — PG's default.
3875 #[default]
3876 Wait,
3877 /// `NOWAIT` — fail the statement with 55P03.
3878 NoWait,
3879 /// `SKIP LOCKED` — leave the row out of the result.
3880 SkipLocked,
3881}
3882
3883#[derive(Debug, Clone, PartialEq, Default)]
3884pub struct SelectStatement {
3885 /// v7.39 (round 293, E3 Phase 1) — `FOR UPDATE` and friends. The
3886 /// clause was parsed and DISCARDED since v7.17, so SPG accepted the
3887 /// whole syntax and locked nothing: two workers running the classic
3888 /// `SKIP LOCKED` queue take both took the same row.
3889 /// v7.39 (round 305) — boxed. A locking clause appears on a
3890 /// vanishing fraction of SELECTs, but an inline `Option<LockingClause>`
3891 /// cost every `SelectStatement` 32 bytes, and this struct sits in
3892 /// recursive evaluation frames where the engine already runs close to
3893 /// its stack budget (a 512 KB depth guard is the canary).
3894 pub locking: Option<alloc::boxed::Box<LockingClause>>,
3895 /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
3896 /// expressions, materialised once at query start before the
3897 /// body SELECT runs. Empty for a regular SELECT. Non-recursive
3898 /// only — no `WITH RECURSIVE` for v4.x.
3899 pub ctes: Vec<Cte>,
3900 pub distinct: bool,
3901 /// v7.37.17 (17.6 siblings) — `SELECT DISTINCT ON (exprs)`:
3902 /// keep the first row (per ORDER BY) of each group the
3903 /// expressions define. Empty = no DISTINCT ON.
3904 pub distinct_on: Vec<Expr>,
3905 pub items: Vec<SelectItem>,
3906 pub from: Option<FromClause>,
3907 pub where_: Option<Expr>,
3908 pub group_by: Option<Vec<Expr>>,
3909 /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
3910 /// expands `group_by` to every non-aggregate SELECT-list item
3911 /// before the executor runs. Mutually exclusive with an
3912 /// explicit `group_by` list (the parser sets exactly one).
3913 pub group_by_all: bool,
3914 /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
3915 /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
3916 /// aggregate executor resolves them through the same synthetic
3917 /// schema used for the SELECT items.
3918 pub having: Option<Expr>,
3919 /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
3920 /// itself a `SelectStatement` with `order_by = None` and `limit =
3921 /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
3922 /// top of the chain).
3923 pub unions: Vec<(UnionKind, SelectStatement)>,
3924 /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
3925 /// Keys are matched left-to-right: first key decides, ties break
3926 /// to the second, etc.
3927 pub order_by: Vec<OrderBy>,
3928 /// `LIMIT <n>` — bound on row output. `n` is an integer
3929 /// literal **or** (v7.9.24) a placeholder `$N` resolved
3930 /// against the prepared-statement Bind values. mailrs
3931 /// migration follow-up H2.
3932 pub limit: Option<LimitExpr>,
3933 /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
3934 /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
3935 pub offset: Option<LimitExpr>,
3936 /// v7.17.0 Phase 3.P0-49 — `FETCH FIRST <n> ROWS WITH TIES`
3937 /// (SQL:2008). When true and an ORDER BY is present, the
3938 /// executor extends past the LIMIT-truncated tail to include
3939 /// every row whose ORDER BY key equals the last-kept row's
3940 /// key. Requires an ORDER BY; the executor errors otherwise
3941 /// (matching PG's `WITH TIES` rule). The parser was already
3942 /// accepting `WITH TIES` since Phase 5.1; this field captures
3943 /// the choice so the executor can act on it.
3944 pub limit_with_ties: bool,
3945 /// v7.39 (round 705) — the key expressions of WINDOW-clause definitions
3946 /// that NOTHING referenced. PG analyses every definition whether
3947 /// referenced or not, so `WINDOW w AS (ORDER BY nosuch)` fails there
3948 /// and silently succeeded here — the referenced ones get their columns
3949 /// resolved through the WindowFunction nodes they were inlined into,
3950 /// and the unreferenced ones used to be dropped at parse, unexamined.
3951 /// The engine resolves these with a LIMIT-0 probe of the same FROM.
3952 ///
3953 /// Not part of `Display`: an unreferenced definition has no effect on
3954 /// the result, so a deparsed body (a stored view) omits it.
3955 pub window_check_exprs: Vec<Expr>,
3956}
3957
3958impl Expr {
3959 /// v7.39 (round 305, V23) — hand every `SelectStatement` nested
3960 /// directly inside this expression to `f`. `f` receives each nested
3961 /// statement once; descending further (into that statement's own
3962 /// clauses) is the caller's job, which keeps this walk finite and
3963 /// lets the caller order the recursion.
3964 ///
3965 /// The match is deliberately **wildcard-free**: a new `Expr` variant
3966 /// does not compile until it says whether it can carry a subquery.
3967 /// The row-count resolution pass is built on this, and a shape it
3968 /// silently failed to visit would leave a `LimitExpr::Expr` behind —
3969 /// which every row-count reader would take as "no limit", i.e. the
3970 /// whole table. Compile-time exhaustiveness is what rules that out.
3971 /// Iterative on purpose. Expression trees here get deep (long
3972 /// boolean chains, big IN lists), and this walk is on the path of
3973 /// every statement; recursing would add a frame per node to a stack
3974 /// budget the engine already runs close to — a depth guard that runs
3975 /// on a deliberately small stack caught exactly that. Depth costs
3976 /// heap here instead.
3977 pub fn for_each_subquery_mut<E>(
3978 &mut self,
3979 f: &mut impl FnMut(&mut SelectStatement) -> Result<(), E>,
3980 ) -> Result<(), E> {
3981 let mut stack: Vec<&mut Self> = alloc::vec![self];
3982 while let Some(e) = stack.pop() {
3983 match e {
3984 Self::Literal(_) | Self::Column(_) | Self::Placeholder(_) => {}
3985 Self::NamedArg { expr, .. }
3986 | Self::Collate { expr, .. }
3987 | Self::Variadic(expr)
3988 | Self::Unary { expr, .. }
3989 | Self::Cast { expr, .. }
3990 | Self::FieldAccess { base: expr, .. }
3991 | Self::IsNull { expr, .. }
3992 | Self::BoolTest { expr, .. }
3993 | Self::Extract { source: expr, .. } => stack.push(expr),
3994 Self::Binary { lhs, rhs, .. } => {
3995 stack.push(lhs);
3996 stack.push(rhs);
3997 }
3998 Self::Like { expr, pattern, .. } => {
3999 stack.push(expr);
4000 stack.push(pattern);
4001 }
4002 Self::ArraySubscript { target, index } => {
4003 stack.push(target);
4004 stack.push(index);
4005 }
4006 Self::ArraySlice { target, lo, hi } => {
4007 stack.push(target);
4008 stack.extend(lo.iter_mut().chain(hi.iter_mut()).map(|b| &mut **b));
4009 }
4010 Self::AnyAll { expr, array, .. } => {
4011 stack.push(expr);
4012 stack.push(array);
4013 }
4014 Self::FunctionCall { args, .. } | Self::Array(args) => {
4015 stack.extend(args.iter_mut());
4016 }
4017 Self::AggregateOrdered {
4018 call,
4019 order_by,
4020 filter,
4021 ..
4022 } => {
4023 stack.push(call);
4024 stack.extend(order_by.iter_mut().map(|o| &mut o.expr));
4025 stack.extend(filter.iter_mut().map(|b| &mut **b));
4026 }
4027 Self::WindowFunction {
4028 args,
4029 partition_by,
4030 order_by,
4031 filter,
4032 ..
4033 } => {
4034 // `frame` bounds hold folded numbers / interval
4035 // parts, never expressions — nothing to visit there.
4036 stack.extend(args.iter_mut().chain(partition_by.iter_mut()));
4037 stack.extend(order_by.iter_mut().map(|(e, _, _)| e));
4038 stack.extend(filter.iter_mut().map(|b| &mut **b));
4039 }
4040 Self::InList { expr, list, .. } => {
4041 stack.push(expr);
4042 stack.extend(list.iter_mut());
4043 }
4044 Self::Case {
4045 operand,
4046 branches,
4047 else_branch,
4048 } => {
4049 stack.extend(
4050 operand
4051 .iter_mut()
4052 .chain(else_branch.iter_mut())
4053 .map(|b| &mut **b),
4054 );
4055 for (when, then) in branches.iter_mut() {
4056 stack.push(when);
4057 stack.push(then);
4058 }
4059 }
4060 Self::ScalarSubquery(s) | Self::Exists { subquery: s, .. } => f(s)?,
4061 Self::InSubquery { expr, subquery, .. } => {
4062 stack.push(expr);
4063 f(subquery)?;
4064 }
4065 Self::RowInSubquery { row, subquery, .. }
4066 | Self::RowCmpSubquery { row, subquery, .. } => {
4067 stack.extend(row.iter_mut());
4068 f(subquery)?;
4069 }
4070 }
4071 }
4072 Ok(())
4073 }
4074}
4075
4076/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
4077/// time or a placeholder `$N` resolved during extended-query
4078/// Bind. mailrs migration follow-up H2.
4079///
4080/// v7.39 (round 305) — no longer `Copy`/`Eq`: the `Expr` variant boxes
4081/// an arbitrary row-count expression. Losing `Copy` is deliberate — it
4082/// made the compiler point at every site that used to duplicate a
4083/// row-count out of the AST, which is exactly the set that must not
4084/// bypass the resolution pre-pass.
4085#[derive(Debug, Clone, PartialEq)]
4086pub enum LimitExpr {
4087 /// `LIMIT 10` — value known at parse time.
4088 Literal(u32),
4089 /// `LIMIT $N` — the 1-based parameter index, resolved against
4090 /// the bind values when the prepared statement executes.
4091 Placeholder(u16),
4092 /// v7.39 (round 305, V23) — `LIMIT (SELECT 4)` / `LIMIT
4093 /// greatest(2,3)`: a row-count expression that isn't constant, so
4094 /// it can't be folded at parse time. Evaluated once, before
4095 /// dispatch, by the engine's `resolve_limit_exprs` pre-pass, which
4096 /// rewrites it to `Literal` (or to `None` for a NULL result, PG's
4097 /// "no limit"). **No execution path may see this variant** —
4098 /// `as_literal` would report `None`, which every row-count reader
4099 /// takes to mean "unlimited", i.e. the whole table.
4100 Expr(alloc::boxed::Box<Expr>),
4101}
4102
4103impl fmt::Display for LimitExpr {
4104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4105 match self {
4106 Self::Literal(n) => write!(f, "{n}"),
4107 Self::Placeholder(n) => write!(f, "${n}"),
4108 // Parenthesised so the round-trip text re-parses as one
4109 // row-count expression (`LIMIT (SELECT 4)`), which is also
4110 // the only spelling `FETCH FIRST` accepts.
4111 Self::Expr(e) => write!(f, "({e})"),
4112 }
4113 }
4114}
4115
4116impl LimitExpr {
4117 /// Convenience for the simple-query path where no placeholders
4118 /// can possibly exist. Returns the literal value or `None` if
4119 /// this is a placeholder (caller must surface as Unsupported).
4120 ///
4121 /// v7.39 (round 305) — `None` is read by every row-count consumer as
4122 /// "no limit". An unresolved [`LimitExpr::Expr`] reaching here would
4123 /// therefore silently return the whole table, so the engine's
4124 /// `resolve_limit_exprs` pre-pass rewrites the variant away before
4125 /// dispatch. The assertion makes a missed nesting site fail loudly
4126 /// in every test build rather than quietly widening a result set.
4127 #[must_use]
4128 pub fn as_literal(&self) -> Option<u32> {
4129 match self {
4130 Self::Literal(n) => Some(*n),
4131 Self::Placeholder(_) => None,
4132 Self::Expr(_) => {
4133 debug_assert!(
4134 false,
4135 "LimitExpr::Expr reached execution — resolve_limit_exprs \
4136 missed a nesting site; treating it as `no limit` would \
4137 return every row"
4138 );
4139 None
4140 }
4141 }
4142 }
4143}
4144
4145/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
4146/// the engine's `substitute_placeholders` pass these are
4147/// always Literal; in the simple-query path a Placeholder
4148/// shape returns None (executor surfaces as
4149/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
4150impl SelectStatement {
4151 #[must_use]
4152 pub fn limit_literal(&self) -> Option<u32> {
4153 self.limit.as_ref().and_then(LimitExpr::as_literal)
4154 }
4155 #[must_use]
4156 pub fn offset_literal(&self) -> Option<u32> {
4157 self.offset.as_ref().and_then(LimitExpr::as_literal)
4158 }
4159}
4160
4161#[derive(Debug, Clone, PartialEq)]
4162pub struct Cte {
4163 pub name: String,
4164 /// v7.37.43-T4.4 — body is either a SELECT (read-only CTE, the
4165 /// classical case) or a data-modifying statement
4166 /// (INSERT / UPDATE / DELETE … RETURNING …) per PG writable
4167 /// CTE semantics. The modifying body's RETURNING projection
4168 /// becomes the materialised CTE table the outer query can
4169 /// reference; the modifying statement runs once before the
4170 /// outer query, within the same transaction.
4171 pub body: CteBody,
4172 /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
4173 /// RECURSIVE keyword. Applies to every CTE in the clause per
4174 /// PG semantics. A non-recursive body in a RECURSIVE WITH is
4175 /// allowed; the engine just runs it once.
4176 pub recursive: bool,
4177 /// v4.22: optional `WITH name(a, b, c)` column-name list. When
4178 /// non-empty, these override the body's output column names
4179 /// position-by-position; the engine errors out if the count
4180 /// doesn't match the body's projection width.
4181 pub column_overrides: Vec<String>,
4182 /// v7.38 (read01 U16) — `SEARCH { DEPTH | BREADTH } FIRST BY cols
4183 /// SET seqcol` on a recursive CTE. Desugared at parse time into an
4184 /// extra ordering column on the body (see `rewrite_search_and_cycle`).
4185 pub search: Option<SearchClause>,
4186 /// v7.38 (read01 U16) — `CYCLE cols SET markcol [TO v DEFAULT w]
4187 /// USING pathcol` cycle detection, desugared at parse time.
4188 pub cycle: Option<CycleClause>,
4189}
4190
4191/// v7.38 (read01 U16) — parsed `SEARCH … FIRST BY … SET …` clause.
4192#[derive(Debug, Clone, PartialEq)]
4193pub struct SearchClause {
4194 /// `true` = DEPTH FIRST, `false` = BREADTH FIRST.
4195 pub depth_first: bool,
4196 /// The CTE output columns the search orders by.
4197 pub by_columns: Vec<String>,
4198 /// The new column holding the ordering key (a row-array for depth,
4199 /// a `(depth, keys…)` row for breadth).
4200 pub set_column: String,
4201}
4202
4203/// v7.38 (read01 U16) — parsed `CYCLE … SET … [TO … DEFAULT …] USING …`.
4204#[derive(Debug, Clone, PartialEq)]
4205pub struct CycleClause {
4206 /// Columns whose repetition along a path marks a cycle.
4207 pub columns: Vec<String>,
4208 /// The new boolean-ish column set to `mark_value` on a cycle.
4209 pub mark_column: String,
4210 /// Value written to `mark_column` when a cycle is detected (default
4211 /// `true`); `default_value` otherwise. PG allows any type; SPG carries
4212 /// them as literals.
4213 pub mark_value: Option<Literal>,
4214 pub default_value: Option<Literal>,
4215 /// The new column accumulating the visited-row path array.
4216 pub path_column: String,
4217}
4218
4219/// v7.37.43-T4.4 — CTE body. Read-only (Select) or data-modifying
4220/// (Insert / Update / Delete with optional RETURNING). The
4221/// data-modifying variants must carry a RETURNING projection for the
4222/// outer query to reference the CTE alias by; an empty RETURNING is
4223/// only valid if no outer reference materialises (rare — typically
4224/// caught at planning).
4225#[allow(clippy::large_enum_variant)] // CteBody::Select dominates; Boxing would touch every match site
4226#[derive(Debug, Clone, PartialEq)]
4227pub enum CteBody {
4228 Select(SelectStatement),
4229 Insert(Box<InsertStatement>),
4230 Update(Box<UpdateStatement>),
4231 Delete(Box<DeleteStatement>),
4232 /// v7.39 (read01 round 149) — PG 17 allows MERGE as a
4233 /// data-modifying CTE body (`WITH m AS (MERGE … RETURNING …)`).
4234 Merge(Box<MergeStatement>),
4235}
4236
4237impl CteBody {
4238 /// Convenience accessor used by classical (read-only) CTE
4239 /// callsites that still expect a SELECT body. Returns None for
4240 /// data-modifying CTEs; callers must explicitly route those
4241 /// through `exec_with_ctes`'s modifying branch.
4242 #[must_use]
4243 pub fn as_select(&self) -> Option<&SelectStatement> {
4244 match self {
4245 Self::Select(s) => Some(s),
4246 _ => None,
4247 }
4248 }
4249
4250 #[must_use]
4251 pub fn as_select_mut(&mut self) -> Option<&mut SelectStatement> {
4252 match self {
4253 Self::Select(s) => Some(s),
4254 _ => None,
4255 }
4256 }
4257
4258 #[must_use]
4259 pub fn is_modifying(&self) -> bool {
4260 !matches!(self, Self::Select(_))
4261 }
4262}
4263
4264#[derive(Debug, Clone, PartialEq)]
4265pub struct OrderBy {
4266 pub expr: Expr,
4267 /// `false` = ASC (default), `true` = DESC.
4268 pub desc: bool,
4269 /// v7.24 (mailrs round-16 A) — explicit `NULLS FIRST` /
4270 /// `NULLS LAST`. `None` = PG default (NULLS LAST for ASC,
4271 /// NULLS FIRST for DESC); the engine resolves the effective
4272 /// value via `nulls_first.unwrap_or(desc)`.
4273 pub nulls_first: Option<bool>,
4274 /// v7.39 (round 691) — an explicit `COLLATE` written on this key.
4275 /// It lives here rather than in the expression for the same reason
4276 /// `desc` does: at an ORDER BY key a collation is ordering
4277 /// information, and nothing downstream of the sort needs it. A new
4278 /// `Expr` variant would instead put a new arm on `eval_expr`, which
4279 /// this repo has measured to overflow the debug stack.
4280 ///
4281 /// `None` means none was written, and the key falls back to whatever
4282 /// its COLUMN declares — which is every key that existed before this.
4283 pub collation: Option<String>,
4284}
4285
4286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4287pub enum UnionKind {
4288 /// `UNION` — dedupes the combined set.
4289 Distinct,
4290 /// `UNION ALL` — concatenates without dedup.
4291 All,
4292 /// v7.37.17 (17.6 siblings) — `INTERSECT`: distinct rows
4293 /// present on both sides.
4294 Intersect,
4295 /// `INTERSECT ALL` — multiset intersection (min per-row count).
4296 IntersectAll,
4297 /// `EXCEPT` — distinct left rows absent from the right.
4298 Except,
4299 /// `EXCEPT ALL` — multiset subtraction.
4300 ExceptAll,
4301}
4302
4303#[derive(Debug, Clone, PartialEq)]
4304pub enum SelectItem {
4305 Wildcard,
4306 /// v7.39 (read01 round 128) — qualified wildcard `qualifier.*`: every column
4307 /// of the table / alias `qualifier` (or, in a RETURNING list, the `OLD` /
4308 /// `NEW` pseudo-relation).
4309 QualifiedWildcard(String),
4310 Expr {
4311 expr: Expr,
4312 alias: Option<String>,
4313 },
4314}
4315
4316#[derive(Debug, Clone, PartialEq)]
4317pub struct TableRef {
4318 pub name: String,
4319 pub alias: Option<String>,
4320 /// v7.39 (round 644) — `FROM ONLY t`: do not descend into `t`'s
4321 /// children.
4322 ///
4323 /// The keyword used to be absorbed at parse time, on the reasoning
4324 /// that SPG's inheritance children are separate relations a plain
4325 /// scan does not descend into — so ONLY already described what the
4326 /// scan did. That stopped being true when a partition parent
4327 /// started unioning its children: measured, `SELECT count(*) FROM
4328 /// ONLY <partitioned parent>` answered 2 where PG answers 0.
4329 pub only: bool,
4330 /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
4331 /// When `Some(id)`, the scan restricts to rows that live in
4332 /// segment `<id>` only — useful for forensic inspection of a
4333 /// specific freezer-emitted segment without exposing the hot
4334 /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
4335 /// is STABILITY carve-out for v6.10 — needs the freezer to
4336 /// stamp each segment with a wall-clock at creation time.
4337 pub as_of_segment: Option<u32>,
4338 /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
4339 /// source. When `Some`, `name` is the alias (defaulting to
4340 /// `"unnest"` when no `AS` is given) and the engine builds a
4341 /// synthetic single-column table by evaluating the expression
4342 /// once at SELECT entry. Each TEXT[] element becomes one row;
4343 /// NULL elements become NULL cells. v7.11 supported
4344 /// uncorrelated UNNEST only as the FROM primary; v7.13.2
4345 /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
4346 /// position (cross-join with regular tables).
4347 pub unnest_expr: Option<Box<Expr>>,
4348 /// v7.13.2 — mailrs round-6 S5. PG-standard
4349 /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
4350 /// when non-empty, the first entry overrides the projected
4351 /// column name for the unnested column. Empty = fall back to
4352 /// the table alias (pre-v7.13.2 behaviour).
4353 pub unnest_column_aliases: Vec<String>,
4354 /// `WITH ORDINALITY` on an unnest-channel SRF — when true, the
4355 /// row-stream gains a trailing BIGINT column counting rows
4356 /// from 1 in element order. PG names it `ordinality`; a second
4357 /// entry in the column-alias list renames it.
4358 pub with_ordinality: bool,
4359 /// v7.17.0 Phase 3.10 — `FROM generate_series(start, stop
4360 /// [, step])` set-returning source. When `Some`, the engine
4361 /// materialises a single-column virtual table by stepping
4362 /// `start` to `stop` inclusive. Args are the literal arg list
4363 /// (2 for default-step, 3 for explicit-step). Supports:
4364 /// * SmallInt / Int / BigInt with integer step (default = 1)
4365 /// * Timestamp with INTERVAL step (PG date-range pattern)
4366 /// Mutually exclusive with `unnest_expr` — both populate the
4367 /// same downstream dispatch slot. `name` defaults to
4368 /// `"generate_series"` when no alias is provided.
4369 pub generate_series_args: Option<Vec<Expr>>,
4370 /// v7.17.0 Phase 3.P0-41 — `LATERAL ( SELECT … )` derived
4371 /// table. When `Some`, the TableRef is a parenthesised SELECT
4372 /// that may reference columns from the preceding FROM items
4373 /// (correlated derived table). The executor materialises the
4374 /// subquery per left-row, substituting outer-column references
4375 /// against the current join row's values before running the
4376 /// inner SELECT, then cross-joins the result back.
4377 /// Mutually exclusive with `name` / `unnest_expr` /
4378 /// `generate_series_args`.
4379 pub lateral_subquery: Option<Box<SelectStatement>>,
4380 /// v7.37.43-T4.5 — `jsonb_each_text(<expr>)` set-returning
4381 /// function as a FROM item. PG semantics: for each key/value
4382 /// pair in the JSONB object argument, emit one (key TEXT,
4383 /// value TEXT) row. When prefixed by `LATERAL` and joined via
4384 /// `CROSS JOIN LATERAL`, the argument may reference columns
4385 /// from a preceding FROM item, in which case the executor
4386 /// evaluates `<expr>` per outer row.
4387 /// Mutually exclusive with `unnest_expr` / `generate_series_args`
4388 /// / `lateral_subquery`. The optional `LATERAL` keyword does not
4389 /// require a separate flag — the executor evaluates per-row
4390 /// whenever the join sits in a JoinKind context.
4391 ///
4392 /// v7.37.17 (17.6 siblings) — the tuple's first slot carries the
4393 /// lowercase SRF name (`jsonb_each` / `jsonb_each_text` /
4394 /// `json_each` / `json_each_text`) so the executor picks the
4395 /// value-column rendering (JSON text vs unwrapped text).
4396 pub jsonb_each_text_arg: Option<(String, Box<Expr>)>,
4397 /// v7.39 (read01 partitionfuncs.c) — generic FROM-position table
4398 /// function channel: `(lowercase fn name, args)`. Carries
4399 /// `pg_partition_tree` / `pg_partition_ancestors`; the executor
4400 /// dispatches by name.
4401 pub table_fn_call: Option<Box<(String, Vec<Expr>)>>,
4402 /// v7.39 (read01 round 78) — this FROM item is a call to a function that
4403 /// returns a BASE type, so the item's row type IS that scalar: a whole-row
4404 /// reference to it yields the value, not a one-field composite
4405 /// (`SELECT j FROM jsonb_array_elements('[1]') AS j` → `1`, PG). The
4406 /// desugared shape is indistinguishable from a hand-written
4407 /// `FROM (SELECT unnest(…)) s`, which is a subquery and does NOT collapse —
4408 /// only the parser knows which one it built, so it says so here.
4409 pub scalar_fn_item: bool,
4410 /// v7.39 (read01 round 74) — `ROWS FROM (f(a), g(b))`: N table functions
4411 /// zipped in LOCKSTEP, the shorter padded with NULLs (the same rule the
4412 /// target-list SRFs follow — see round 67). The array-returning family keeps
4413 /// its own lowering; this channel carries the ones that have no array form
4414 /// (`generate_series`, a user `RETURNS SETOF` function).
4415 pub rows_from: Option<Vec<(String, Vec<Expr>)>>,
4416 /// v7.39 (round 205, JSON_TABLE epic) — a `JSON_TABLE(doc, '$path'
4417 /// COLUMNS (...))` FROM item. The doc expr may reference left-side
4418 /// tables (implicit LATERAL, like every SRF channel). Executed by
4419 /// walking the row path over the parsed doc, then each column's
4420 /// path per row-item; NESTED expands as a per-parent outer join.
4421 pub json_table: Option<Box<JsonTable>>,
4422}
4423
4424/// v7.39 (round 205) — a `JSON_TABLE` FROM item.
4425#[derive(Debug, Clone, PartialEq)]
4426pub struct JsonTable {
4427 /// The document expression (jsonb/json/text). May reference outer
4428 /// columns → implicit LATERAL.
4429 pub doc: Box<Expr>,
4430 /// The row-pattern jsonpath (the 2nd JSON_TABLE argument); each
4431 /// match is one row's context item.
4432 pub row_path: String,
4433 /// The COLUMNS list (regular columns, FOR ORDINALITY, NESTED).
4434 pub columns: Vec<JsonTableColumn>,
4435 /// `PASSING <expr> AS <name>` variables, folded into jsonpath `$name`.
4436 pub passing: Vec<(String, Expr)>,
4437}
4438
4439/// v7.39 (round 205) — one entry in a JSON_TABLE (or NESTED) COLUMNS list.
4440#[derive(Debug, Clone, PartialEq)]
4441pub enum JsonTableColumn {
4442 /// `<name> FOR ORDINALITY` — 1-based counter within this level.
4443 Ordinality { name: String },
4444 /// `<name> <type> [FORMAT JSON] PATH '<p>' [WITH WRAPPER]
4445 /// [{DEFAULT <e>|ERROR|NULL} ON EMPTY] [... ON ERROR]`, or
4446 /// `<name> <type> EXISTS [PATH '<p>']`.
4447 Regular {
4448 name: String,
4449 ty: ColumnTypeName,
4450 /// The column jsonpath; defaults to `$.<name>` when `PATH` omitted.
4451 path: String,
4452 /// `EXISTS [PATH …]` — the column is a boolean "did the path match".
4453 exists: bool,
4454 /// `FORMAT JSON` — return the raw jsonb value (not a coerced scalar).
4455 format_json: bool,
4456 /// `WITH [UNCONDITIONAL] WRAPPER` — wrap the result in a json array.
4457 wrapper: bool,
4458 /// Behaviour when the path matches nothing (default NULL).
4459 on_empty: JsonTableOnBehavior,
4460 /// Behaviour when coercion fails (default NULL).
4461 on_error: JsonTableOnBehavior,
4462 },
4463 /// `NESTED PATH '<p>' COLUMNS (...)` — a child level joined per parent
4464 /// row like a LEFT JOIN (a parent with no nested match still emits one
4465 /// row, nested cols NULL).
4466 Nested {
4467 path: String,
4468 columns: Vec<JsonTableColumn>,
4469 },
4470}
4471
4472/// v7.39 (round 205) — a JSON_TABLE column's ON EMPTY / ON ERROR clause.
4473#[derive(Debug, Clone, PartialEq)]
4474pub enum JsonTableOnBehavior {
4475 /// Default: the column value is NULL.
4476 Null,
4477 /// `ERROR ON {EMPTY|ERROR}` — raise PG's error.
4478 Error,
4479 /// `DEFAULT <expr> ON {EMPTY|ERROR}` — the given value.
4480 Default(Box<Expr>),
4481}
4482
4483/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
4484/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
4485/// joins evaluate left-associatively in nested-loop order.
4486#[derive(Debug, Clone, PartialEq)]
4487pub struct FromClause {
4488 pub primary: TableRef,
4489 pub joins: Vec<FromJoin>,
4490}
4491
4492#[derive(Debug, Clone, PartialEq)]
4493pub struct FromJoin {
4494 pub kind: JoinKind,
4495 pub table: TableRef,
4496 /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
4497 pub on: Option<Expr>,
4498 /// v7.37.16 — `JOIN … USING (c1, c2, …)`. When `Some`, records the
4499 /// USING column list so the executor can perform PG's column-merge
4500 /// (the join columns collapse to a single unqualified output column,
4501 /// `t1.c` for INNER/LEFT, `t2.c` for RIGHT, `COALESCE(t1.c,t2.c)` for
4502 /// FULL, and appear first in `SELECT *`). The parser ALSO desugars
4503 /// USING into an equivalent `on` predicate so the join filter/count
4504 /// path works unchanged; `using_cols` drives only the output-shape
4505 /// rewrite. Empty/`None` for `ON` and CROSS joins.
4506 pub using_cols: Option<Vec<String>>,
4507 /// v7.37.16 — `NATURAL [INNER|LEFT|RIGHT|FULL] JOIN`. The common
4508 /// column names are not known until the table schemas are available
4509 /// (parse time is schema-less), so the parser only sets this flag and
4510 /// leaves `on`/`using_cols` empty; the engine resolves the common
4511 /// columns at execution time, synthesises the `on` predicate + the
4512 /// USING column-merge, and clears the flag. If there are no common
4513 /// columns PG treats it as a CROSS join.
4514 pub natural: bool,
4515}
4516
4517#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4518pub enum JoinKind {
4519 Inner,
4520 Left,
4521 Cross,
4522 /// v7.37.16 — `RIGHT [OUTER] JOIN`: keep every right (peer) row,
4523 /// NULL-filling the left (drive) columns on unmatched right rows.
4524 /// The executor runs the LEFT algorithm's mirror: it tracks which
4525 /// peer rows matched and emits the unmatched ones with a NULL-left
4526 /// tuple after the probe loop. Output column order is unchanged
4527 /// (left-table cols then right-table cols).
4528 Right,
4529 /// v7.37.16 — `FULL [OUTER] JOIN`: keep every row from both sides
4530 /// (LEFT-unmatched → NULL right, RIGHT-unmatched → NULL left).
4531 FullOuter,
4532 /// v7.39 (round 725) — SEMI join: each drive row is kept AT MOST
4533 /// once, paired with the first peer row that satisfies the ON. Not
4534 /// reachable from SQL — the EXISTS pull-up emits it, which is what
4535 /// frees positive EXISTS from the round-721 uniqueness gate (an
4536 /// INNER join would multiply the outer rows; a semi join cannot).
4537 Semi,
4538}
4539
4540#[derive(Debug, Clone, PartialEq)]
4541pub enum Expr {
4542 Literal(Literal),
4543 /// v7.39.2 — `<expr> COLLATE <name>`: the collation this expression
4544 /// compares under, whatever the column or the database says.
4545 ///
4546 /// The parser used to refuse the locale names in this position and
4547 /// SILENTLY ABSORB the byte-order ones, so `'a' COLLATE "C" < 'B'`
4548 /// answered `t` where PostgreSQL 18.6 answers `f` — the one family
4549 /// it let through is the one where dropping it changes the answer.
4550 ///
4551 /// Whether dropping is safe depends on the DATABASE's own collation,
4552 /// which the parser cannot see: under `SPG_LC_COLLATE=C` absorbing
4553 /// `COLLATE "C"` is exactly right. So the name rides along and the
4554 /// engine, which knows, decides.
4555 Collate {
4556 expr: Box<Expr>,
4557 collation: String,
4558 },
4559 Column(ColumnName),
4560 /// v7.39 (read01 round 77) — a NAMED call argument (`f(x := 1)`, or the
4561 /// older `f(x => 1)` spelling). Which slot the name fills depends on the
4562 /// callee's declared parameter names, and a user function's live in the
4563 /// catalog — which the parser cannot see. So the name rides along in the
4564 /// tree and the evaluator, which has the catalog, does the reordering.
4565 /// Appears only inside a `FunctionCall`'s argument list.
4566 NamedArg {
4567 name: String,
4568 expr: Box<Expr>,
4569 },
4570 /// v7.39 (read01 round 100) — `VARIADIC <array>` as the last argument of a
4571 /// variadic function call (`concat_ws(',', VARIADIC ARRAY[…])`). The inner
4572 /// expression evaluates to an array whose elements the evaluator splices
4573 /// into the call as individual trailing arguments. Appears only inside a
4574 /// `FunctionCall`'s argument list.
4575 Variadic(Box<Expr>),
4576 /// v6.1.1 — `$N` parameter placeholder for the extended query
4577 /// protocol. The number is 1-based per PostgreSQL convention.
4578 /// Evaluation looks up `params[N-1]` from the prepared-statement
4579 /// bind buffer; out-of-range indices raise a runtime error
4580 /// (same shape as a column-not-found miss).
4581 Placeholder(u16),
4582 Binary {
4583 lhs: Box<Expr>,
4584 op: BinOp,
4585 rhs: Box<Expr>,
4586 },
4587 Unary {
4588 op: UnOp,
4589 expr: Box<Expr>,
4590 },
4591 /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
4592 /// TEXT, BOOL targets; engine coerces at evaluation time.
4593 Cast {
4594 expr: Box<Expr>,
4595 target: CastTarget,
4596 },
4597 /// v7.38 (read01, T9) — composite field access `(expr).field`. `base`
4598 /// evaluates to a composite/record value (an explicit `ROW(...)`, a
4599 /// whole-row reference, or a composite-returning function); `field` names
4600 /// the member (`f1`..`fN` positional for an anonymous ROW, or the base
4601 /// column names for a whole-row). Only the parenthesised form reaches
4602 /// here — a bare `a.b` is parsed as a qualified column reference.
4603 FieldAccess {
4604 base: Box<Expr>,
4605 field: String,
4606 },
4607 /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
4608 IsNull {
4609 expr: Box<Expr>,
4610 negated: bool,
4611 },
4612 /// v7.39 (round 328, V45) — `x IS [NOT] TRUE | FALSE | UNKNOWN`, the
4613 /// three-valued boolean tests. `value` is `Some(true)` for TRUE,
4614 /// `Some(false)` for FALSE and `None` for UNKNOWN.
4615 ///
4616 /// These used to be lowered to `CASE` / `IS NULL` right in the parser.
4617 /// The semantics were right, but the AST then had no way to say what
4618 /// the user wrote, so every renderer printed the lowering:
4619 /// `CHECK ((a > 1) IS TRUE)` came back as
4620 /// `CHECK ((CASE WHEN (a > 1) THEN TRUE ELSE FALSE END))`, and a
4621 /// dumped view lost the form too.
4622 BoolTest {
4623 expr: Box<Expr>,
4624 value: Option<bool>,
4625 negated: bool,
4626 },
4627 /// Function call `name(args...)`. v1.4 supports a small built-in set
4628 /// (length, upper, lower, abs, coalesce); unknown names error at eval
4629 /// time so the parser stays open for v1.5 aggregates.
4630 FunctionCall {
4631 name: String,
4632 args: Vec<Expr>,
4633 },
4634 /// v7.24 (mailrs round-16 A) — an aggregate call with an
4635 /// internal ordering: `array_agg(x ORDER BY y DESC NULLS LAST)`.
4636 /// Wraps the plain [`Expr::FunctionCall`] so every existing
4637 /// FunctionCall consumer stays untouched; only the aggregate
4638 /// executor (and the expression walkers) know the wrapper.
4639 /// Non-aggregate evaluation contexts reject it at eval time.
4640 AggregateOrdered {
4641 call: Box<Expr>,
4642 order_by: Vec<OrderBy>,
4643 /// v7.25 (round-17) — `COUNT(DISTINCT x)` /
4644 /// `string_agg(DISTINCT s, ',')`. The wrapper carries every
4645 /// aggregate modifier so plain FunctionCall stays untouched.
4646 distinct: bool,
4647 /// v7.32 (mailrs round-29) — `agg(args) FILTER (WHERE cond)`.
4648 /// Only the rows where `cond` is true contribute to this
4649 /// aggregate (SQL:2003 T612 / PG 9.4). Carried as a first-class
4650 /// modifier — NOT desugared to `agg(CASE WHEN cond THEN arg
4651 /// END)`, which is faithful for NULL-ignoring aggregates but
4652 /// WRONG for `array_agg` (it would collect a NULL per excluded
4653 /// row). The executor instead skips excluded rows before
4654 /// accumulation, which is correct for every aggregate.
4655 filter: Option<Box<Expr>>,
4656 },
4657 /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
4658 /// wildcards are `%` (any run) and `_` (one char), backslash escapes
4659 /// the next char (so `\%` matches a literal `%`).
4660 Like {
4661 expr: Box<Expr>,
4662 pattern: Box<Expr>,
4663 negated: bool,
4664 /// v7.25 (mailrs round-17) — `ILIKE`: case-insensitive
4665 /// match. PG folds both operands.
4666 case_insensitive: bool,
4667 },
4668 /// v4.12 window function call: `name(args) OVER (PARTITION BY
4669 /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
4670 /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
4671 /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
4672 /// unordered windows and "from start of partition through
4673 /// current row" for ordered windows — no explicit ROWS /
4674 /// RANGE clause in v4.12 MVP.
4675 WindowFunction {
4676 name: String,
4677 args: Vec<Expr>,
4678 partition_by: Vec<Expr>,
4679 /// v7.24.1 — third slot: explicit NULLS FIRST/LAST
4680 /// (None = PG default, same contract as [`OrderBy`]).
4681 order_by: Vec<(
4682 Expr,
4683 bool, /* desc */
4684 Option<bool>, /* nulls_first */
4685 )>,
4686 /// v4.20 explicit frame. `None` means "use the default":
4687 /// whole-partition when unordered, running aggregate from
4688 /// partition start through current row when ordered.
4689 frame: Option<WindowFrame>,
4690 /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
4691 /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
4692 /// `Respect` (PG / ANSI default — NULLs participate). Other
4693 /// window functions ignore this flag.
4694 null_treatment: NullTreatment,
4695 /// v7.37 D.40 — `agg(...) FILTER (WHERE cond) OVER (...)`. `None`
4696 /// = no FILTER. Only aggregate window functions honor it; the
4697 /// predicate restricts which peer rows contribute within the frame.
4698 filter: Option<Box<Expr>>,
4699 },
4700 /// v4.10 scalar subquery — `(SELECT ...)` used in expression
4701 /// position. Must return exactly one row × one column at eval
4702 /// time; the engine errors out otherwise. Uncorrelated only —
4703 /// the inner SELECT cannot reference outer columns.
4704 ScalarSubquery(Box<SelectStatement>),
4705 /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
4706 /// projection is ignored; only row-count matters.
4707 Exists {
4708 subquery: Box<SelectStatement>,
4709 negated: bool,
4710 },
4711 /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
4712 /// project exactly one column; membership is tested by Eq
4713 /// against each row's value (NULL handling follows ANSI:
4714 /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
4715 InSubquery {
4716 expr: Box<Expr>,
4717 subquery: Box<SelectStatement>,
4718 negated: bool,
4719 },
4720 /// `(a, b, …) [NOT] IN (SELECT x, y, …)` — a row constructor tested
4721 /// against a multi-column subquery. Row comparisons against a *list*
4722 /// decompose to OR-of-AND at parse time, but the subquery form can't
4723 /// (its rows are only known at runtime), so this survives as its own
4724 /// node evaluated with PG's row-comparison three-valued logic.
4725 RowInSubquery {
4726 row: Vec<Expr>,
4727 subquery: Box<SelectStatement>,
4728 negated: bool,
4729 },
4730 /// `(a, b, …) <op> (SELECT x, y, …)` — a row constructor compared to a
4731 /// single-row subquery (`=`, `<>`, `<`, `<=`, `>`, `>=`). Like
4732 /// RowInSubquery, the literal-RHS form decomposes at parse time but the
4733 /// subquery form can't, so it survives as its own node. The subquery
4734 /// must yield at most one row (zero → NULL, PG scalar-subquery rule).
4735 RowCmpSubquery {
4736 row: Vec<Expr>,
4737 op: BinOp,
4738 subquery: Box<SelectStatement>,
4739 },
4740 /// v7.30.2 (mailrs round-25) — `expr [NOT] IN (a, b, …)` as a FLAT
4741 /// list. Both the parser's literal-list path and the engine's
4742 /// IN-subquery materialisation used to desugar into a left-deep
4743 /// OR-Eq chain, so expression depth scaled with the element count
4744 /// — a 24k-row subquery result overflowed the 2 MiB worker stack
4745 /// (recursive eval AND recursive Box drop) and aborted embedding
4746 /// host processes. The flat node keeps depth constant: eval is an
4747 /// iterative scan with PG three-valued logic, drop is a Vec drop.
4748 InList {
4749 expr: Box<Expr>,
4750 list: Vec<Expr>,
4751 negated: bool,
4752 },
4753 /// `EXTRACT(<field> FROM <source>)` — pull an integer component
4754 /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
4755 /// because the `FROM` keyword is what separates the two halves,
4756 /// not a comma.
4757 Extract {
4758 field: ExtractField,
4759 source: Box<Expr>,
4760 },
4761 /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
4762 /// element is evaluated independently; NULLs are allowed.
4763 /// v7.10 supports only single-dimension TEXT[] semantically;
4764 /// non-text elements coerce at engine evaluation time when
4765 /// the surrounding context (column type / cast) makes the
4766 /// target clear.
4767 Array(Vec<Expr>),
4768 /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
4769 /// engine returns NULL for out-of-range indices.
4770 ArraySubscript {
4771 target: Box<Expr>,
4772 index: Box<Expr>,
4773 },
4774 /// Array slice `arr[lo:hi]` — PG 1-based, both ends
4775 /// inclusive; a missing bound extends to that end of the
4776 /// array and out-of-range bounds clamp. Returns an array of
4777 /// the same element type.
4778 ArraySlice {
4779 target: Box<Expr>,
4780 lo: Option<Box<Expr>>,
4781 hi: Option<Box<Expr>>,
4782 },
4783 /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
4784 /// operator is the comparison binary op (Eq / Ne / Lt / …);
4785 /// the engine desugars: `ANY` returns true if any element
4786 /// satisfies; `ALL` returns true only if every element does.
4787 /// NULL handling follows PG's three-valued logic.
4788 AnyAll {
4789 expr: Box<Expr>,
4790 op: BinOp,
4791 array: Box<Expr>,
4792 /// `true` = ANY, `false` = ALL.
4793 is_any: bool,
4794 },
4795 /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
4796 /// (searched form, `operand` is None) and
4797 /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
4798 /// `operand` is the lead expression compared against each
4799 /// branch's match). Each `(when_expr, then_expr)` branch
4800 /// stays as written; engine short-circuits on the first match.
4801 /// `else_branch` is `None` when no ELSE; evaluates to NULL.
4802 /// mailrs round-5 G9.
4803 Case {
4804 operand: Option<Box<Expr>>,
4805 branches: Vec<(Expr, Expr)>,
4806 else_branch: Option<Box<Expr>>,
4807 },
4808}
4809
4810/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
4811/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
4812/// in the offset walk. `Ignore` causes the function to skip NULL
4813/// values in the argument expression, returning the next non-NULL.
4814#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4815pub enum NullTreatment {
4816 #[default]
4817 Respect,
4818 Ignore,
4819}
4820
4821/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
4822/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
4823/// where end implicitly = CURRENT ROW.
4824#[derive(Debug, Clone, PartialEq, Eq)]
4825pub struct WindowFrame {
4826 pub kind: FrameKind,
4827 pub start: FrameBound,
4828 pub end: Option<FrameBound>,
4829 /// v7.37 (scout round 12) — `EXCLUDE {CURRENT ROW | GROUP |
4830 /// TIES | NO OTHERS}` frame exclusion. NO OTHERS is the default
4831 /// no-op; CURRENT ROW drops the current row from the frame.
4832 pub exclude: FrameExclusion,
4833}
4834
4835#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
4836pub enum FrameExclusion {
4837 /// Default — exclude nothing.
4838 #[default]
4839 NoOthers,
4840 /// Drop the current row from the frame.
4841 CurrentRow,
4842 /// Drop the current row's whole peer group.
4843 Group,
4844 /// Drop the current row's peers but keep the current row.
4845 Ties,
4846}
4847
4848#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4849pub enum FrameKind {
4850 Rows,
4851 Range,
4852 /// v7.37.19 (19.11) — PG 11+ `GROUPS BETWEEN N PRECEDING AND M
4853 /// FOLLOWING` peer-group frame mode. With UNBOUNDED / CURRENT ROW
4854 /// bounds (no explicit integer offsets) GROUPS behaves identically
4855 /// to RANGE — both consult the peer-group of the current row.
4856 /// Integer offsets are not yet supported; the executor rejects
4857 /// them at run time.
4858 Groups,
4859}
4860
4861#[derive(Debug, Clone, PartialEq, Eq)]
4862pub enum FrameBound {
4863 UnboundedPreceding,
4864 OffsetPreceding(u64),
4865 CurrentRow,
4866 OffsetFollowing(u64),
4867 UnboundedFollowing,
4868 /// `RANGE BETWEEN <interval> PRECEDING …` — value-based offset over a
4869 /// DATE / TIMESTAMP ORDER BY column (PG time-series windows). The
4870 /// interval is folded to its (months, days, micros) components at
4871 /// parse time.
4872 IntervalPreceding {
4873 months: i32,
4874 days: i32,
4875 micros: i64,
4876 },
4877 IntervalFollowing {
4878 months: i32,
4879 days: i32,
4880 micros: i64,
4881 },
4882}
4883
4884impl fmt::Display for FrameBound {
4885 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4886 match self {
4887 Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
4888 Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
4889 Self::CurrentRow => f.write_str("CURRENT ROW"),
4890 Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
4891 Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
4892 Self::IntervalPreceding { .. } => f.write_str("INTERVAL PRECEDING"),
4893 Self::IntervalFollowing { .. } => f.write_str("INTERVAL FOLLOWING"),
4894 }
4895 }
4896}
4897
4898#[derive(Debug, Clone, PartialEq, Eq)]
4899pub enum ExtractField {
4900 Year,
4901 Month,
4902 Day,
4903 Hour,
4904 Minute,
4905 Second,
4906 Microsecond,
4907 /// Seconds since 1970-01-01 00:00:00 UTC (PG returns numeric;
4908 /// SPG keeps the integer convention — truncated seconds).
4909 Epoch,
4910 /// Day of week, 0 = Sunday … 6 = Saturday.
4911 Dow,
4912 /// ISO day of week, 1 = Monday … 7 = Sunday.
4913 Isodow,
4914 /// Day of year, 1-366.
4915 Doy,
4916 /// ISO 8601 week number, 1-53.
4917 Week,
4918 /// ISO 8601 week-numbering year (pairs with `Week`).
4919 Isoyear,
4920 /// Quarter, 1-4.
4921 Quarter,
4922 /// Year divided by 10 (floor).
4923 Decade,
4924 /// Century — 2001-2100 is century 21.
4925 Century,
4926 /// Millennium — 2001-3000 is millennium 3.
4927 Millennium,
4928 /// Julian day number (truncated for timestamps).
4929 Julian,
4930 /// Seconds and fraction in milliseconds (ss·1000 + frac).
4931 Millisecond,
4932 /// UTC offset in seconds — SPG sessions run UTC, so 0.
4933 Timezone,
4934 /// Hour component of the UTC offset — 0.
4935 TimezoneHour,
4936 /// Minute component of the UTC offset — 0.
4937 TimezoneMinute,
4938 /// v7.39 (round 253) — a field name the parser does not know. PG
4939 /// resolves EXTRACT fields at RUNTIME and reports them with the
4940 /// source type (`unit "nosuch" not recognized for type timestamp
4941 /// without time zone`, 22023), so the parser carries the raw name
4942 /// instead of rejecting.
4943 Other(String),
4944}
4945
4946impl fmt::Display for ExtractField {
4947 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4948 f.write_str(match self {
4949 Self::Year => "YEAR",
4950 Self::Month => "MONTH",
4951 Self::Day => "DAY",
4952 Self::Hour => "HOUR",
4953 Self::Minute => "MINUTE",
4954 Self::Second => "SECOND",
4955 Self::Microsecond => "MICROSECOND",
4956 Self::Epoch => "EPOCH",
4957 Self::Dow => "DOW",
4958 Self::Isodow => "ISODOW",
4959 Self::Doy => "DOY",
4960 Self::Week => "WEEK",
4961 Self::Isoyear => "ISOYEAR",
4962 Self::Quarter => "QUARTER",
4963 Self::Decade => "DECADE",
4964 Self::Century => "CENTURY",
4965 Self::Millennium => "MILLENNIUM",
4966 Self::Julian => "JULIAN",
4967 Self::Millisecond => "MILLISECOND",
4968 Self::Timezone => "TIMEZONE",
4969 Self::TimezoneHour => "TIMEZONE_HOUR",
4970 Self::TimezoneMinute => "TIMEZONE_MINUTE",
4971 Self::Other(name) => return f.write_str(name),
4972 })
4973 }
4974}
4975
4976#[derive(Debug, Clone, PartialEq, Eq)]
4977pub enum CastTarget {
4978 Int,
4979 BigInt,
4980 Float,
4981 Text,
4982 Bool,
4983 Vector,
4984 Date,
4985 Timestamp,
4986 /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
4987 /// H3a. Engine reuses the existing runtime-interval / timestamp
4988 /// paths (parse the text input, return the matching Value).
4989 Interval,
4990 Timestamptz,
4991 /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
4992 /// types (v7.9.0); the cast just routes Text→Json with the
4993 /// requested OID for the wire layer.
4994 Json,
4995 Jsonb,
4996 /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
4997 /// compatibility; engine surfaces as Unsupported with a
4998 /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
4999 RegType,
5000 RegClass,
5001 /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
5002 /// the PG external array form `{a,b,NULL}`.
5003 TextArray,
5004 /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
5005 /// `{1,2,3}` or widens a `TextArray` whose elements are
5006 /// integer-shaped.
5007 IntArray,
5008 BigIntArray,
5009 /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
5010 /// external form text representation. Used by pg_dump output
5011 /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
5012 TsVector,
5013 TsQuery,
5014 /// v7.17.0 — `::uuid`. Decodes the LHS Text via
5015 /// `spg_storage::parse_uuid_str` (accepts canonical hyphenated,
5016 /// unhyphenated, uppercase, and brace-wrapped forms); malformed
5017 /// input is a SQL error.
5018 Uuid,
5019 /// v7.18 — `::bytea`. Decodes the LHS Text via PG's hex form
5020 /// (`'\xdeadbeef'`) or escape form (`'\x05\x00'`); Bytes
5021 /// inputs pass through unchanged. Closes the mailrs D-pre #3
5022 /// reverse-acceptance gap — anywhere a PG schema writes
5023 /// `expr::bytea`, SPG now matches.
5024 Bytea,
5025 /// v7.37.5 ship triage — generic cast target for the long tail
5026 /// of PG type names the parser meets in `expr::TYPE` shapes that
5027 /// don't deserve their own enum variant. The engine routes these
5028 /// through `column_type_to_data_type` + the existing typed
5029 /// `coerce_value` dispatch, so adding a new PG type to SPG
5030 /// implicitly adds its cast-target form too — no parser change
5031 /// per type. The string carries the lowercase PG type ident
5032 /// (e.g. `"point"`, `"int4multirange"`); the engine errors with
5033 /// a clear message when the type isn't known.
5034 Named(String),
5035}
5036
5037impl fmt::Display for CastTarget {
5038 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5039 f.write_str(match self {
5040 Self::Int => "int",
5041 Self::BigInt => "bigint",
5042 Self::Float => "float",
5043 Self::Text => "text",
5044 Self::Bool => "bool",
5045 Self::Vector => "vector",
5046 Self::Interval => "interval",
5047 Self::Timestamptz => "timestamptz",
5048 Self::Json => "json",
5049 Self::Jsonb => "jsonb",
5050 Self::RegType => "regtype",
5051 Self::RegClass => "regclass",
5052 Self::Date => "date",
5053 Self::Timestamp => "timestamp",
5054 Self::TextArray => "TEXT[]",
5055 Self::IntArray => "INT[]",
5056 Self::BigIntArray => "BIGINT[]",
5057 Self::TsVector => "tsvector",
5058 Self::TsQuery => "tsquery",
5059 Self::Uuid => "uuid",
5060 Self::Bytea => "bytea",
5061 // v7.37.5 — `Self::Named` carries its own canonical name.
5062 Self::Named(name) => return f.write_str(name),
5063 })
5064 }
5065}
5066
5067#[derive(Debug, Clone, PartialEq)]
5068pub enum Literal {
5069 Integer(i64),
5070 Float(f64),
5071 /// Exact decimal literal — a bare `12.34`-style token, kept as
5072 /// `unscaled / 10^scale` so no precision or trailing-zero scale is lost
5073 /// before it becomes a `Value::Numeric`. PG parses such literals as
5074 /// `numeric`, not `double precision`. (Scientific/huge literals stay
5075 /// `Float`.)
5076 Numeric {
5077 unscaled: i128,
5078 /// v7.39 (round 271) — widened to u16. At u8 a literal with more
5079 /// than 255 decimal places could not be represented, and the
5080 /// conversion's `.expect("lexer-validated decimal")` aborted the
5081 /// query with an internal error on SQL PG accepts.
5082 scale: u16,
5083 },
5084 /// v7.38 (read01, T3.C3) — an exact decimal literal whose mantissa overflows
5085 /// i128 (kept as its source digit string, `[-]digits[.digits]`). Becomes a
5086 /// `Value::NumericBig` at eval; previously such literals fell back to double.
5087 NumericBig(String),
5088 String(String),
5089 /// v7.38.8 — a temporal constant that has already been decoded.
5090 ///
5091 /// Without these the only way to carry one through the AST was as
5092 /// text, and a predicate comparing a `timestamp` column against a
5093 /// literal then coerced that text back into a timestamp ONCE PER
5094 /// ROW — 32 ns of the 52 a comparison cost, measured on a customer
5095 /// profile. `constfold` produced text for the same reason: its exit
5096 /// had nothing else to hand back.
5097 ///
5098 /// `text` keeps the spelling so `Display` round-trips byte for byte,
5099 /// the way `Interval` already does and for the same reason: this
5100 /// node is printed in EXPLAIN, in dumps and in error messages, and
5101 /// none of those should change because the value stopped being
5102 /// carried as a string. The enum already holds a `String` and an
5103 /// `i128`, so neither variant widens it.
5104 Timestamp {
5105 micros: i64,
5106 text: String,
5107 },
5108 /// Days since the epoch `Value::Date` counts from. See
5109 /// [`Literal::Timestamp`].
5110 Date {
5111 days: i32,
5112 text: String,
5113 },
5114 Bool(bool),
5115 Null,
5116 /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
5117 Vector(Vec<f32>),
5118 /// TEXT[] value carried through the prepared-bind path
5119 /// (`= ANY($1)` has no column context to re-parse a `{a,b}`
5120 /// text form, so the array rides the AST natively).
5121 TextArray(Vec<Option<String>>),
5122 /// INT[] value carried through the prepared-bind path.
5123 IntArray(Vec<Option<i32>>),
5124 /// BIGINT[] value carried through the prepared-bind path.
5125 BigIntArray(Vec<Option<i64>>),
5126 /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
5127 /// Three independent dimensions: `months` (variable-length;
5128 /// year/month), `days` (fixed 86400 seconds at non-DST, but
5129 /// preserved as its own dimension so `'1 day'` ≠ `'24 hours'`
5130 /// stays distinguishable), and `micros` (sub-day; can carry).
5131 /// `text` keeps the original spelling so Display round-trips
5132 /// byte-for-byte. v7.37.5 β added the `days` field for PG parity.
5133 Interval {
5134 months: i32,
5135 days: i32,
5136 micros: i64,
5137 text: String,
5138 },
5139}
5140
5141#[derive(Debug, Clone, PartialEq, Eq)]
5142pub struct ColumnName {
5143 pub qualifier: Option<String>,
5144 pub name: String,
5145}
5146
5147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5148pub enum BinOp {
5149 Or,
5150 And,
5151 Eq,
5152 NotEq,
5153 /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
5154 /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
5155 /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
5156 /// non-NULL behaviour matches `<>` / `=` exactly. Common in
5157 /// PG-style JOIN ON predicates and pg_dump output.
5158 IsDistinctFrom,
5159 IsNotDistinctFrom,
5160 /// v7.39 (round 353, M9) — MySQL's `DIV`: integer division that
5161 /// truncates TOWARD ZERO (`-7 DIV 2` is -3, measured on MariaDB 11)
5162 /// and answers NULL on a zero divisor. MySQL-dialect only; `/` there
5163 /// is a real division (round 351).
5164 IntDiv,
5165 Lt,
5166 LtEq,
5167 Gt,
5168 GtEq,
5169 Add,
5170 Sub,
5171 Mul,
5172 Div,
5173 /// v7.37.7 C.1.7 — PG / SQL standard integer modulo. Same
5174 /// precedence as Mul/Div; result type follows left operand.
5175 Mod,
5176 /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
5177 /// operands of equal dimension; engine returns `Value::Float(d)`.
5178 L2Distance,
5179 /// v7.39 (read01 geo_ops.c) — `?||` geometric "is parallel".
5180 GeomParallel,
5181 /// v7.39 (read01 rangetypes.c) — range `&<` / `&>`.
5182 OverLeft,
5183 OverRight,
5184 /// v7.39 (read01 geo_ops.c) — `?-|` geometric "is perpendicular".
5185 GeomPerp,
5186 /// v7.39 (read01 geo_ops.c) — `~=` geometric "same as".
5187 GeomSameAs,
5188 /// v7.39 (read01 geo_ops.c) — `##` closest point on the right-hand
5189 /// object to the left-hand one.
5190 ClosestPoint,
5191 /// v7.39 (read01 geo_ops.c) — `?-` points horizontally aligned.
5192 GeomHoriz,
5193 /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
5194 /// more similar" remains true (matches pgvector's published convention).
5195 InnerProduct,
5196 /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
5197 CosineDistance,
5198 /// SQL string concatenation `||`. NULL propagates.
5199 Concat,
5200 /// Bitwise OR `|` on integers.
5201 BitOr,
5202 /// Bitwise AND `&` on integers.
5203 BitAnd,
5204 /// Bitwise XOR `#` on integers and equal-length bit strings.
5205 BitXor,
5206 /// v7.39 (round 407) — MySQL's logical `XOR` operator. Reads both
5207 /// sides as truth values and returns their exclusive-or (`1 XOR 0`
5208 /// is 1, `1 XOR 1` is 0); NULL on either side yields NULL. Only the
5209 /// MySQL dialect produces it; PG has no logical XOR. Its precedence
5210 /// sits between OR (loosest) and AND.
5211 LogicalXor,
5212 /// v4.14 `json -> key` — element access by string key (object)
5213 /// or integer index (array). Returns a JSON value.
5214 JsonGet,
5215 /// v4.14 `json ->> key` — same access, returns the result as
5216 /// TEXT (unwraps a top-level JSON string; renders other scalars
5217 /// as their canonical text).
5218 JsonGetText,
5219 /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
5220 /// text array literal like `'{a,0,b}'`. Returns JSON.
5221 JsonGetPath,
5222 /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
5223 JsonGetPathText,
5224 /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
5225 /// when every key/value in `sub_json` is structurally present in
5226 /// the left side. Matches PG semantics (top-level + recursive).
5227 JsonContains,
5228 /// `@?` — jsonb path existence (jsonb_path_exists).
5229 JsonPathExists,
5230 /// v7.37.6-A `json <@ sub_json` — contained-by. Returns BOOL;
5231 /// `a <@ b` is defined as `b @> a` (same semantics, swapped
5232 /// sides). Eval dispatch reuses `JsonContains` with swapped args.
5233 JsonContainedBy,
5234 /// v7.37.6-A `json ? key` — key-exists. RHS is TEXT;
5235 /// returns BOOL. For an object, true if `key` is an existing
5236 /// member name; for an array, true if any element is the string
5237 /// `key` (PG semantics).
5238 JsonKeyExists,
5239 /// v7.37.6-A `json ?| keys` — any-key-exists. RHS is TEXT[];
5240 /// returns BOOL.
5241 JsonKeysAny,
5242 /// v7.37.6-A `json ?& keys` — all-keys-exist. RHS is TEXT[];
5243 /// returns BOOL.
5244 JsonKeysAll,
5245 /// `jsonb #- path_text[]` — delete the value at a nested path.
5246 /// RHS is a PG text-array literal like `'{a,b}'`; returns JSONB.
5247 JsonDeletePath,
5248 /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
5249 /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
5250 /// tsvector` and engine eval normalises either ordering.
5251 TsMatch,
5252 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contained-in
5253 /// `<<`. LHS network is strictly inside RHS network (no equality).
5254 InetContainedBy,
5255 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contained-in-or-equal
5256 /// `<<=`. LHS network ⊆ RHS network.
5257 InetContainedByEq,
5258 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR strict contains `>>`.
5259 /// LHS network strictly contains RHS network.
5260 InetContains,
5261 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR contains-or-equal `>>=`.
5262 /// LHS network ⊇ RHS network.
5263 InetContainsEq,
5264 /// v7.17.0 Phase 3.P0-47 — PG INET / CIDR network overlap `&&`.
5265 /// True iff either network contains any address of the other.
5266 InetOverlap,
5267 /// v7.39 (round 508) — `?#`, "do these intersect": box/box, line/box,
5268 /// line/line, lseg/box, lseg/line, lseg/lseg, path/path.
5269 Intersects,
5270 /// v7.39 (round 508) — `<^` / `>^`, strictly below / strictly above
5271 /// (point, box).
5272 IsBelow,
5273 IsAbove,
5274 /// v7.39 (round 508) — the `text_pattern_ops` comparisons `~<~`, `~<=~`,
5275 /// `~>~`, `~>=~`: BYTE order, ignoring collation. `'A' ~<~ 'a'` is true
5276 /// where `'A' < 'a'` is false under a non-C collation, which is the
5277 /// whole reason the operator family exists — it is what makes a LIKE
5278 /// prefix index-usable. pg_dump writes these into index definitions.
5279 PatternLt,
5280 PatternLtEq,
5281 PatternGt,
5282 PatternGtEq,
5283}
5284
5285#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5286pub enum UnOp {
5287 Not,
5288 Neg,
5289 /// Bitwise NOT `~` on integers.
5290 BitNot,
5291 /// v7.39 (round 507) — unary `+`. SPG had no such operator at all:
5292 /// `SELECT +1` parsed only because the lexer reads `+1` as one signed
5293 /// literal, so `+ 1`, `+a`, `+(1)` and `1 + +1` were all syntax errors
5294 /// while PG18 and MariaDB accept every one of them.
5295 ///
5296 /// It is not a no-op to drop at parse time — PG refuses it on
5297 /// non-numeric operands ("operator does not exist: + boolean"), so the
5298 /// operand's type has to be seen at eval.
5299 Plus,
5300}
5301
5302// --- Display impls (round-trip-safe) --------------------------------------
5303
5304impl Statement {
5305 /// v7.18 — classify whether the statement is read-only at
5306 /// engine level. Used by `spg-sqlx`'s `SpgConnection` to
5307 /// route SELECT-shaped traffic through the fan-out
5308 /// `AsyncReadHandle` (no writer-lock contention) while
5309 /// keeping DML / DDL / TX-control on the single-writer path.
5310 ///
5311 /// The classification matches what
5312 /// `Engine::execute_readonly_with_cancel` accepts: anything
5313 /// that does NOT mutate catalog, statistics, session state,
5314 /// or transaction state. WaitForWalPosition is included
5315 /// (engine returns `Unsupported`, but the classification is
5316 /// semantically read-only — no mutation). Empty is excluded
5317 /// out of an abundance of caution — the no-op routes
5318 /// through the writer so any future side effect lands
5319 /// uniformly.
5320 ///
5321 /// **Not connection-state aware**. `SET LOCAL` / `RESET`
5322 /// affect session parameters and must run on the writer
5323 /// engine that owns the session state; they classify as
5324 /// writer-path here. Same for `BEGIN` / `COMMIT` /
5325 /// `ROLLBACK` / `SAVEPOINT` — transaction control is
5326 /// always writer-path.
5327 /// v7.39 (round 435) — does this statement implicitly COMMIT an open
5328 /// transaction under MySQL?
5329 ///
5330 /// PG runs DDL inside the transaction; MySQL commits before (and after)
5331 /// it, so `START TRANSACTION; INSERT …; CREATE TABLE …; ROLLBACK` keeps
5332 /// the INSERT on MySQL and loses it on PG. Measured on MariaDB 11 for
5333 /// CREATE TABLE, ALTER TABLE, DROP TABLE, TRUNCATE, CREATE INDEX and a
5334 /// nested START TRANSACTION; and measured NOT to fire for `CREATE
5335 /// TEMPORARY TABLE`, `SET`, or a SELECT.
5336 ///
5337 /// A positive list, not "everything that is not DML": a statement
5338 /// wrongly listed here commits a client's data early, which is as bad as
5339 /// the divergence it fixes. SPG-only maintenance verbs (VACUUM, DISCARD,
5340 /// COMPACT) are left out — a MySQL session never sends them.
5341 #[must_use]
5342 pub fn mysql_implicit_commit(&self) -> bool {
5343 match self {
5344 // MySQL's documented exception, measured on MariaDB 11: a
5345 // TEMPORARY table is not DDL for this purpose and does not
5346 // commit. (Round 435 got this for free because the parser then
5347 // lowered that spelling to `Statement::Empty`; round 436 made it
5348 // a real CREATE TABLE, and the round-435 pin caught it.)
5349 Self::CreateTable(c) => !c.temporary,
5350 // MySQL commits the open transaction and opens a fresh one.
5351 Self::Begin { .. }
5352 | Self::DropTable { .. }
5353 | Self::DropIndex { .. }
5354 | Self::CreateIndex(_)
5355 | Self::AlterIndex { .. }
5356 | Self::AlterTable(_)
5357 | Self::Truncate { .. }
5358 | Self::Analyze { .. }
5359 | Self::CreateStatistics { .. }
5360 | Self::DropStatistics { .. }
5361 | Self::CreateView { .. }
5362 | Self::DropView { .. }
5363 | Self::CreateMaterializedView { .. }
5364 | Self::RefreshMaterializedView { .. }
5365 | Self::DropMaterializedView { .. }
5366 | Self::CreateSequence(_)
5367 | Self::AlterSequence { .. }
5368 | Self::DropSequence { .. }
5369 | Self::CreateFunction(_)
5370 | Self::DropFunction { .. }
5371 | Self::CreateTrigger(_)
5372 | Self::DropTrigger { .. }
5373 | Self::CreateRule(_)
5374 | Self::DropRule { .. }
5375 | Self::CreateType(_)
5376 | Self::DropType { .. }
5377 | Self::AlterTypeAddValue { .. }
5378 | Self::AlterTypeRenameValue { .. }
5379 | Self::CreateDomain(_)
5380 | Self::AlterDomain { .. }
5381 | Self::DropDomain { .. }
5382 | Self::CreateSchema { .. }
5383 | Self::DropSchema { .. }
5384 | Self::CreateUser { .. }
5385 | Self::DropUser { .. }
5386 | Self::Grant { .. }
5387 | Self::Revoke { .. }
5388 | Self::CreatePolicy(_)
5389 | Self::AlterPolicy(_)
5390 | Self::DropPolicy { .. }
5391 | Self::CommentOn { .. }
5392 | Self::CreateExtension { .. } => true,
5393 _ => false,
5394 }
5395 }
5396
5397 #[must_use]
5398 pub fn is_readonly(&self) -> bool {
5399 match self {
5400 Statement::RenameTables(_) => false,
5401 // v7.39 (round 288) — SET CONSTRAINTS changes transaction
5402 // state, and IMMEDIATE can run the deferred checks there and
5403 // then; writer-path.
5404 Statement::SetConstraints { .. } => false,
5405 // v7.39 (round 695) — it writes nothing (SPG has no
5406 // postgresql.auto.conf), but PG classes ALTER SYSTEM as a
5407 // writer and a read-only session refuses it there too.
5408 Statement::AlterSystem { .. } => false,
5409 // Same shape: a no-op here, a writer to PG, so a read-only
5410 // session refuses it as PG's would.
5411 Statement::NoOpPreventedInTransaction { .. } => false,
5412 Statement::DropDatabase { .. } => false,
5413 // v7.39 (round 696) — they perform nothing, so nothing is
5414 // written; PG classes LOCK and the OWNED BY pair as writers and
5415 // a read-only session refuses them there.
5416 Statement::ValidateOnly { .. } => false,
5417 // v7.39 (round 750) — a credential rotation persists.
5418 Statement::AlterRolePassword { .. } => true,
5419 Statement::DropAggregate { .. } => false,
5420 // v7.39 (round 547) — records a GUC default in the catalog.
5421 Statement::SetDbRoleSetting(_) => false,
5422 // v7.39 (round 535) — REINDEX / CLUSTER rebuild nothing here,
5423 // but they name a relation and PG refuses one that is not
5424 // there, so they are not read-only in the sense this asks.
5425 Statement::Maintain { .. } => false,
5426 // v7.39 (round 277) — the prepared-statement surface is
5427 // session state, like SET; writer-path so it lands on the
5428 // engine that owns the session. EXECUTE may also run a
5429 // write, and its body is only known at execution time.
5430 Statement::Prepare { .. }
5431 | Statement::Execute { .. }
5432 | Statement::Deallocate(_)
5433 | Statement::Call(_)
5434 | Statement::PrepareTransaction(_)
5435 | Statement::CreateStatistics { .. }
5436 | Statement::DropStatistics { .. }
5437 // v7.39 (round 318, V51) — KILL signals another connection;
5438 // it must run on the writer path that owns the registry hook.
5439 | Statement::Kill { .. }
5440 // v7.39 (round 320, V53) — DISCARD throws session state away;
5441 // writer path, like SET / RESET.
5442 | Statement::Discard(_)
5443 // v7.39.2 — `USE <db>` writes session state, the same way
5444 // SET does, and takes the same path.
5445 | Statement::UseDatabase(_) => false,
5446 // v7.39 (round 295, E3 Phase 1b) — a SELECT that asks for row
5447 // locks MUTATES the lock table, so it is not a read. Left as
5448 // a read it went to the read-only executor and the locking
5449 // pre-pass never ran at all — the clause was honoured only
5450 // inside an explicit transaction, and silently ignored in
5451 // autocommit, which is where a queue worker runs it.
5452 Statement::Select(s) if s.locking.is_some() => false,
5453 Statement::Select(_)
5454 | Statement::CopyTo { .. }
5455 | Statement::CopyToFile { .. }
5456 | Statement::Explain(_)
5457 | Statement::ShowTables
5458 | Statement::ShowDatabases
5459 | Statement::ShowCreateTable(_)
5460 | Statement::ShowIndexes(_)
5461 | Statement::ShowStatus
5462 | Statement::ShowVariables
5463 | Statement::ShowVariablesLike(_)
5464 | Statement::ShowProcesslist
5465 | Statement::ShowColumns(_)
5466 | Statement::ShowUsers
5467 | Statement::ShowPublications
5468 | Statement::ShowSubscriptions
5469 | Statement::WaitForWalPosition { .. } => true,
5470 // Everything else mutates catalog, statistics,
5471 // session state, or transaction state — writer path.
5472 // Listed explicitly so a new Statement variant fails
5473 // the match exhaustiveness check and forces a
5474 // classification decision at add-site.
5475 Statement::Empty
5476 // v7.39 (round 169) — VACUUM mutates storage (reclaims
5477 // tombstoned versions): writer path.
5478 | Statement::Vacuum { .. }
5479 | Statement::DropTable { .. }
5480 | Statement::DropIndex { .. }
5481 | Statement::CreateTable(_)
5482 | Statement::CreateExtension(_)
5483 | Statement::DoBlock(_)
5484 | Statement::CreateIndex(_)
5485 | Statement::Insert(_)
5486 | Statement::Update(_)
5487 | Statement::Delete(_)
5488 | Statement::Merge(_)
5489 | Statement::Begin(_)
5490 | Statement::Commit
5491 | Statement::Rollback
5492 | Statement::Savepoint(_)
5493 | Statement::RollbackToSavepoint(_)
5494 | Statement::ReleaseSavepoint(_)
5495 | Statement::CreateUser(_)
5496 | Statement::DropUser { .. }
5497 | Statement::SetRole(_)
5498 | Statement::Grant(_)
5499 | Statement::Revoke(_)
5500 | Statement::CreatePolicy(_)
5501 | Statement::AlterPolicy(_)
5502 | Statement::DropPolicy(_)
5503 | Statement::AlterIndex(_)
5504 | Statement::AlterTable(_)
5505 | Statement::CreatePublication(_)
5506 | Statement::DropPublication { .. }
5507 | Statement::CreateSubscription(_)
5508 | Statement::DropSubscription { .. }
5509 | Statement::Analyze(_)
5510 | Statement::Truncate { .. }
5511 | Statement::CompactColdSegments
5512 | Statement::SetParameter { .. }
5513 | Statement::SetParameterList(_)
5514 | Statement::SetUserVars(..)
5515 | Statement::SetTransaction { .. }
5516 | Statement::ShowParameter(_)
5517 | Statement::ResetParameter(_)
5518 | Statement::CreateFunction(_)
5519 | Statement::CreateTrigger(_)
5520 | Statement::DropTrigger { .. }
5521 | Statement::CreateRule(_)
5522 | Statement::DropRule { .. }
5523 | Statement::DropFunction { .. }
5524 | Statement::CreateSequence(_)
5525 | Statement::AlterSequence(_)
5526 | Statement::DropSequence { .. }
5527 | Statement::CreateView(_)
5528 | Statement::DropView { .. }
5529 | Statement::CreateMaterializedView(_)
5530 | Statement::RefreshMaterializedView { .. }
5531 | Statement::DropMaterializedView { .. }
5532 | Statement::CreateType(_)
5533 | Statement::AlterTypeAddValue { .. }
5534 | Statement::AlterTypeRenameValue { .. }
5535 | Statement::CommentOn { .. }
5536 | Statement::DropType { .. }
5537 | Statement::CreateDomain(_)
5538 | Statement::DropDomain { .. }
5539 | Statement::CreateSchema { .. }
5540 | Statement::DropSchema { .. }
5541 // v7.39 (round 218) — cursors mutate per-session cursor state
5542 // (open/position/close) on the writer engine: writer path.
5543 | Statement::DeclareCursor { .. }
5544 | Statement::FetchCursor { .. }
5545 | Statement::MoveCursor { .. }
5546 | Statement::CloseCursor { .. }
5547 // v7.39 (round 222) — LISTEN/NOTIFY mutate session channel
5548 // state / the notification queue: writer path.
5549 | Statement::Listen(_)
5550 | Statement::Notify { .. }
5551 | Statement::Unlisten(_)
5552 | Statement::CopyFromFile { .. }
5553 | Statement::AlterDomain { .. } => false,
5554 }
5555 }
5556}
5557
5558/// v7.39 (read01 round 57) — a parsed GRANT / REVOKE. The same shape serves
5559/// both; `Statement::Grant` vs `Statement::Revoke` says which way it runs.
5560#[derive(Debug, Clone, PartialEq, Eq)]
5561pub struct GrantStatement {
5562 /// The privileges. EMPTY = `ALL [PRIVILEGES]`. In the role-membership shape
5563 /// (`GRANT devs TO alice`, no ON clause) these words are ROLE NAMES, which
5564 /// is why they keep the case the user typed.
5565 pub privileges: Vec<GrantPriv>,
5566 /// What the privileges are on.
5567 pub object: GrantObject,
5568 /// The roles granted to / revoked from. An empty string entry = PUBLIC.
5569 pub grantees: Vec<String>,
5570 /// GRANT: a trailing `WITH GRANT OPTION`. REVOKE: a leading
5571 /// `GRANT OPTION FOR` (revoke only the right to re-grant, keep the
5572 /// privilege itself).
5573 pub grant_option: bool,
5574}
5575
5576/// v7.39 (read01 round 59) — one privilege in a GRANT, with the optional COLUMN
5577/// list PG allows per privilege: `GRANT SELECT (a, b), INSERT (c) ON t TO dan`.
5578/// An empty column list means the privilege is table-wide.
5579#[derive(Debug, Clone, PartialEq, Eq)]
5580pub struct GrantPriv {
5581 pub word: String,
5582 pub columns: Vec<String>,
5583}
5584
5585/// v7.39 (read01 round 57) — the object a GRANT names. SPG enforces TABLE
5586/// privileges; every other object class parses and is accepted as a no-op, so
5587/// a pg_dump that grants on schemas / sequences / functions still restores.
5588#[derive(Debug, Clone, PartialEq, Eq)]
5589pub enum GrantObject {
5590 /// `ON [TABLE] a, b` — the enforced case.
5591 Tables(Vec<String>),
5592 /// v7.39 (read01 round 58) — `GRANT devs TO alice` / `REVOKE devs FROM
5593 /// alice`: role MEMBERSHIP, which has no ON clause at all. Carries the
5594 /// granted roles; the grantees are the members.
5595 Roles(Vec<String>),
5596 /// v7.39 (read01 round 60) — `ON SEQUENCE a, b`. A sequence's meaningful
5597 /// privileges are SELECT (currval), UPDATE (setval) and USAGE (nextval).
5598 Sequences(Vec<String>),
5599 /// v7.39 (read01 round 60) — `ON SCHEMA public`. USAGE / CREATE.
5600 Schemas(Vec<String>),
5601 /// v7.39 (read01 round 60) — `ON DATABASE app`. CREATE / CONNECT / TEMP.
5602 Databases(Vec<String>),
5603 /// v7.39 (read01 round 61) — `ON FUNCTION f(int)`. The names are bare
5604 /// (SPG keys functions by name); the argument list parses and is dropped.
5605 Functions(Vec<(String, Option<Vec<String>>)>),
5606 /// v7.39 (read01 round 61) — `ON ALL TABLES IN SCHEMA public`: expands to
5607 /// every table at GRANT time, exactly like PG.
5608 AllTablesInSchema,
5609 /// `ON TYPE / LANGUAGE / …`. Carries the object-class word for the no-op
5610 /// message.
5611 Other(String),
5612}
5613
5614impl GrantStatement {
5615 /// Round-trip text. `grant = false` renders the REVOKE form.
5616 fn render(&self, grant: bool) -> alloc::string::String {
5617 use core::fmt::Write as _;
5618 let mut s = alloc::string::String::new();
5619 let privs = if self.privileges.is_empty() {
5620 alloc::string::String::from("ALL")
5621 } else {
5622 let parts: Vec<_> = self
5623 .privileges
5624 .iter()
5625 .map(|p| {
5626 if p.columns.is_empty() {
5627 p.word.clone()
5628 } else {
5629 let cols: Vec<_> = p.columns.iter().map(|c| quote_ident(c)).collect();
5630 alloc::format!("{} ({})", p.word, cols.join(", "))
5631 }
5632 })
5633 .collect();
5634 parts.join(", ")
5635 };
5636 let obj = match &self.object {
5637 GrantObject::Tables(t) => {
5638 let names: Vec<_> = t.iter().map(|n| quote_ident(n)).collect();
5639 alloc::format!("TABLE {}", names.join(", "))
5640 }
5641 GrantObject::Roles(r) => {
5642 let names: Vec<_> = r.iter().map(|n| quote_ident(n)).collect();
5643 names.join(", ")
5644 }
5645 GrantObject::Sequences(n) => {
5646 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5647 alloc::format!("SEQUENCE {}", names.join(", "))
5648 }
5649 GrantObject::Schemas(n) => {
5650 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5651 alloc::format!("SCHEMA {}", names.join(", "))
5652 }
5653 GrantObject::Databases(n) => {
5654 let names: Vec<_> = n.iter().map(|x| quote_ident(x)).collect();
5655 alloc::format!("DATABASE {}", names.join(", "))
5656 }
5657 GrantObject::Functions(n) => {
5658 let names: Vec<_> = n
5659 .iter()
5660 .map(|(name, args)| match args {
5661 Some(a) => alloc::format!("{}({})", quote_ident(name), a.join(", ")),
5662 None => quote_ident(name),
5663 })
5664 .collect();
5665 alloc::format!("FUNCTION {}", names.join(", "))
5666 }
5667 GrantObject::AllTablesInSchema => "ALL TABLES IN SCHEMA public".into(),
5668 GrantObject::Other(k) => k.clone(),
5669 };
5670 let who: Vec<_> = self
5671 .grantees
5672 .iter()
5673 .map(|g| {
5674 if g.is_empty() {
5675 "PUBLIC".into()
5676 } else {
5677 quote_ident(g)
5678 }
5679 })
5680 .collect();
5681 if let GrantObject::Roles(_) = &self.object {
5682 let _ = if grant {
5683 write!(s, "GRANT {obj} TO {}", who.join(", "))
5684 } else {
5685 write!(s, "REVOKE {obj} FROM {}", who.join(", "))
5686 };
5687 return s;
5688 }
5689 if grant {
5690 let _ = write!(s, "GRANT {privs} ON {obj} TO {}", who.join(", "));
5691 if self.grant_option {
5692 s.push_str(" WITH GRANT OPTION");
5693 }
5694 } else {
5695 s.push_str("REVOKE ");
5696 if self.grant_option {
5697 s.push_str("GRANT OPTION FOR ");
5698 }
5699 let _ = write!(s, "{privs} ON {obj} FROM {}", who.join(", "));
5700 }
5701 s
5702 }
5703}
5704
5705impl fmt::Display for Statement {
5706 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5707 match self {
5708 Self::Empty => Ok(()),
5709 // v7.39 (round 695) — deparsed the way PG writes it.
5710 // v7.39 (round 696) — never deparsed into a dump (nothing is
5711 // stored), so the shortest faithful spelling of what it was.
5712 Self::DropAggregate { if_exists, items } => {
5713 f.write_str("DROP AGGREGATE ")?;
5714 if *if_exists {
5715 f.write_str("IF EXISTS ")?;
5716 }
5717 for (i, (name, args)) in items.iter().enumerate() {
5718 if i > 0 {
5719 f.write_str(", ")?;
5720 }
5721 match args {
5722 Some(a) => write!(f, "{name}({})", a.join(", "))?,
5723 None => write!(f, "{name}(*)")?,
5724 }
5725 }
5726 Ok(())
5727 }
5728 Self::AlterRolePassword { name, password } => {
5729 write!(f, "ALTER ROLE {}", quote_ident(name))?;
5730 match password {
5731 Some(_) => f.write_str(" PASSWORD '<redacted>'"),
5732 None => f.write_str(" PASSWORD NULL"),
5733 }
5734 }
5735 Self::ValidateOnly { kind, names } => match kind {
5736 ValidateOnlyKind::LockTable => write!(f, "LOCK TABLE {}", names.join(", ")),
5737 ValidateOnlyKind::RoleName => {
5738 write!(f, "DROP OWNED BY {}", names.join(", "))
5739 }
5740 ValidateOnlyKind::SecurityLabel => f.write_str("SECURITY LABEL"),
5741 ValidateOnlyKind::ExtensionAvailable => {
5742 write!(f, "CREATE EXTENSION {}", names.join(", "))
5743 }
5744 ValidateOnlyKind::ForeignInfra => f.write_str("CREATE SERVER"),
5745 ValidateOnlyKind::CollationName => {
5746 write!(f, "DROP COLLATION {}", names.join(", "))
5747 }
5748 ValidateOnlyKind::TsConfigName => {
5749 write!(f, "DROP TEXT SEARCH CONFIGURATION {}", names.join(", "))
5750 }
5751 ValidateOnlyKind::EventTriggerName => {
5752 write!(f, "DROP EVENT TRIGGER {}", names.join(", "))
5753 }
5754 ValidateOnlyKind::TablespaceName => {
5755 write!(f, "DROP TABLESPACE {}", names.join(", "))
5756 }
5757 ValidateOnlyKind::LargeObjectOid => {
5758 write!(f, "ALTER LARGE OBJECT {}", names.join(", "))
5759 }
5760 ValidateOnlyKind::TypeName => write!(f, "ALTER TYPE {}", names.join(", ")),
5761 ValidateOnlyKind::AggregateName => {
5762 write!(f, "ALTER AGGREGATE {}", names.join(", "))
5763 }
5764 ValidateOnlyKind::ConversionName => {
5765 write!(f, "DROP CONVERSION {}", names.join(", "))
5766 }
5767 ValidateOnlyKind::LanguageName => {
5768 write!(f, "DROP LANGUAGE {}", names.join(", "))
5769 }
5770 ValidateOnlyKind::ExtensionInstalled => {
5771 write!(f, "DROP EXTENSION {}", names.join(", "))
5772 }
5773 },
5774 Self::AlterSystem { parameter } => match parameter {
5775 Some(p) => write!(f, "ALTER SYSTEM RESET {p}"),
5776 None => f.write_str("ALTER SYSTEM RESET ALL"),
5777 },
5778 // v7.39 (round 547) — round-trips as PG writes it.
5779 Self::SetDbRoleSetting(st) => {
5780 match (&st.database, &st.role) {
5781 (Some(d), None) => write!(f, "ALTER DATABASE {d}")?,
5782 (_, Some(r)) => write!(f, "ALTER ROLE {r}")?,
5783 (None, None) => f.write_str("ALTER ROLE ALL")?,
5784 }
5785 if let (Some(d), Some(_)) = (&st.database, &st.role) {
5786 write!(f, " IN DATABASE {d}")?;
5787 }
5788 match (&st.param, &st.value) {
5789 (None, _) => f.write_str(" RESET ALL"),
5790 (Some(p), None) => write!(f, " RESET {p}"),
5791 (Some(p), Some(v)) => write!(f, " SET {p} = '{v}'"),
5792 }
5793 }
5794 Self::Maintain {
5795 kind,
5796 concurrently,
5797 target,
5798 } => {
5799 f.write_str(match kind {
5800 crate::ast::MaintainKind::ClusterRelation => "CLUSTER ",
5801 _ => "REINDEX ",
5802 })?;
5803 if *concurrently {
5804 f.write_str("CONCURRENTLY ")?;
5805 }
5806 if let Some(t) = target {
5807 f.write_str(t)?;
5808 }
5809 Ok(())
5810 }
5811 Self::DropDatabase { name, if_exists } => {
5812 f.write_str("DROP DATABASE ")?;
5813 if *if_exists {
5814 f.write_str("IF EXISTS ")?;
5815 }
5816 f.write_str(name)
5817 }
5818 Self::NoOpPreventedInTransaction { what, .. } => f.write_str(what),
5819 Self::SetConstraints { names, deferred } => {
5820 f.write_str("SET CONSTRAINTS ")?;
5821 if names.is_empty() {
5822 f.write_str("ALL")?;
5823 } else {
5824 for (i, n) in names.iter().enumerate() {
5825 if i > 0 {
5826 f.write_str(", ")?;
5827 }
5828 f.write_str(n)?;
5829 }
5830 }
5831 f.write_str(if *deferred { " DEFERRED" } else { " IMMEDIATE" })
5832 }
5833 // v7.39 (round 277) — the source text is kept verbatim so
5834 // `pg_prepared_statements.statement` can report it the way
5835 // PG does (the whole PREPARE statement, not just the body).
5836 Self::Prepare { source, .. } => f.write_str(source),
5837 Self::Execute { name, args } => {
5838 write!(f, "EXECUTE {}", quote_ident(name))?;
5839 if !args.is_empty() {
5840 f.write_str("(")?;
5841 for (i, a) in args.iter().enumerate() {
5842 if i > 0 {
5843 f.write_str(", ")?;
5844 }
5845 write!(f, "{a}")?;
5846 }
5847 f.write_str(")")?;
5848 }
5849 Ok(())
5850 }
5851 Self::CreateStatistics {
5852 name,
5853 if_not_exists,
5854 kinds,
5855 columns,
5856 table,
5857 } => {
5858 f.write_str("CREATE STATISTICS ")?;
5859 if *if_not_exists {
5860 f.write_str("IF NOT EXISTS ")?;
5861 }
5862 write!(f, "{}", quote_ident(name))?;
5863 if !kinds.is_empty() {
5864 write!(f, " ({})", kinds.join(", "))?;
5865 }
5866 write!(f, " ON {} FROM {}", columns.join(", "), quote_ident(table))
5867 }
5868 Self::DropStatistics { name, if_exists } => {
5869 f.write_str("DROP STATISTICS ")?;
5870 if *if_exists {
5871 f.write_str("IF EXISTS ")?;
5872 }
5873 write!(f, "{}", quote_ident(name))
5874 }
5875 Self::Call(n) => write!(f, "CALL {}()", quote_ident(n)),
5876 Self::PrepareTransaction(gid) => write!(f, "PREPARE TRANSACTION '{gid}'"),
5877 Self::Deallocate(None) => f.write_str("DEALLOCATE ALL"),
5878 Self::Deallocate(Some(n)) => write!(f, "DEALLOCATE {}", quote_ident(n)),
5879 Self::DeclareCursor {
5880 name,
5881 scroll,
5882 hold,
5883 query,
5884 } => {
5885 write!(f, "DECLARE {} ", quote_ident(name))?;
5886 match scroll {
5887 Some(true) => f.write_str("SCROLL ")?,
5888 Some(false) => f.write_str("NO SCROLL ")?,
5889 None => {}
5890 }
5891 f.write_str("CURSOR ")?;
5892 if *hold {
5893 f.write_str("WITH HOLD ")?;
5894 }
5895 write!(f, "FOR {query}")
5896 }
5897 Self::FetchCursor { name, direction } => {
5898 write!(f, "FETCH {direction} FROM {}", quote_ident(name))
5899 }
5900 Self::MoveCursor { name, direction } => {
5901 write!(f, "MOVE {direction} FROM {}", quote_ident(name))
5902 }
5903 Self::CloseCursor { name } => match name {
5904 Some(n) => write!(f, "CLOSE {}", quote_ident(n)),
5905 None => f.write_str("CLOSE ALL"),
5906 },
5907 Self::Listen(ch) => write!(f, "LISTEN {}", quote_ident(ch)),
5908 Self::Notify { channel, payload } => {
5909 write!(f, "NOTIFY {}", quote_ident(channel))?;
5910 if let Some(p) = payload {
5911 write!(f, ", '{}'", p.replace('\'', "''"))?;
5912 }
5913 Ok(())
5914 }
5915 Self::Unlisten(ch) => match ch {
5916 Some(c) => write!(f, "UNLISTEN {}", quote_ident(c)),
5917 None => f.write_str("UNLISTEN *"),
5918 },
5919 Self::CopyTo {
5920 table,
5921 columns,
5922 query,
5923 options,
5924 } => {
5925 if let Some(q) = query {
5926 write!(f, "COPY ({q})")?;
5927 } else {
5928 write!(f, "COPY {table}")?;
5929 if let Some(cols) = columns {
5930 write!(f, " ({})", cols.join(", "))?;
5931 }
5932 }
5933 write!(f, " TO STDOUT")?;
5934 let mut parts: Vec<String> = Vec::new();
5935 if options.format == CopyFormat::Csv {
5936 parts.push("FORMAT csv".to_string());
5937 }
5938 if options.header {
5939 parts.push("HEADER true".to_string());
5940 }
5941 if let Some(d) = options.delimiter {
5942 parts.push(alloc::format!("DELIMITER '{d}'"));
5943 }
5944 if let Some(n) = &options.null_str {
5945 parts.push(alloc::format!("NULL '{n}'"));
5946 }
5947 if let Some(q) = options.quote {
5948 parts.push(alloc::format!("QUOTE '{q}'"));
5949 }
5950 if !parts.is_empty() {
5951 write!(f, " WITH ({})", parts.join(", "))?;
5952 }
5953 Ok(())
5954 }
5955 Self::CopyFromFile {
5956 table,
5957 columns,
5958 path,
5959 options,
5960 } => {
5961 write!(f, "COPY {table}")?;
5962 if let Some(cols) = columns {
5963 write!(f, " ({})", cols.join(", "))?;
5964 }
5965 write!(f, " FROM '{path}'")?;
5966 let mut parts: Vec<String> = Vec::new();
5967 if options.format == CopyFormat::Csv {
5968 parts.push("FORMAT csv".to_string());
5969 }
5970 if options.header {
5971 parts.push("HEADER true".to_string());
5972 }
5973 if let Some(d) = options.delimiter {
5974 parts.push(alloc::format!("DELIMITER '{d}'"));
5975 }
5976 if let Some(n) = &options.null_str {
5977 parts.push(alloc::format!("NULL '{n}'"));
5978 }
5979 if let Some(q) = options.quote {
5980 parts.push(alloc::format!("QUOTE '{q}'"));
5981 }
5982 if !parts.is_empty() {
5983 write!(f, " WITH ({})", parts.join(", "))?;
5984 }
5985 Ok(())
5986 }
5987 Self::CopyToFile {
5988 table,
5989 columns,
5990 query,
5991 path,
5992 options,
5993 } => {
5994 if let Some(q) = query {
5995 write!(f, "COPY ({q})")?;
5996 } else {
5997 write!(f, "COPY {table}")?;
5998 if let Some(cols) = columns {
5999 write!(f, " ({})", cols.join(", "))?;
6000 }
6001 }
6002 write!(f, " TO '{path}'")?;
6003 let mut parts: Vec<String> = Vec::new();
6004 if options.format == CopyFormat::Csv {
6005 parts.push("FORMAT csv".to_string());
6006 }
6007 if options.header {
6008 parts.push("HEADER true".to_string());
6009 }
6010 if let Some(d) = options.delimiter {
6011 parts.push(alloc::format!("DELIMITER '{d}'"));
6012 }
6013 if let Some(n) = &options.null_str {
6014 parts.push(alloc::format!("NULL '{n}'"));
6015 }
6016 if let Some(q) = options.quote {
6017 parts.push(alloc::format!("QUOTE '{q}'"));
6018 }
6019 if !parts.is_empty() {
6020 write!(f, " WITH ({})", parts.join(", "))?;
6021 }
6022 Ok(())
6023 }
6024 Self::AlterDomain { name, action } => {
6025 write!(f, "ALTER DOMAIN {name} ")?;
6026 match action {
6027 AlterDomainAction::AddConstraint { name: cn, check } => match cn {
6028 Some(cn) => write!(f, "ADD CONSTRAINT {cn} CHECK ({check})"),
6029 None => write!(f, "ADD CHECK ({check})"),
6030 },
6031 AlterDomainAction::DropConstraint {
6032 name: cn,
6033 if_exists,
6034 } => {
6035 if *if_exists {
6036 write!(f, "DROP CONSTRAINT IF EXISTS {cn}")
6037 } else {
6038 write!(f, "DROP CONSTRAINT {cn}")
6039 }
6040 }
6041 AlterDomainAction::SetDefault(e) => write!(f, "SET DEFAULT {e}"),
6042 AlterDomainAction::DropDefault => f.write_str("DROP DEFAULT"),
6043 AlterDomainAction::SetNotNull => f.write_str("SET NOT NULL"),
6044 AlterDomainAction::DropNotNull => f.write_str("DROP NOT NULL"),
6045 AlterDomainAction::RenameTo(n) => write!(f, "RENAME TO {n}"),
6046 }
6047 }
6048 Self::Truncate {
6049 tables,
6050 restart_identity,
6051 cascade,
6052 only,
6053 } => {
6054 f.write_str("TRUNCATE TABLE ")?;
6055 if *only {
6056 f.write_str("ONLY ")?;
6057 }
6058 for (i, t) in tables.iter().enumerate() {
6059 if i > 0 {
6060 f.write_str(", ")?;
6061 }
6062 f.write_str(t)?;
6063 }
6064 if *restart_identity {
6065 f.write_str(" RESTART IDENTITY")?;
6066 }
6067 if *cascade {
6068 f.write_str(" CASCADE")?;
6069 }
6070 Ok(())
6071 }
6072 Self::DropTable { names, if_exists } => {
6073 f.write_str("DROP TABLE ")?;
6074 if *if_exists {
6075 f.write_str("IF EXISTS ")?;
6076 }
6077 for (i, n) in names.iter().enumerate() {
6078 if i > 0 {
6079 f.write_str(", ")?;
6080 }
6081 write!(f, "{}", quote_ident(n))?;
6082 }
6083 Ok(())
6084 }
6085 Self::DropIndex {
6086 name,
6087 if_exists,
6088 table,
6089 } => {
6090 f.write_str("DROP INDEX ")?;
6091 if *if_exists {
6092 f.write_str("IF EXISTS ")?;
6093 }
6094 write!(f, "{}", quote_ident(name))?;
6095 if let Some(t) = table {
6096 write!(f, " ON {}", quote_ident(t))?;
6097 }
6098 Ok(())
6099 }
6100 Self::Select(s) => s.fmt(f),
6101 Self::CreateTable(s) => s.fmt(f),
6102 Self::CreateIndex(s) => s.fmt(f),
6103 Self::Insert(s) => s.fmt(f),
6104 Self::Update(s) => s.fmt(f),
6105 Self::Delete(s) => s.fmt(f),
6106 Self::Merge(s) => s.fmt(f),
6107 Self::Vacuum { table, analyze } => {
6108 f.write_str("VACUUM")?;
6109 if *analyze {
6110 f.write_str(" ANALYZE")?;
6111 }
6112 if let Some(t) = table {
6113 write!(f, " {}", quote_ident(t))?;
6114 }
6115 Ok(())
6116 }
6117 Self::Begin(modes) => {
6118 f.write_str("BEGIN")?;
6119 if let Some(level) = modes.isolation {
6120 write!(f, " ISOLATION LEVEL {level}")?;
6121 }
6122 match modes.read_only {
6123 Some(true) => f.write_str(" READ ONLY")?,
6124 Some(false) => f.write_str(" READ WRITE")?,
6125 None => {}
6126 }
6127 Ok(())
6128 }
6129 Self::Commit => f.write_str("COMMIT"),
6130 Self::Rollback => f.write_str("ROLLBACK"),
6131 Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
6132 Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
6133 Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
6134 Self::ShowTables => f.write_str("SHOW TABLES"),
6135 Self::ShowDatabases => f.write_str("SHOW DATABASES"),
6136 Self::UseDatabase(n) => write!(f, "USE {}", quote_ident(n)),
6137 Self::ShowCreateTable(t) => write!(f, "SHOW CREATE TABLE {}", quote_ident(t)),
6138 Self::ShowIndexes(t) => write!(f, "SHOW INDEXES FROM {}", quote_ident(t)),
6139 Self::ShowStatus => f.write_str("SHOW STATUS"),
6140 Self::ShowVariables => f.write_str("SHOW VARIABLES"),
6141 Self::ShowVariablesLike(p) => {
6142 write!(f, "SHOW VARIABLES LIKE '{}'", p.replace('\'', "''"))
6143 }
6144 Self::ShowProcesslist => f.write_str("SHOW PROCESSLIST"),
6145 Self::Discard(t) => write!(f, "DISCARD {t}"),
6146 Self::Kill { query_only, id } => {
6147 if *query_only {
6148 write!(f, "KILL QUERY {id}")
6149 } else {
6150 write!(f, "KILL CONNECTION {id}")
6151 }
6152 }
6153 Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
6154 Self::CreateUser(s) => write!(
6155 f,
6156 "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
6157 quote_ident(&s.name),
6158 s.role
6159 ),
6160 Self::DropUser { name, if_exists } => {
6161 let ie = if *if_exists { "IF EXISTS " } else { "" };
6162 write!(f, "DROP USER {ie}{}", quote_ident(name))
6163 }
6164 Self::SetRole(Some(r)) => write!(f, "SET ROLE {}", quote_ident(r)),
6165 Self::SetRole(None) => f.write_str("RESET ROLE"),
6166 Self::Grant(g) => write!(f, "{}", g.render(true)),
6167 Self::Revoke(g) => write!(f, "{}", g.render(false)),
6168 Self::CreatePolicy(s) => {
6169 write!(
6170 f,
6171 "CREATE POLICY {} ON {}",
6172 quote_ident(&s.name),
6173 quote_ident(&s.table)
6174 )?;
6175 if !s.permissive {
6176 f.write_str(" AS RESTRICTIVE")?;
6177 }
6178 if !matches!(s.cmd, PolicyCmd::All) {
6179 let w = match s.cmd {
6180 PolicyCmd::Select => "SELECT",
6181 PolicyCmd::Insert => "INSERT",
6182 PolicyCmd::Update => "UPDATE",
6183 PolicyCmd::Delete => "DELETE",
6184 PolicyCmd::All => unreachable!(),
6185 };
6186 write!(f, " FOR {w}")?;
6187 }
6188 if !s.roles.is_empty() {
6189 write!(f, " TO {}", s.roles.join(", "))?;
6190 }
6191 if let Some(u) = &s.using {
6192 write!(f, " USING ({u})")?;
6193 }
6194 if let Some(c) = &s.with_check {
6195 write!(f, " WITH CHECK ({c})")?;
6196 }
6197 Ok(())
6198 }
6199 Self::AlterPolicy(s) => {
6200 write!(
6201 f,
6202 "ALTER POLICY {} ON {}",
6203 quote_ident(&s.name),
6204 quote_ident(&s.table)
6205 )?;
6206 if let Some(nn) = &s.rename_to {
6207 return write!(f, " RENAME TO {}", quote_ident(nn));
6208 }
6209 if let Some(roles) = &s.roles {
6210 write!(f, " TO {}", roles.join(", "))?;
6211 }
6212 if let Some(u) = &s.using {
6213 write!(f, " USING ({u})")?;
6214 }
6215 if let Some(c) = &s.with_check {
6216 write!(f, " WITH CHECK ({c})")?;
6217 }
6218 Ok(())
6219 }
6220 Self::DropPolicy(s) => {
6221 f.write_str("DROP POLICY ")?;
6222 if s.if_exists {
6223 f.write_str("IF EXISTS ")?;
6224 }
6225 write!(f, "{} ON {}", quote_ident(&s.name), quote_ident(&s.table))
6226 }
6227 Self::ShowUsers => f.write_str("SHOW USERS"),
6228 Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
6229 Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
6230 Self::CreateSubscription(s) => {
6231 write!(
6232 f,
6233 "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
6234 quote_ident(&s.name),
6235 s.conn_str.replace('\'', "''")
6236 )?;
6237 for (i, p) in s.publications.iter().enumerate() {
6238 if i > 0 {
6239 f.write_str(", ")?;
6240 }
6241 write!(f, "{}", quote_ident(p))?;
6242 }
6243 Ok(())
6244 }
6245 Self::DropSubscription { name, if_exists } => {
6246 let opt = if *if_exists { "IF EXISTS " } else { "" };
6247 write!(f, "DROP SUBSCRIPTION {opt}{}", quote_ident(name))
6248 }
6249 Self::WaitForWalPosition { pos, timeout_ms } => {
6250 write!(f, "WAIT FOR WAL POSITION {pos}")?;
6251 if let Some(ms) = timeout_ms {
6252 write!(f, " WITH TIMEOUT {ms}")?;
6253 }
6254 Ok(())
6255 }
6256 Self::RenameTables(pairs) => {
6257 f.write_str("RENAME TABLE ")?;
6258 for (i, (from, to)) in pairs.iter().enumerate() {
6259 if i > 0 {
6260 f.write_str(", ")?;
6261 }
6262 write!(f, "{} TO {}", quote_ident(from), quote_ident(to))?;
6263 }
6264 Ok(())
6265 }
6266 Self::Analyze(None) => f.write_str("ANALYZE"),
6267 Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
6268 Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
6269 Self::Explain(e) => {
6270 if e.suggest {
6271 write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
6272 } else if e.analyze {
6273 write!(f, "EXPLAIN ANALYZE {}", e.inner)
6274 } else {
6275 write!(f, "EXPLAIN {}", e.inner)
6276 }
6277 }
6278 Self::AlterIndex(a) => {
6279 write!(f, "ALTER INDEX ")?;
6280 match &a.target {
6281 // Parameters are consumed, not stored; the shortest
6282 // faithful spelling.
6283 AlterIndexTarget::StorageParams => {
6284 write!(f, "{} SET ()", quote_ident(&a.name))
6285 }
6286 AlterIndexTarget::Rebuild { encoding } => {
6287 write!(f, "{} REBUILD", quote_ident(&a.name))?;
6288 if let Some(enc) = encoding {
6289 write!(f, " WITH (encoding = {enc})")?;
6290 }
6291 Ok(())
6292 }
6293 AlterIndexTarget::Rename { new, if_exists } => {
6294 if *if_exists {
6295 f.write_str("IF EXISTS ")?;
6296 }
6297 write!(f, "{} RENAME TO {}", quote_ident(&a.name), quote_ident(new))
6298 }
6299 }
6300 }
6301 Self::AlterTable(a) => {
6302 write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
6303 for (i, t) in a.targets.iter().enumerate() {
6304 if i > 0 {
6305 f.write_str(", ")?;
6306 }
6307 fmt_alter_target(f, t)?;
6308 }
6309 Ok(())
6310 }
6311 Self::CreatePublication(p) => {
6312 write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
6313 match &p.scope {
6314 PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
6315 PublicationScope::ForTables(ts) => {
6316 f.write_str(" FOR TABLE ")?;
6317 for (i, t) in ts.iter().enumerate() {
6318 if i > 0 {
6319 f.write_str(", ")?;
6320 }
6321 write!(f, "{}", quote_ident(t))?;
6322 }
6323 Ok(())
6324 }
6325 PublicationScope::TablesInSchema(schema) => {
6326 write!(f, " FOR TABLES IN SCHEMA {}", quote_ident(schema))?;
6327 Ok(())
6328 }
6329 PublicationScope::AllTablesExcept(ts) => {
6330 f.write_str(" FOR ALL TABLES EXCEPT ")?;
6331 for (i, t) in ts.iter().enumerate() {
6332 if i > 0 {
6333 f.write_str(", ")?;
6334 }
6335 write!(f, "{}", quote_ident(t))?;
6336 }
6337 Ok(())
6338 }
6339 }
6340 }
6341 Self::CreateExtension(name) => {
6342 write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
6343 }
6344 Self::DoBlock(body) => write!(f, "DO $$ {body} $$"),
6345 Self::DropPublication { name, if_exists } => {
6346 let opt = if *if_exists { "IF EXISTS " } else { "" };
6347 write!(f, "DROP PUBLICATION {opt}{}", quote_ident(name))
6348 }
6349 Self::SetParameter { name, value, local } => {
6350 write!(f, "SET {}{name} = ", if *local { "LOCAL " } else { "" })?;
6351 match value {
6352 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
6353 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
6354 SetValue::Default => f.write_str("DEFAULT"),
6355 }
6356 }
6357 Self::SetTransaction { modes } => {
6358 f.write_str("SET TRANSACTION")?;
6359 if let Some(isolation) = modes.isolation {
6360 let name = match isolation {
6361 IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
6362 IsolationLevel::ReadCommitted => "READ COMMITTED",
6363 IsolationLevel::RepeatableRead => "REPEATABLE READ",
6364 IsolationLevel::Serializable => "SERIALIZABLE",
6365 };
6366 write!(f, " ISOLATION LEVEL {name}")?;
6367 }
6368 match modes.read_only {
6369 Some(true) => f.write_str(" READ ONLY")?,
6370 Some(false) => f.write_str(" READ WRITE")?,
6371 None => {}
6372 }
6373 Ok(())
6374 }
6375 Self::ShowParameter(name) => write!(f, "SHOW {name}"),
6376 Self::SetUserVars(assigns, _) => {
6377 f.write_str("SET ")?;
6378 for (i, (name, value)) in assigns.iter().enumerate() {
6379 if i > 0 {
6380 f.write_str(", ")?;
6381 }
6382 write!(f, "@{name} = {value}")?;
6383 }
6384 Ok(())
6385 }
6386 Self::SetParameterList(pairs) => {
6387 f.write_str("SET ")?;
6388 for (i, (name, value)) in pairs.iter().enumerate() {
6389 if i > 0 {
6390 f.write_str(", ")?;
6391 }
6392 write!(f, "{name} = ")?;
6393 match value {
6394 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
6395 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
6396 SetValue::Default => f.write_str("DEFAULT")?,
6397 }
6398 }
6399 Ok(())
6400 }
6401 Self::ResetParameter(None) => f.write_str("RESET ALL"),
6402 Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
6403 Self::CreateFunction(s) => s.fmt(f),
6404 Self::CreateTrigger(s) => s.fmt(f),
6405 Self::DropTrigger {
6406 name,
6407 table,
6408 if_exists,
6409 } => {
6410 f.write_str("DROP TRIGGER ")?;
6411 if *if_exists {
6412 f.write_str("IF EXISTS ")?;
6413 }
6414 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6415 }
6416 Self::DropFunction {
6417 name,
6418 args,
6419 if_exists,
6420 } => {
6421 f.write_str("DROP FUNCTION ")?;
6422 if *if_exists {
6423 f.write_str("IF EXISTS ")?;
6424 }
6425 write!(f, "{}", quote_ident(name))?;
6426 if let Some(a) = args {
6427 write!(f, "({})", a.join(", "))?;
6428 }
6429 Ok(())
6430 }
6431 Self::CreateSequence(s) => s.fmt(f),
6432 Self::AlterSequence(s) => s.fmt(f),
6433 Self::DropSequence { names, if_exists } => {
6434 f.write_str("DROP SEQUENCE ")?;
6435 if *if_exists {
6436 f.write_str("IF EXISTS ")?;
6437 }
6438 for (i, n) in names.iter().enumerate() {
6439 if i > 0 {
6440 f.write_str(", ")?;
6441 }
6442 write!(f, "{}", quote_ident(n))?;
6443 }
6444 Ok(())
6445 }
6446 Self::CreateView(v) => v.fmt(f),
6447 Self::DropView { names, if_exists } => {
6448 f.write_str("DROP VIEW ")?;
6449 if *if_exists {
6450 f.write_str("IF EXISTS ")?;
6451 }
6452 for (i, n) in names.iter().enumerate() {
6453 if i > 0 {
6454 f.write_str(", ")?;
6455 }
6456 write!(f, "{}", quote_ident(n))?;
6457 }
6458 Ok(())
6459 }
6460 Self::CreateMaterializedView(v) => v.fmt(f),
6461 Self::RefreshMaterializedView { name, with_data } => {
6462 write!(f, "REFRESH MATERIALIZED VIEW {}", quote_ident(name))?;
6463 if !*with_data {
6464 f.write_str(" WITH NO DATA")?;
6465 }
6466 Ok(())
6467 }
6468 Self::DropMaterializedView { names, if_exists } => {
6469 f.write_str("DROP MATERIALIZED VIEW ")?;
6470 if *if_exists {
6471 f.write_str("IF EXISTS ")?;
6472 }
6473 for (i, n) in names.iter().enumerate() {
6474 if i > 0 {
6475 f.write_str(", ")?;
6476 }
6477 write!(f, "{}", quote_ident(n))?;
6478 }
6479 Ok(())
6480 }
6481 Self::CreateType(t) => t.fmt(f),
6482 Self::CommentOn {
6483 kind,
6484 name,
6485 comment,
6486 } => {
6487 let body = match comment {
6488 Some(c) => alloc::format!("'{}'", c.replace('\'', "''")),
6489 None => "NULL".into(),
6490 };
6491 write!(f, "COMMENT ON {} {name} IS {body}", kind.to_uppercase())
6492 }
6493 Self::AlterTypeRenameValue {
6494 type_name,
6495 old,
6496 new,
6497 } => write!(
6498 f,
6499 "ALTER TYPE {} RENAME VALUE '{}' TO '{}'",
6500 quote_ident(type_name),
6501 old.replace('\'', "''"),
6502 new.replace('\'', "''")
6503 ),
6504 Self::AlterTypeAddValue {
6505 type_name,
6506 label,
6507 if_not_exists,
6508 position,
6509 } => {
6510 write!(f, "ALTER TYPE {type_name} ADD VALUE ")?;
6511 if *if_not_exists {
6512 write!(f, "IF NOT EXISTS ")?;
6513 }
6514 write!(f, "'{label}'")?;
6515 if let Some((is_before, anchor)) = position {
6516 write!(
6517 f,
6518 " {} '{anchor}'",
6519 if *is_before { "BEFORE" } else { "AFTER" }
6520 )?;
6521 }
6522 Ok(())
6523 }
6524 Self::DropType { names, if_exists } => {
6525 f.write_str("DROP TYPE ")?;
6526 if *if_exists {
6527 f.write_str("IF EXISTS ")?;
6528 }
6529 for (i, n) in names.iter().enumerate() {
6530 if i > 0 {
6531 f.write_str(", ")?;
6532 }
6533 write!(f, "{}", quote_ident(n))?;
6534 }
6535 Ok(())
6536 }
6537 Self::CreateDomain(d) => d.fmt(f),
6538 Self::DropDomain { names, if_exists } => {
6539 f.write_str("DROP DOMAIN ")?;
6540 if *if_exists {
6541 f.write_str("IF EXISTS ")?;
6542 }
6543 for (i, n) in names.iter().enumerate() {
6544 if i > 0 {
6545 f.write_str(", ")?;
6546 }
6547 write!(f, "{}", quote_ident(n))?;
6548 }
6549 Ok(())
6550 }
6551 Self::CreateSchema {
6552 name,
6553 if_not_exists,
6554 } => {
6555 f.write_str("CREATE SCHEMA ")?;
6556 if *if_not_exists {
6557 f.write_str("IF NOT EXISTS ")?;
6558 }
6559 write!(f, "{}", quote_ident(name))
6560 }
6561 Self::DropSchema { names, if_exists } => {
6562 f.write_str("DROP SCHEMA ")?;
6563 if *if_exists {
6564 f.write_str("IF EXISTS ")?;
6565 }
6566 for (i, n) in names.iter().enumerate() {
6567 if i > 0 {
6568 f.write_str(", ")?;
6569 }
6570 write!(f, "{}", quote_ident(n))?;
6571 }
6572 Ok(())
6573 }
6574 Self::CreateRule(r) => {
6575 f.write_str("CREATE ")?;
6576 if r.or_replace {
6577 f.write_str("OR REPLACE ")?;
6578 }
6579 write!(
6580 f,
6581 "RULE {} AS ON {} TO {}",
6582 quote_ident(&r.name),
6583 r.event,
6584 quote_ident(&r.table)
6585 )?;
6586 if let Some(w) = &r.when_condition {
6587 write!(f, " WHERE {w}")?;
6588 }
6589 f.write_str(if r.instead {
6590 " DO INSTEAD "
6591 } else {
6592 " DO ALSO "
6593 })?;
6594 if r.commands.is_empty() {
6595 f.write_str("NOTHING")?;
6596 } else if r.commands.len() == 1 {
6597 write!(f, "{}", r.commands[0])?;
6598 } else {
6599 f.write_str("(")?;
6600 for (i, c) in r.commands.iter().enumerate() {
6601 if i > 0 {
6602 f.write_str("; ")?;
6603 }
6604 write!(f, "{c}")?;
6605 }
6606 f.write_str(")")?;
6607 }
6608 Ok(())
6609 }
6610 Self::DropRule {
6611 name,
6612 table,
6613 if_exists,
6614 } => {
6615 f.write_str("DROP RULE ")?;
6616 if *if_exists {
6617 f.write_str("IF EXISTS ")?;
6618 }
6619 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
6620 }
6621 }
6622 }
6623}
6624
6625impl fmt::Display for CreateDomainStatement {
6626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6627 write!(
6628 f,
6629 "CREATE DOMAIN {} AS {}",
6630 quote_ident(&self.name),
6631 self.base_type
6632 )?;
6633 if let Some(d) = &self.default {
6634 write!(f, " DEFAULT {d}")?;
6635 }
6636 if self.not_null {
6637 f.write_str(" NOT NULL")?;
6638 }
6639 for c in &self.checks {
6640 write!(f, " CHECK ({c})")?;
6641 }
6642 Ok(())
6643 }
6644}
6645
6646impl fmt::Display for CreateTypeStatement {
6647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6648 write!(f, "CREATE TYPE {} AS ", quote_ident(&self.name))?;
6649 match &self.kind {
6650 TypeKind::Enum { labels } => {
6651 f.write_str("ENUM (")?;
6652 for (i, l) in labels.iter().enumerate() {
6653 if i > 0 {
6654 f.write_str(", ")?;
6655 }
6656 write!(f, "'{}'", l.replace('\'', "''"))?;
6657 }
6658 f.write_str(")")
6659 }
6660 TypeKind::Composite { fields, .. } => {
6661 f.write_str("(")?;
6662 for (i, (n, t)) in fields.iter().enumerate() {
6663 if i > 0 {
6664 f.write_str(", ")?;
6665 }
6666 write!(f, "{} {}", quote_ident(n), t)?;
6667 }
6668 f.write_str(")")
6669 }
6670 }
6671 }
6672}
6673
6674impl fmt::Display for CreateMaterializedViewStatement {
6675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6676 f.write_str("CREATE MATERIALIZED VIEW ")?;
6677 if self.if_not_exists {
6678 f.write_str("IF NOT EXISTS ")?;
6679 }
6680 write!(f, "{}", quote_ident(&self.name))?;
6681 if !self.columns.is_empty() {
6682 f.write_str(" (")?;
6683 for (i, c) in self.columns.iter().enumerate() {
6684 if i > 0 {
6685 f.write_str(", ")?;
6686 }
6687 write!(f, "{}", quote_ident(c))?;
6688 }
6689 f.write_str(")")?;
6690 }
6691 write!(f, " AS {}", self.body)?;
6692 if !self.with_data {
6693 f.write_str(" WITH NO DATA")?;
6694 }
6695 Ok(())
6696 }
6697}
6698
6699impl fmt::Display for CreateViewStatement {
6700 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6701 f.write_str("CREATE ")?;
6702 if self.or_replace {
6703 f.write_str("OR REPLACE ")?;
6704 }
6705 if self.temporary {
6706 f.write_str("TEMPORARY ")?;
6707 }
6708 f.write_str("VIEW ")?;
6709 if self.if_not_exists {
6710 f.write_str("IF NOT EXISTS ")?;
6711 }
6712 write!(f, "{}", quote_ident(&self.name))?;
6713 if !self.columns.is_empty() {
6714 f.write_str(" (")?;
6715 for (i, c) in self.columns.iter().enumerate() {
6716 if i > 0 {
6717 f.write_str(", ")?;
6718 }
6719 write!(f, "{}", quote_ident(c))?;
6720 }
6721 f.write_str(")")?;
6722 }
6723 write!(f, " AS {}", self.body)?;
6724 match self.check_option {
6725 Some(ViewCheckOption::Local) => f.write_str(" WITH LOCAL CHECK OPTION"),
6726 Some(ViewCheckOption::Cascaded) => f.write_str(" WITH CASCADED CHECK OPTION"),
6727 None => Ok(()),
6728 }
6729 }
6730}
6731
6732impl fmt::Display for CreateSequenceStatement {
6733 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6734 f.write_str("CREATE ")?;
6735 if self.temporary {
6736 f.write_str("TEMPORARY ")?;
6737 }
6738 f.write_str("SEQUENCE ")?;
6739 if self.if_not_exists {
6740 f.write_str("IF NOT EXISTS ")?;
6741 }
6742 write!(f, "{}", quote_ident(&self.name))?;
6743 if let Some(dt) = self.data_type {
6744 write!(f, " AS {dt}")?;
6745 }
6746 write_sequence_options(f, &self.options)
6747 }
6748}
6749
6750impl fmt::Display for AlterSequenceStatement {
6751 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6752 f.write_str("ALTER SEQUENCE ")?;
6753 if self.if_exists {
6754 f.write_str("IF EXISTS ")?;
6755 }
6756 write!(f, "{}", quote_ident(&self.name))?;
6757 write_sequence_options(f, &self.options)
6758 }
6759}
6760
6761impl fmt::Display for SequenceDataType {
6762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6763 f.write_str(match self {
6764 Self::SmallInt => "smallint",
6765 Self::Int => "integer",
6766 Self::BigInt => "bigint",
6767 })
6768 }
6769}
6770
6771fn write_sequence_options(f: &mut fmt::Formatter<'_>, o: &SequenceOptions) -> fmt::Result {
6772 if let Some(n) = o.increment {
6773 write!(f, " INCREMENT BY {n}")?;
6774 }
6775 match o.min_value {
6776 Some(SeqBound::Value(n)) => write!(f, " MINVALUE {n}")?,
6777 Some(SeqBound::NoBound) => f.write_str(" NO MINVALUE")?,
6778 None => {}
6779 }
6780 match o.max_value {
6781 Some(SeqBound::Value(n)) => write!(f, " MAXVALUE {n}")?,
6782 Some(SeqBound::NoBound) => f.write_str(" NO MAXVALUE")?,
6783 None => {}
6784 }
6785 if let Some(n) = o.start {
6786 write!(f, " START WITH {n}")?;
6787 }
6788 match o.restart {
6789 Some(Some(n)) => write!(f, " RESTART WITH {n}")?,
6790 Some(None) => f.write_str(" RESTART")?,
6791 None => {}
6792 }
6793 if let Some(n) = o.cache {
6794 write!(f, " CACHE {n}")?;
6795 }
6796 match o.cycle {
6797 Some(true) => f.write_str(" CYCLE")?,
6798 Some(false) => f.write_str(" NO CYCLE")?,
6799 None => {}
6800 }
6801 if let Some(ob) = &o.owned_by {
6802 match ob {
6803 SequenceOwnedBy::None => f.write_str(" OWNED BY NONE")?,
6804 SequenceOwnedBy::Column { table, column } => {
6805 write!(
6806 f,
6807 " OWNED BY {}.{}",
6808 quote_ident(table),
6809 quote_ident(column)
6810 )?;
6811 }
6812 }
6813 }
6814 Ok(())
6815}
6816
6817impl fmt::Display for CreateFunctionStatement {
6818 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6819 f.write_str("CREATE ")?;
6820 if self.or_replace {
6821 f.write_str("OR REPLACE ")?;
6822 }
6823 write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
6824 for (i, arg) in self.args.iter().enumerate() {
6825 if i > 0 {
6826 f.write_str(", ")?;
6827 }
6828 match arg.mode {
6829 FunctionArgMode::In => {}
6830 FunctionArgMode::Out => f.write_str("OUT ")?,
6831 FunctionArgMode::InOut => f.write_str("INOUT ")?,
6832 }
6833 if let Some(name) = &arg.name {
6834 write!(f, "{} ", quote_ident(name))?;
6835 }
6836 match &arg.ty {
6837 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6838 FunctionArgType::Raw(s) => f.write_str(s)?,
6839 }
6840 }
6841 f.write_str(") RETURNS ")?;
6842 match &self.returns {
6843 FunctionReturn::Trigger => f.write_str("TRIGGER")?,
6844 FunctionReturn::Void => f.write_str("VOID")?,
6845 FunctionReturn::Type(t) => write!(f, "{t}")?,
6846 FunctionReturn::Other(s) => f.write_str(s)?,
6847 }
6848 write!(f, " LANGUAGE {} AS $$", self.language)?;
6849 match &self.body {
6850 FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
6851 FunctionBody::Raw(s) => f.write_str(s)?,
6852 }
6853 f.write_str("$$")
6854 }
6855}
6856
6857impl fmt::Display for PlPgSqlBlock {
6858 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6859 if !self.declarations.is_empty() {
6860 f.write_str("DECLARE\n")?;
6861 for d in &self.declarations {
6862 write!(f, " {} ", quote_ident(&d.name))?;
6863 match &d.ty {
6864 FunctionArgType::Typed(t) => write!(f, "{t}")?,
6865 FunctionArgType::Raw(s) => f.write_str(s)?,
6866 }
6867 if let Some(e) = &d.default {
6868 write!(f, " := {e}")?;
6869 }
6870 f.write_str(";\n")?;
6871 }
6872 }
6873 f.write_str("BEGIN\n")?;
6874 for stmt in &self.statements {
6875 writeln!(f, " {stmt};")?;
6876 }
6877 // v7.39 (read01 round 64) — the EXCEPTION section. It was MISSING from
6878 // this Display, and `CREATE FUNCTION` stores a body by re-rendering the
6879 // parsed block through it — so every exception handler a function
6880 // declared was thrown away AT STORE TIME. The block executed fine while
6881 // it was still an AST (a DO block never round-trips through text), which
6882 // is why only functions and triggers lost theirs.
6883 if !self.exception_handlers.is_empty() {
6884 f.write_str("EXCEPTION\n")?;
6885 for h in &self.exception_handlers {
6886 writeln!(f, " WHEN {} THEN", h.conditions.join(" OR "))?;
6887 for stmt in &h.body {
6888 writeln!(f, " {stmt};")?;
6889 }
6890 }
6891 }
6892 f.write_str("END")
6893 }
6894}
6895
6896impl fmt::Display for PlPgSqlStmt {
6897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6898 match self {
6899 Self::Assign { target, value } => write!(f, "{target} := {value}"),
6900 Self::SelectInto { var, body } => write!(f, "{body} INTO {var}"),
6901 Self::ReturnNext(e) => write!(f, "RETURN NEXT {e}"),
6902 Self::ReturnQuery(s) => write!(f, "RETURN QUERY {s}"),
6903 Self::ReturnQueryExecute { sql } => write!(f, "RETURN QUERY EXECUTE {sql}"),
6904 Self::Return(t) => match t {
6905 ReturnTarget::New => f.write_str("RETURN NEW"),
6906 ReturnTarget::Old => f.write_str("RETURN OLD"),
6907 ReturnTarget::Null => f.write_str("RETURN NULL"),
6908 ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
6909 },
6910 Self::If {
6911 branches,
6912 else_branch,
6913 } => {
6914 for (i, (cond, body)) in branches.iter().enumerate() {
6915 if i == 0 {
6916 write!(f, "IF {cond} THEN ")?;
6917 } else {
6918 write!(f, " ELSIF {cond} THEN ")?;
6919 }
6920 for (j, s) in body.iter().enumerate() {
6921 if j > 0 {
6922 f.write_str("; ")?;
6923 }
6924 write!(f, "{s}")?;
6925 }
6926 }
6927 if !else_branch.is_empty() {
6928 f.write_str(" ELSE ")?;
6929 for (j, s) in else_branch.iter().enumerate() {
6930 if j > 0 {
6931 f.write_str("; ")?;
6932 }
6933 write!(f, "{s}")?;
6934 }
6935 }
6936 f.write_str(" END IF")
6937 }
6938 Self::Raise {
6939 level,
6940 message,
6941 args,
6942 } => {
6943 let lvl = match level {
6944 RaiseLevel::Notice => "NOTICE",
6945 RaiseLevel::Warning => "WARNING",
6946 RaiseLevel::Info => "INFO",
6947 RaiseLevel::Log => "LOG",
6948 RaiseLevel::Debug => "DEBUG",
6949 RaiseLevel::Exception => "EXCEPTION",
6950 };
6951 write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
6952 for a in args {
6953 write!(f, ", {a}")?;
6954 }
6955 Ok(())
6956 }
6957 Self::EmbeddedSql(s) => write!(f, "{s}"),
6958 Self::Assert { condition, message } => {
6959 write!(f, "ASSERT {condition}")?;
6960 if let Some(m) = message {
6961 write!(f, ", {m}")?;
6962 }
6963 Ok(())
6964 }
6965 Self::While { condition, body } => {
6966 writeln!(f, "WHILE {condition} LOOP")?;
6967 for s in body {
6968 writeln!(f, " {s};")?;
6969 }
6970 f.write_str("END LOOP")
6971 }
6972 Self::ForRange {
6973 var,
6974 start,
6975 end,
6976 reverse,
6977 body,
6978 } => {
6979 write!(f, "FOR {var} IN ")?;
6980 if *reverse {
6981 f.write_str("REVERSE ")?;
6982 }
6983 writeln!(f, "{start}..{end} LOOP")?;
6984 for s in body {
6985 writeln!(f, " {s};")?;
6986 }
6987 f.write_str("END LOOP")
6988 }
6989 Self::Loop { body } => {
6990 writeln!(f, "LOOP")?;
6991 for s in body {
6992 writeln!(f, " {s};")?;
6993 }
6994 f.write_str("END LOOP")
6995 }
6996 Self::Exit { when } => {
6997 f.write_str("EXIT")?;
6998 if let Some(c) = when {
6999 write!(f, " WHEN {c}")?;
7000 }
7001 Ok(())
7002 }
7003 Self::Continue { when } => {
7004 f.write_str("CONTINUE")?;
7005 if let Some(c) = when {
7006 write!(f, " WHEN {c}")?;
7007 }
7008 Ok(())
7009 }
7010 Self::ExecuteDynamic { sql } => write!(f, "EXECUTE {sql}"),
7011 Self::ForQuery { var, query, body } => {
7012 writeln!(f, "FOR {var} IN ({query}) LOOP")?;
7013 for s in body {
7014 writeln!(f, " {s};")?;
7015 }
7016 f.write_str("END LOOP")
7017 }
7018 Self::ForExecute {
7019 var,
7020 sql_expr,
7021 body,
7022 } => {
7023 writeln!(f, "FOR {var} IN EXECUTE {sql_expr} LOOP")?;
7024 for s in body {
7025 writeln!(f, " {s};")?;
7026 }
7027 f.write_str("END LOOP")
7028 }
7029 }
7030 }
7031}
7032
7033impl fmt::Display for AssignTarget {
7034 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7035 match self {
7036 Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
7037 Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
7038 Self::Local(n) => f.write_str(n),
7039 }
7040 }
7041}
7042
7043impl fmt::Display for CreateTriggerStatement {
7044 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7045 f.write_str("CREATE ")?;
7046 if self.or_replace {
7047 f.write_str("OR REPLACE ")?;
7048 }
7049 write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
7050 match self.timing {
7051 TriggerTiming::Before => f.write_str("BEFORE")?,
7052 TriggerTiming::After => f.write_str("AFTER")?,
7053 TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
7054 }
7055 for (i, e) in self.events.iter().enumerate() {
7056 if i == 0 {
7057 f.write_str(" ")?;
7058 } else {
7059 f.write_str(" OR ")?;
7060 }
7061 match e {
7062 TriggerEvent::Insert => f.write_str("INSERT")?,
7063 TriggerEvent::Update => {
7064 f.write_str("UPDATE")?;
7065 if !self.update_columns.is_empty() {
7066 f.write_str(" OF ")?;
7067 for (j, col) in self.update_columns.iter().enumerate() {
7068 if j > 0 {
7069 f.write_str(", ")?;
7070 }
7071 f.write_str("e_ident(col))?;
7072 }
7073 }
7074 }
7075 TriggerEvent::Delete => f.write_str("DELETE")?,
7076 TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
7077 }
7078 }
7079 write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
7080 match self.for_each {
7081 TriggerForEach::Row => f.write_str("ROW")?,
7082 TriggerForEach::Statement => f.write_str("STATEMENT")?,
7083 }
7084 write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
7085 }
7086}
7087
7088impl fmt::Display for CreateIndexStatement {
7089 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7090 if self.is_unique {
7091 f.write_str("CREATE UNIQUE INDEX ")?;
7092 } else {
7093 f.write_str("CREATE INDEX ")?;
7094 }
7095 if self.if_not_exists {
7096 f.write_str("IF NOT EXISTS ")?;
7097 }
7098 write!(
7099 f,
7100 "{} ON {} ",
7101 quote_ident(&self.name),
7102 quote_ident(&self.table)
7103 )?;
7104 match self.method {
7105 IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
7106 IndexMethod::Brin => f.write_str("USING brin ")?,
7107 IndexMethod::Gin => f.write_str("USING gin ")?,
7108 IndexMethod::BTree => {}
7109 }
7110 if let Some(expr) = &self.expression {
7111 write!(f, "({})", expr)?;
7112 } else if self.extra_columns.is_empty() {
7113 // v7.15.0 — preserve operator class on round-trip
7114 // (`(col opclass)`) so WAL replay reconstructs the
7115 // engine-routing intent (e.g. `gin_trgm_ops` →
7116 // trigram-GIN build path).
7117 if let Some(op) = &self.opclass {
7118 write!(f, "({} {})", quote_ident(&self.column), op)?;
7119 } else {
7120 write!(f, "({})", quote_ident(&self.column))?;
7121 }
7122 } else {
7123 // v7.9.14 — multi-column key. Emit each column quoted
7124 // so the round-tripped form re-parses to identical AST.
7125 f.write_str("(")?;
7126 write!(f, "{}", quote_ident(&self.column))?;
7127 for c in &self.extra_columns {
7128 write!(f, ", {}", quote_ident(c))?;
7129 }
7130 f.write_str(")")?;
7131 }
7132 if !self.included_columns.is_empty() {
7133 f.write_str(" INCLUDE (")?;
7134 for (i, c) in self.included_columns.iter().enumerate() {
7135 if i > 0 {
7136 f.write_str(", ")?;
7137 }
7138 write!(f, "{}", quote_ident(c))?;
7139 }
7140 f.write_str(")")?;
7141 }
7142 if let Some(pred) = &self.partial_predicate {
7143 write!(f, " WHERE {}", pred)?;
7144 }
7145 Ok(())
7146 }
7147}
7148
7149impl fmt::Display for CreateTableStatement {
7150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7151 f.write_str("CREATE TABLE ")?;
7152 if self.if_not_exists {
7153 f.write_str("IF NOT EXISTS ")?;
7154 }
7155 write!(f, "{}", quote_ident(&self.name))?;
7156 // v7.37.6-B — `PARTITION OF parent <bounds>` child form has
7157 // no column list and no constraints; the table inherits its
7158 // columns from the parent at engine-DDL time.
7159 if let Some(spec) = &self.partition_of {
7160 write!(f, " PARTITION OF {} ", quote_ident(&spec.parent_name))?;
7161 return match &spec.bounds {
7162 PartitionOfBoundsAst::Range { lower, upper } => {
7163 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7164 }
7165 PartitionOfBoundsAst::List { values } => {
7166 f.write_str("FOR VALUES IN (")?;
7167 for (i, v) in values.iter().enumerate() {
7168 if i > 0 {
7169 f.write_str(", ")?;
7170 }
7171 write!(f, "{}", v)?;
7172 }
7173 f.write_str(")")
7174 }
7175 PartitionOfBoundsAst::Hash { modulus, remainder } => {
7176 write!(
7177 f,
7178 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7179 modulus, remainder
7180 )
7181 }
7182 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7183 };
7184 }
7185 f.write_str(" (")?;
7186 for (i, col) in self.columns.iter().enumerate() {
7187 if i > 0 {
7188 f.write_str(", ")?;
7189 }
7190 write!(f, "{col}")?;
7191 }
7192 // v7.6.0 — render FK constraints in table-level form, after
7193 // the column list. WAL replay round-trips through Display, so
7194 // every FK must serialise here for replay to reconstruct the
7195 // schema bit-for-bit.
7196 for fk in &self.foreign_keys {
7197 f.write_str(", ")?;
7198 write!(f, "{fk}")?;
7199 }
7200 // v7.13.0 — render table-level constraints (PRIMARY KEY /
7201 // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
7202 // column-level UNIQUE / CHECK get lifted to this list at
7203 // parse time, so emitting only here avoids double-counting.
7204 for tc in &self.table_constraints {
7205 f.write_str(", ")?;
7206 write!(f, "{tc}")?;
7207 }
7208 f.write_str(")")?;
7209 // v7.37.6-B — partition-parent suffix renders after the
7210 // closing column-list paren, before the optional MySQL
7211 // table-options tail (which Display doesn't currently emit).
7212 if let Some(spec) = &self.partition_by {
7213 f.write_str(" PARTITION BY ")?;
7214 match spec.kind {
7215 PartitionKindAst::Range => f.write_str("RANGE ")?,
7216 PartitionKindAst::List => f.write_str("LIST ")?,
7217 PartitionKindAst::Hash => f.write_str("HASH ")?,
7218 }
7219 f.write_str("(")?;
7220 for (i, col) in spec.key_columns.iter().enumerate() {
7221 if i > 0 {
7222 f.write_str(", ")?;
7223 }
7224 f.write_str("e_ident(col))?;
7225 }
7226 f.write_str(")")?;
7227 }
7228 Ok(())
7229 }
7230}
7231
7232fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
7233 match t {
7234 AlterTableTarget::OfType { type_name } => write!(f, "OF {type_name}"),
7235 AlterTableTarget::ReplicaIdentityUsingIndex { index } => {
7236 write!(f, "REPLICA IDENTITY USING INDEX {index}")
7237 }
7238 AlterTableTarget::Inherit { parent, detach } => {
7239 if *detach {
7240 write!(f, "NO INHERIT {parent}")
7241 } else {
7242 write!(f, "INHERIT {parent}")
7243 }
7244 }
7245 AlterTableTarget::SetHotTierBytes(n) => {
7246 write!(f, "SET hot_tier_bytes = {n}")
7247 }
7248 AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
7249 AlterTableTarget::DropForeignKey { name, if_exists } => {
7250 f.write_str("DROP CONSTRAINT ")?;
7251 if *if_exists {
7252 f.write_str("IF EXISTS ")?;
7253 }
7254 write!(f, "{}", quote_ident(name))
7255 }
7256 AlterTableTarget::DropIndex { name, if_exists } => {
7257 f.write_str("DROP INDEX ")?;
7258 if *if_exists {
7259 f.write_str("IF EXISTS ")?;
7260 }
7261 write!(f, "{}", quote_ident(name))
7262 }
7263 AlterTableTarget::ModifyColumn {
7264 column,
7265 rename_to,
7266 definition,
7267 position,
7268 } => {
7269 if let Some(new) = rename_to {
7270 write!(
7271 f,
7272 "CHANGE COLUMN {} {} {}",
7273 quote_ident(column),
7274 quote_ident(new),
7275 definition.ty
7276 )?;
7277 } else {
7278 write!(f, "MODIFY COLUMN {} {}", quote_ident(column), definition.ty)?;
7279 }
7280 if !definition.nullable {
7281 f.write_str(" NOT NULL")?;
7282 }
7283 write_column_position(f, position.as_ref())
7284 }
7285 AlterTableTarget::RenameIndex { old, new } => {
7286 write!(
7287 f,
7288 "RENAME INDEX {} TO {}",
7289 quote_ident(old),
7290 quote_ident(new)
7291 )
7292 }
7293 AlterTableTarget::SetTableAutoIncrement(n) => write!(f, "AUTO_INCREMENT = {n}"),
7294 AlterTableTarget::SetEngine(name) => write!(f, "ENGINE = {name}"),
7295 AlterTableTarget::ConvertToCharacterSet { charset, collate } => {
7296 write!(f, "CONVERT TO CHARACTER SET {charset}")?;
7297 if let Some(c) = collate {
7298 write!(f, " COLLATE {c}")?;
7299 }
7300 Ok(())
7301 }
7302 AlterTableTarget::AddColumn {
7303 column,
7304 if_not_exists,
7305 position,
7306 } => {
7307 f.write_str("ADD COLUMN ")?;
7308 if *if_not_exists {
7309 f.write_str("IF NOT EXISTS ")?;
7310 }
7311 write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
7312 if !column.nullable {
7313 f.write_str(" NOT NULL")?;
7314 }
7315 if let Some(d) = &column.default {
7316 write!(f, " DEFAULT {d}")?;
7317 }
7318 if column.auto_increment {
7319 f.write_str(" AUTO_INCREMENT")?;
7320 }
7321 if column.is_primary_key {
7322 f.write_str(" PRIMARY KEY")?;
7323 }
7324 Ok(())
7325 }
7326 AlterTableTarget::AlterColumnType {
7327 column,
7328 new_type,
7329 using,
7330 collation,
7331 } => {
7332 write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
7333 if let Some((_, name)) = collation {
7334 write!(f, " COLLATE {}", quote_ident(name))?;
7335 }
7336 if let Some(u) = using {
7337 write!(f, " USING {u}")?;
7338 }
7339 Ok(())
7340 }
7341 AlterTableTarget::DropColumn {
7342 column,
7343 if_exists,
7344 cascade,
7345 } => {
7346 f.write_str("DROP COLUMN ")?;
7347 if *if_exists {
7348 f.write_str("IF EXISTS ")?;
7349 }
7350 write!(f, "{}", quote_ident(column))?;
7351 if *cascade {
7352 f.write_str(" CASCADE")?;
7353 }
7354 Ok(())
7355 }
7356 AlterTableTarget::AddTableConstraint(tc) => {
7357 write!(f, "ADD {tc}")
7358 }
7359 AlterTableTarget::ValidateConstraint { name } => {
7360 write!(f, "VALIDATE CONSTRAINT {}", quote_ident(name))
7361 }
7362 AlterTableTarget::OwnerTo { role } => write!(f, "OWNER TO {}", quote_ident(role)),
7363 AlterTableTarget::ClusterOn { index } => match index {
7364 Some(i) => write!(f, "CLUSTER ON {}", quote_ident(i)),
7365 None => f.write_str("SET WITHOUT CLUSTER"),
7366 },
7367 AlterTableTarget::SetColumnAutoIncrement { column, seq_name } => {
7368 // Round-trip-safe spelling: re-parsing this form lowers
7369 // back to SetColumnAutoIncrement (the nextval default is
7370 // how pg_dump says "serial").
7371 let seq = seq_name
7372 .clone()
7373 .unwrap_or_else(|| alloc::format!("{column}_seq"));
7374 write!(
7375 f,
7376 "ALTER COLUMN {} SET DEFAULT nextval('{seq}')",
7377 quote_ident(column)
7378 )
7379 }
7380 AlterTableTarget::RenameColumn { old, new } => {
7381 write!(
7382 f,
7383 "RENAME COLUMN {} TO {}",
7384 quote_ident(old),
7385 quote_ident(new)
7386 )
7387 }
7388 AlterTableTarget::RenameConstraint { old, new } => {
7389 write!(
7390 f,
7391 "RENAME CONSTRAINT {} TO {}",
7392 quote_ident(old),
7393 quote_ident(new)
7394 )
7395 }
7396 AlterTableTarget::RenameTable { new } => {
7397 write!(f, "RENAME TO {}", quote_ident(new))
7398 }
7399 AlterTableTarget::SetTriggerEnabled { which, enabled } => {
7400 f.write_str(if *enabled {
7401 "ENABLE TRIGGER "
7402 } else {
7403 "DISABLE TRIGGER "
7404 })?;
7405 match which {
7406 TriggerSelector::All => f.write_str("ALL"),
7407 TriggerSelector::Named(n) => f.write_str("e_ident(n)),
7408 }
7409 }
7410 AlterTableTarget::SetRowSecurity { enabled, force } => match (enabled, force) {
7411 (Some(true), _) => f.write_str("ENABLE ROW LEVEL SECURITY"),
7412 (Some(false), _) => f.write_str("DISABLE ROW LEVEL SECURITY"),
7413 (_, Some(true)) => f.write_str("FORCE ROW LEVEL SECURITY"),
7414 (_, Some(false)) => f.write_str("NO FORCE ROW LEVEL SECURITY"),
7415 (None, None) => Ok(()),
7416 },
7417 AlterTableTarget::AttachPartition { child, bounds } => {
7418 write!(f, "ATTACH PARTITION {} ", quote_ident(child))?;
7419 match bounds {
7420 PartitionOfBoundsAst::Range { lower, upper } => {
7421 write!(f, "FOR VALUES FROM ({}) TO ({})", *lower, *upper)
7422 }
7423 PartitionOfBoundsAst::List { values } => {
7424 f.write_str("FOR VALUES IN (")?;
7425 for (i, v) in values.iter().enumerate() {
7426 if i > 0 {
7427 f.write_str(", ")?;
7428 }
7429 write!(f, "{}", v)?;
7430 }
7431 f.write_str(")")
7432 }
7433 PartitionOfBoundsAst::Hash { modulus, remainder } => {
7434 write!(
7435 f,
7436 "FOR VALUES WITH (MODULUS {}, REMAINDER {})",
7437 modulus, remainder
7438 )
7439 }
7440 PartitionOfBoundsAst::Default => f.write_str("DEFAULT"),
7441 }
7442 }
7443 AlterTableTarget::DetachPartition {
7444 child,
7445 concurrently,
7446 finalize,
7447 } => {
7448 write!(f, "DETACH PARTITION {}", quote_ident(child))?;
7449 if *concurrently {
7450 f.write_str(" CONCURRENTLY")?;
7451 }
7452 if *finalize {
7453 f.write_str(" FINALIZE")?;
7454 }
7455 Ok(())
7456 }
7457 AlterTableTarget::AlterColumnSetDefault {
7458 column,
7459 default_expr,
7460 } => write!(
7461 f,
7462 "ALTER COLUMN {} SET DEFAULT {}",
7463 quote_ident(column),
7464 default_expr
7465 ),
7466 AlterTableTarget::AlterColumnDropDefault { column } => {
7467 write!(f, "ALTER COLUMN {} DROP DEFAULT", quote_ident(column))
7468 }
7469 AlterTableTarget::AlterColumnSetNotNull { column } => {
7470 write!(f, "ALTER COLUMN {} SET NOT NULL", quote_ident(column))
7471 }
7472 AlterTableTarget::AlterColumnDropNotNull { column } => {
7473 write!(f, "ALTER COLUMN {} DROP NOT NULL", quote_ident(column))
7474 }
7475 AlterTableTarget::AlterColumnRestart { column, with } => {
7476 write!(f, "ALTER COLUMN {} RESTART", quote_ident(column))?;
7477 if let Some(n) = with {
7478 write!(f, " WITH {n}")?;
7479 }
7480 Ok(())
7481 }
7482 AlterTableTarget::AlterColumnDropExpression { column, if_exists } => {
7483 write!(
7484 f,
7485 "ALTER COLUMN {} DROP EXPRESSION{}",
7486 quote_ident(column),
7487 if *if_exists { " IF EXISTS" } else { "" }
7488 )
7489 }
7490 AlterTableTarget::AlterColumnDropIdentity { column, if_exists } => {
7491 write!(
7492 f,
7493 "ALTER COLUMN {} DROP IDENTITY{}",
7494 quote_ident(column),
7495 if *if_exists { " IF EXISTS" } else { "" }
7496 )
7497 }
7498 AlterTableTarget::AlterColumnSetExpression { column, expr } => {
7499 write!(
7500 f,
7501 "ALTER COLUMN {} SET EXPRESSION AS ({expr})",
7502 quote_ident(column)
7503 )
7504 }
7505 }
7506}
7507
7508impl fmt::Display for TableConstraint {
7509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7510 match self {
7511 Self::PrimaryKey { name, columns, .. } => {
7512 if let Some(n) = name {
7513 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7514 }
7515 f.write_str("PRIMARY KEY (")?;
7516 for (i, c) in columns.iter().enumerate() {
7517 if i > 0 {
7518 f.write_str(", ")?;
7519 }
7520 f.write_str("e_ident(c))?;
7521 }
7522 f.write_str(")")
7523 }
7524 Self::Unique {
7525 name,
7526 columns,
7527 nulls_not_distinct,
7528 ..
7529 } => {
7530 if let Some(n) = name {
7531 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7532 }
7533 f.write_str("UNIQUE ")?;
7534 if *nulls_not_distinct {
7535 f.write_str("NULLS NOT DISTINCT ")?;
7536 }
7537 f.write_str("(")?;
7538 for (i, c) in columns.iter().enumerate() {
7539 if i > 0 {
7540 f.write_str(", ")?;
7541 }
7542 f.write_str("e_ident(c))?;
7543 }
7544 f.write_str(")")
7545 }
7546 Self::Check {
7547 name,
7548 expr,
7549 not_valid,
7550 } => {
7551 if let Some(n) = name {
7552 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7553 }
7554 write!(f, "CHECK ({expr})")?;
7555 if *not_valid {
7556 write!(f, " NOT VALID")?;
7557 }
7558 Ok(())
7559 }
7560 Self::Index {
7561 name,
7562 columns,
7563 prefix_lengths,
7564 } => {
7565 f.write_str("KEY ")?;
7566 if let Some(n) = name {
7567 write!(f, "{} ", quote_ident(n))?;
7568 }
7569 f.write_str("(")?;
7570 for (i, c) in columns.iter().enumerate() {
7571 if i > 0 {
7572 f.write_str(", ")?;
7573 }
7574 f.write_str("e_ident(c))?;
7575 // v7.40.0 — the declared prefix rounds back with it.
7576 if let Some(Some(p)) = prefix_lengths.get(i) {
7577 write!(f, "({p})")?;
7578 }
7579 }
7580 f.write_str(")")
7581 }
7582 Self::FulltextIndex { name, columns } => {
7583 // Mysqldump emits `FULLTEXT KEY name (cols)` —
7584 // Display rounds back to that shape so dump
7585 // replay reproduces the input verbatim.
7586 f.write_str("FULLTEXT KEY ")?;
7587 if let Some(n) = name {
7588 write!(f, "{} ", quote_ident(n))?;
7589 }
7590 f.write_str("(")?;
7591 for (i, c) in columns.iter().enumerate() {
7592 if i > 0 {
7593 f.write_str(", ")?;
7594 }
7595 f.write_str("e_ident(c))?;
7596 }
7597 f.write_str(")")
7598 }
7599 Self::Exclude {
7600 name,
7601 method,
7602 elements,
7603 } => {
7604 if let Some(n) = name {
7605 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
7606 }
7607 f.write_str("EXCLUDE ")?;
7608 if let Some(m) = method {
7609 write!(f, "USING {m} ")?;
7610 }
7611 f.write_str("(")?;
7612 for (i, (col, op)) in elements.iter().enumerate() {
7613 if i > 0 {
7614 f.write_str(", ")?;
7615 }
7616 write!(f, "{} WITH {op}", quote_ident(col))?;
7617 }
7618 f.write_str(")")
7619 }
7620 }
7621 }
7622}
7623
7624impl fmt::Display for ForeignKeyConstraint {
7625 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7626 if let Some(name) = &self.name {
7627 write!(f, "CONSTRAINT {} ", quote_ident(name))?;
7628 }
7629 f.write_str("FOREIGN KEY (")?;
7630 for (i, c) in self.columns.iter().enumerate() {
7631 if i > 0 {
7632 f.write_str(", ")?;
7633 }
7634 f.write_str("e_ident(c))?;
7635 }
7636 write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
7637 if !self.parent_columns.is_empty() {
7638 f.write_str(" (")?;
7639 for (i, c) in self.parent_columns.iter().enumerate() {
7640 if i > 0 {
7641 f.write_str(", ")?;
7642 }
7643 f.write_str("e_ident(c))?;
7644 }
7645 f.write_str(")")?;
7646 }
7647 // Only render non-default actions to keep Display output
7648 // close to user input. SPG's default is RESTRICT (matches
7649 // SQL spec).
7650 if self.on_delete != FkAction::Restrict {
7651 write!(f, " ON DELETE {}", self.on_delete)?;
7652 }
7653 if self.on_update != FkAction::Restrict {
7654 write!(f, " ON UPDATE {}", self.on_update)?;
7655 }
7656 Ok(())
7657 }
7658}
7659
7660impl fmt::Display for FkAction {
7661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7662 match self {
7663 Self::Restrict => f.write_str("RESTRICT"),
7664 Self::Cascade => f.write_str("CASCADE"),
7665 Self::SetNull => f.write_str("SET NULL"),
7666 Self::SetDefault => f.write_str("SET DEFAULT"),
7667 Self::NoAction => f.write_str("NO ACTION"),
7668 }
7669 }
7670}
7671
7672impl fmt::Display for ColumnDef {
7673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7674 // v7.30.1 (mailrs round-24 class audit) — the type position
7675 // must re-parse to the same ColumnDef: a user-defined type
7676 // reference and the MySQL inline ENUM / SET value lists all
7677 // lower `ty` to Text, so rendering `ty` lost them.
7678 write!(f, "{}", quote_ident(&self.name))?;
7679 if let Some(ut) = &self.user_type_ref {
7680 write!(f, " {}", quote_ident(ut))?;
7681 } else if let Some(variants) = &self.inline_enum_variants {
7682 write_variant_list(f, "ENUM", variants)?;
7683 } else if let Some(variants) = &self.inline_set_variants {
7684 write_variant_list(f, "SET", variants)?;
7685 } else {
7686 write!(f, " {}", self.ty)?;
7687 }
7688 if self.is_unsigned {
7689 f.write_str(" UNSIGNED")?;
7690 }
7691 // v7.17.0 Phase 2.5 — render COLLATE for round-trippable
7692 // DDL. Only emits when non-default so the typical output
7693 // stays unchanged.
7694 match self.collation {
7695 Collation::Binary => {}
7696 Collation::CaseInsensitive => f.write_str(" COLLATE \"case_insensitive\"")?,
7697 }
7698 if let Some(d) = &self.default {
7699 write!(f, " DEFAULT {d}")?;
7700 }
7701 if self.auto_increment {
7702 f.write_str(" AUTO_INCREMENT")?;
7703 }
7704 if !self.nullable {
7705 f.write_str(" NOT NULL")?;
7706 }
7707 // v7.30.1 (mailrs round-24 class audit) — inline PRIMARY KEY
7708 // is NOT lifted to a table-level constraint at parse time
7709 // (unlike UNIQUE / CHECK), so the WAL round trip of a
7710 // prepared CREATE TABLE silently dropped the primary key.
7711 if self.is_primary_key {
7712 f.write_str(" PRIMARY KEY")?;
7713 }
7714 // The parser accepts only CURRENT_TIMESTAMP here (stored as
7715 // now()), so that spelling is the lossless round trip.
7716 if self.on_update_runtime.is_some() {
7717 f.write_str(" ON UPDATE CURRENT_TIMESTAMP")?;
7718 }
7719 // v7.37.7 — render GENERATED ALWAYS AS (…) STORED so WAL
7720 // replay reconstructs the computed-column declaration. The
7721 // expression sits inside a single set of parens; STORED is
7722 // the only variant the parser accepts.
7723 if let Some(gen_expr) = &self.generated_stored_expr {
7724 write!(f, " GENERATED ALWAYS AS ({gen_expr}) STORED")?;
7725 }
7726 Ok(())
7727 }
7728}
7729
7730/// v7.30.1 — `ENUM('a', 'b')` / `SET('a', 'b')` inline value-list
7731/// types (MySQL flavour; `ty` is Text underneath).
7732fn write_variant_list(f: &mut fmt::Formatter<'_>, kw: &str, variants: &[String]) -> fmt::Result {
7733 write!(f, " {kw}(")?;
7734 for (i, v) in variants.iter().enumerate() {
7735 if i > 0 {
7736 f.write_str(", ")?;
7737 }
7738 write!(f, "'{}'", v.replace('\'', "''"))?;
7739 }
7740 f.write_str(")")
7741}
7742
7743impl fmt::Display for InsertStatement {
7744 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7745 write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
7746 if let Some(cols) = &self.columns {
7747 f.write_str(" (")?;
7748 for (i, c) in cols.iter().enumerate() {
7749 if i > 0 {
7750 f.write_str(", ")?;
7751 }
7752 f.write_str("e_ident(c))?;
7753 }
7754 f.write_str(")")?;
7755 }
7756 // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
7757 // skipping the VALUES list (mailrs round-5 G4).
7758 if let Some(sel) = &self.select_source {
7759 write!(f, " {sel}")?;
7760 } else {
7761 f.write_str(" VALUES ")?;
7762 for (ri, row) in self.rows.iter().enumerate() {
7763 if ri > 0 {
7764 f.write_str(", ")?;
7765 }
7766 f.write_str("(")?;
7767 for (i, v) in row.iter().enumerate() {
7768 if i > 0 {
7769 f.write_str(", ")?;
7770 }
7771 write!(f, "{v}")?;
7772 }
7773 f.write_str(")")?;
7774 }
7775 }
7776 // v7.30.1 (mailrs round-24) — ON CONFLICT must survive the
7777 // Display round trip: WAL persistence renders the bind-final
7778 // AST through this impl, and a replayed bare INSERT turns a
7779 // legal upsert no-op into a UNIQUE violation that refuses to
7780 // open the catalog.
7781 if let Some(oc) = &self.on_conflict {
7782 write!(f, " {oc}")?;
7783 }
7784 write_returning(self.returning.as_deref(), f)?;
7785 Ok(())
7786 }
7787}
7788
7789/// v7.30.1 (mailrs round-24) — render the ON CONFLICT clause the
7790/// parser produced, so the AST→SQL round trip preserves upsert
7791/// semantics (WAL replay depends on it).
7792impl fmt::Display for OnConflictClause {
7793 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7794 f.write_str("ON CONFLICT")?;
7795 if let Some(name) = &self.constraint_name {
7796 write!(f, " ON CONSTRAINT {name}")?;
7797 }
7798 if !self.target_columns.is_empty() {
7799 f.write_str(" (")?;
7800 for (i, c) in self.target_columns.iter().enumerate() {
7801 if i > 0 {
7802 f.write_str(", ")?;
7803 }
7804 f.write_str("e_ident(c))?;
7805 }
7806 f.write_str(")")?;
7807 }
7808 if let Some(w) = &self.index_where {
7809 write!(f, " WHERE {w}")?;
7810 }
7811 match &self.action {
7812 OnConflictAction::Nothing => f.write_str(" DO NOTHING"),
7813 OnConflictAction::Update {
7814 assignments,
7815 where_,
7816 } => {
7817 f.write_str(" DO UPDATE SET ")?;
7818 for (i, (col, expr)) in assignments.iter().enumerate() {
7819 if i > 0 {
7820 f.write_str(", ")?;
7821 }
7822 write!(f, "{} = {expr}", quote_ident(col))?;
7823 }
7824 if let Some(w) = where_ {
7825 write!(f, " WHERE {w}")?;
7826 }
7827 Ok(())
7828 }
7829 }
7830 }
7831}
7832
7833/// v7.30.1 (mailrs round-24) — shared `RETURNING <projection>`
7834/// tail for the three DML Display impls.
7835fn write_returning(ret: Option<&[SelectItem]>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7836 let Some(items) = ret else {
7837 return Ok(());
7838 };
7839 f.write_str(" RETURNING ")?;
7840 for (i, item) in items.iter().enumerate() {
7841 if i > 0 {
7842 f.write_str(", ")?;
7843 }
7844 write!(f, "{item}")?;
7845 }
7846 Ok(())
7847}
7848
7849impl fmt::Display for UpdateStatement {
7850 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7851 write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
7852 for (i, (col, expr)) in self.assignments.iter().enumerate() {
7853 if i > 0 {
7854 f.write_str(", ")?;
7855 }
7856 write!(f, "{} = {expr}", quote_ident(col))?;
7857 }
7858 if let Some(w) = &self.where_ {
7859 write!(f, " WHERE {w}")?;
7860 }
7861 // v7.39 (round 413) — MySQL `UPDATE … ORDER BY … LIMIT n`.
7862 if let Some(ol) = self.order_limit.as_deref() {
7863 if !ol.order_by.is_empty() {
7864 f.write_str(" ORDER BY ")?;
7865 for (i, o) in ol.order_by.iter().enumerate() {
7866 if i > 0 {
7867 f.write_str(", ")?;
7868 }
7869 write!(f, "{}", o.expr)?;
7870 if o.desc {
7871 f.write_str(" DESC")?;
7872 }
7873 match o.nulls_first {
7874 Some(true) => f.write_str(" NULLS FIRST")?,
7875 Some(false) => f.write_str(" NULLS LAST")?,
7876 None => {}
7877 }
7878 }
7879 }
7880 if let Some(n) = ol.limit {
7881 write!(f, " LIMIT {n}")?;
7882 }
7883 }
7884 write_returning(self.returning.as_deref(), f)?;
7885 Ok(())
7886 }
7887}
7888
7889impl fmt::Display for DeleteStatement {
7890 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7891 write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
7892 if let Some(w) = &self.where_ {
7893 write!(f, " WHERE {w}")?;
7894 }
7895 write_returning(self.returning.as_deref(), f)?;
7896 Ok(())
7897 }
7898}
7899
7900impl fmt::Display for CteBody {
7901 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7902 match self {
7903 Self::Select(s) => write!(f, "{s}"),
7904 Self::Insert(s) => write!(f, "{s}"),
7905 Self::Update(s) => write!(f, "{s}"),
7906 Self::Delete(s) => write!(f, "{s}"),
7907 Self::Merge(s) => write!(f, "{s}"),
7908 }
7909 }
7910}
7911
7912impl fmt::Display for MergeStatement {
7913 // v7.17.0 Phase 3.P0-42 — MERGE display is approximate
7914 // (it round-trips for the cases tests cover, not for
7915 // round-tripping every edge of the surface).
7916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7917 fmt_with_clause(&self.ctes, f)?;
7918 f.write_str("MERGE INTO ")?;
7919 write!(f, "{}", quote_ident(&self.target))?;
7920 if let Some(a) = &self.target_alias {
7921 write!(f, " {}", quote_ident(a))?;
7922 }
7923 f.write_str(" USING ")?;
7924 if let Some(sub) = &self.source_select {
7925 write!(f, "({sub})")?;
7926 } else {
7927 write!(f, "{}", quote_ident(&self.source))?;
7928 }
7929 if let Some(a) = &self.source_alias {
7930 write!(f, " {}", quote_ident(a))?;
7931 }
7932 if !self.source_column_aliases.is_empty() {
7933 f.write_str("(")?;
7934 for (i, c) in self.source_column_aliases.iter().enumerate() {
7935 if i > 0 {
7936 f.write_str(", ")?;
7937 }
7938 write!(f, "{}", quote_ident(c))?;
7939 }
7940 f.write_str(")")?;
7941 }
7942 write!(f, " ON {}", self.on)?;
7943 for clause in &self.clauses {
7944 f.write_str(" WHEN ")?;
7945 f.write_str(match clause.matched {
7946 MergeMatched::Matched => "MATCHED",
7947 MergeMatched::NotMatched => "NOT MATCHED",
7948 MergeMatched::NotMatchedBySource => "NOT MATCHED BY SOURCE",
7949 })?;
7950 if let Some(c) = &clause.condition {
7951 write!(f, " AND {c}")?;
7952 }
7953 f.write_str(" THEN ")?;
7954 match &clause.action {
7955 MergeAction::Insert { columns, values } => {
7956 f.write_str("INSERT ")?;
7957 // A column list is optional (round 146): the bare
7958 // `INSERT VALUES (…)` form maps positionally.
7959 if !columns.is_empty() {
7960 f.write_str("(")?;
7961 for (i, c) in columns.iter().enumerate() {
7962 if i > 0 {
7963 f.write_str(", ")?;
7964 }
7965 write!(f, "{}", quote_ident(c))?;
7966 }
7967 f.write_str(") ")?;
7968 }
7969 f.write_str("VALUES (")?;
7970 for (i, v) in values.iter().enumerate() {
7971 if i > 0 {
7972 f.write_str(", ")?;
7973 }
7974 write!(f, "{v}")?;
7975 }
7976 f.write_str(")")?;
7977 }
7978 MergeAction::Update { assignments } => {
7979 f.write_str("UPDATE SET ")?;
7980 for (i, (c, e)) in assignments.iter().enumerate() {
7981 if i > 0 {
7982 f.write_str(", ")?;
7983 }
7984 write!(f, "{} = {e}", quote_ident(c))?;
7985 }
7986 }
7987 MergeAction::Delete => f.write_str("DELETE")?,
7988 MergeAction::DoNothing => f.write_str("DO NOTHING")?,
7989 }
7990 }
7991 if let Some(items) = &self.returning {
7992 f.write_str(" RETURNING ")?;
7993 for (i, it) in items.iter().enumerate() {
7994 if i > 0 {
7995 f.write_str(", ")?;
7996 }
7997 write!(f, "{it}")?;
7998 }
7999 }
8000 Ok(())
8001 }
8002}
8003
8004/// Shared `WITH <cte> [, …] ` prefix renderer — SELECT and MERGE both
8005/// carry a CTE list and must round-trip it identically.
8006fn fmt_with_clause(ctes: &[Cte], f: &mut fmt::Formatter<'_>) -> fmt::Result {
8007 if ctes.is_empty() {
8008 return Ok(());
8009 }
8010 f.write_str("WITH ")?;
8011 if ctes.iter().any(|c| c.recursive) {
8012 f.write_str("RECURSIVE ")?;
8013 }
8014 for (i, cte) in ctes.iter().enumerate() {
8015 if i > 0 {
8016 f.write_str(", ")?;
8017 }
8018 f.write_str("e_ident(&cte.name))?;
8019 if !cte.column_overrides.is_empty() {
8020 f.write_str(" (")?;
8021 for (ci, c) in cte.column_overrides.iter().enumerate() {
8022 if ci > 0 {
8023 f.write_str(", ")?;
8024 }
8025 f.write_str("e_ident(c))?;
8026 }
8027 f.write_str(")")?;
8028 }
8029 write!(f, " AS ({})", cte.body)?;
8030 }
8031 f.write_str(" ")
8032}
8033
8034impl fmt::Display for SelectStatement {
8035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8036 // v7.30.1 (mailrs round-24 class audit) — the WITH clause
8037 // must survive the round trip; a CTE-using statement
8038 // re-parsed without it references undefined tables.
8039 fmt_with_clause(&self.ctes, f)?;
8040 write_bare_select(self, f)?;
8041 for (kind, peer) in &self.unions {
8042 f.write_str(match kind {
8043 UnionKind::Distinct => " UNION ",
8044 UnionKind::All => " UNION ALL ",
8045 UnionKind::Intersect => " INTERSECT ",
8046 UnionKind::IntersectAll => " INTERSECT ALL ",
8047 UnionKind::Except => " EXCEPT ",
8048 UnionKind::ExceptAll => " EXCEPT ALL ",
8049 })?;
8050 write_bare_select(peer, f)?;
8051 }
8052 if !self.order_by.is_empty() {
8053 f.write_str(" ORDER BY ")?;
8054 for (i, o) in self.order_by.iter().enumerate() {
8055 if i > 0 {
8056 f.write_str(", ")?;
8057 }
8058 write!(f, "{}", o.expr)?;
8059 if o.desc {
8060 f.write_str(" DESC")?;
8061 }
8062 match o.nulls_first {
8063 Some(true) => f.write_str(" NULLS FIRST")?,
8064 Some(false) => f.write_str(" NULLS LAST")?,
8065 None => {}
8066 }
8067 }
8068 }
8069 // v7.30.1 (mailrs round-24 class audit) — WITH TIES only
8070 // exists in the FETCH FIRST spelling; rendering it as LIMIT
8071 // dropped the tie-extension semantics on replay. The parser
8072 // accepts OFFSET before FETCH, so keep that order here.
8073 if self.limit_with_ties {
8074 if let Some(o) = &self.offset {
8075 write!(f, " OFFSET {o}")?;
8076 }
8077 if let Some(n) = &self.limit {
8078 write!(f, " FETCH FIRST {n} ROWS WITH TIES")?;
8079 }
8080 } else {
8081 if let Some(n) = &self.limit {
8082 write!(f, " LIMIT {n}")?;
8083 }
8084 if let Some(o) = &self.offset {
8085 write!(f, " OFFSET {o}")?;
8086 }
8087 }
8088 Ok(())
8089 }
8090}
8091
8092fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8093 f.write_str("SELECT ")?;
8094 if s.distinct {
8095 f.write_str("DISTINCT ")?;
8096 }
8097 write_bare_select_body(s, f)
8098}
8099
8100fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8101 for (i, item) in s.items.iter().enumerate() {
8102 if i > 0 {
8103 f.write_str(", ")?;
8104 }
8105 write!(f, "{item}")?;
8106 }
8107 if let Some(t) = &s.from {
8108 write!(f, " FROM {t}")?;
8109 }
8110 if let Some(e) = &s.where_ {
8111 write!(f, " WHERE {e}")?;
8112 }
8113 if let Some(gs) = &s.group_by {
8114 f.write_str(" GROUP BY ")?;
8115 for (i, g) in gs.iter().enumerate() {
8116 if i > 0 {
8117 f.write_str(", ")?;
8118 }
8119 write!(f, "{g}")?;
8120 }
8121 } else if s.group_by_all {
8122 // v7.30.1 (mailrs round-24 class audit) — the GROUP BY ALL
8123 // shortcut parses to group_by: None + this flag; dropping
8124 // it turned an aggregate query into a bare projection on
8125 // re-parse.
8126 f.write_str(" GROUP BY ALL")?;
8127 }
8128 if let Some(h) = &s.having {
8129 write!(f, " HAVING {h}")?;
8130 }
8131 Ok(())
8132}
8133
8134impl fmt::Display for SelectItem {
8135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8136 match self {
8137 Self::Wildcard => f.write_str("*"),
8138 Self::QualifiedWildcard(q) => write!(f, "{}.*", quote_ident(q)),
8139 Self::Expr { expr, alias } => {
8140 write!(f, "{expr}")?;
8141 if let Some(a) = alias {
8142 write!(f, " AS {}", quote_ident(a))?;
8143 }
8144 Ok(())
8145 }
8146 }
8147 }
8148}
8149
8150impl fmt::Display for FromClause {
8151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8152 write!(f, "{}", self.primary)?;
8153 for j in &self.joins {
8154 match j.kind {
8155 JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
8156 JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
8157 JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
8158 JoinKind::Right => write!(f, " RIGHT JOIN {}", j.table)?,
8159 JoinKind::FullOuter => write!(f, " FULL OUTER JOIN {}", j.table)?,
8160 JoinKind::Semi => write!(f, " SEMI JOIN {}", j.table)?,
8161 }
8162 if let Some(on) = &j.on {
8163 write!(f, " ON {on}")?;
8164 }
8165 }
8166 Ok(())
8167 }
8168}
8169
8170/// v7.39 (round 205) — render a JSON_TABLE COLUMNS list (recursive
8171/// for NESTED). Kept close to the parser's grammar so it re-parses.
8172fn fmt_json_table_columns(f: &mut fmt::Formatter<'_>, cols: &[JsonTableColumn]) -> fmt::Result {
8173 for (i, c) in cols.iter().enumerate() {
8174 if i > 0 {
8175 f.write_str(", ")?;
8176 }
8177 match c {
8178 JsonTableColumn::Ordinality { name } => {
8179 write!(f, "{} FOR ORDINALITY", quote_ident(name))?;
8180 }
8181 JsonTableColumn::Nested { path, columns } => {
8182 write!(f, "NESTED PATH '{path}' COLUMNS (")?;
8183 fmt_json_table_columns(f, columns)?;
8184 f.write_str(")")?;
8185 }
8186 JsonTableColumn::Regular {
8187 name,
8188 ty,
8189 path,
8190 exists,
8191 format_json,
8192 wrapper,
8193 on_empty,
8194 on_error,
8195 } => {
8196 write!(f, "{} {ty}", quote_ident(name))?;
8197 if *format_json {
8198 f.write_str(" FORMAT JSON")?;
8199 }
8200 if *exists {
8201 write!(f, " EXISTS PATH '{path}'")?;
8202 } else {
8203 write!(f, " PATH '{path}'")?;
8204 }
8205 if *wrapper {
8206 f.write_str(" WITH WRAPPER")?;
8207 }
8208 if let JsonTableOnBehavior::Error = on_empty {
8209 f.write_str(" ERROR ON EMPTY")?;
8210 } else if let JsonTableOnBehavior::Default(e) = on_empty {
8211 write!(f, " DEFAULT {e} ON EMPTY")?;
8212 }
8213 if let JsonTableOnBehavior::Error = on_error {
8214 f.write_str(" ERROR ON ERROR")?;
8215 } else if let JsonTableOnBehavior::Default(e) = on_error {
8216 write!(f, " DEFAULT {e} ON ERROR")?;
8217 }
8218 }
8219 }
8220 }
8221 Ok(())
8222}
8223
8224impl fmt::Display for TableRef {
8225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8226 // v7.30.1 (mailrs round-24 class audit) — the dynamic
8227 // table-ref shapes must round-trip: rendering only the
8228 // (synthetic) name turned LATERAL / unnest() /
8229 // generate_series() into references to nonexistent tables
8230 // on re-parse.
8231 // v7.39 (round 205) — JSON_TABLE round-trips through Display
8232 // (view bodies, WAL replay of `INSERT … SELECT FROM JSON_TABLE`).
8233 if let Some(jt) = &self.json_table {
8234 write!(f, "JSON_TABLE({}, '{}'", jt.doc, jt.row_path)?;
8235 if !jt.passing.is_empty() {
8236 f.write_str(" PASSING ")?;
8237 for (i, (n, e)) in jt.passing.iter().enumerate() {
8238 if i > 0 {
8239 f.write_str(", ")?;
8240 }
8241 write!(f, "{e} AS {}", quote_ident(n))?;
8242 }
8243 }
8244 f.write_str(" COLUMNS (")?;
8245 fmt_json_table_columns(f, &jt.columns)?;
8246 f.write_str(")")?;
8247 if let Some(a) = &self.alias {
8248 write!(f, " AS {}", quote_ident(a))?;
8249 }
8250 return Ok(());
8251 }
8252 if let Some(inner) = &self.lateral_subquery {
8253 write!(f, "LATERAL ({inner})")?;
8254 if let Some(a) = &self.alias {
8255 write!(f, " AS {}", quote_ident(a))?;
8256 // v7.37 D.28 — a derived table on the lateral_subquery channel
8257 // may carry `AS t(cols)` column aliases (e.g. `(VALUES …) t(g)`
8258 // lowers here). Rendering the alias without the column list lost
8259 // the column names on re-parse (a view body round-trips through
8260 // Display), so `SELECT g FROM the_view` failed ColumnNotFound.
8261 if !self.unnest_column_aliases.is_empty() {
8262 f.write_str(" (")?;
8263 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8264 if i > 0 {
8265 f.write_str(", ")?;
8266 }
8267 f.write_str("e_ident(c))?;
8268 }
8269 f.write_str(")")?;
8270 }
8271 }
8272 return Ok(());
8273 }
8274 if let Some(expr) = &self.unnest_expr {
8275 write!(f, "UNNEST({expr})")?;
8276 if let Some(a) = &self.alias {
8277 write!(f, " AS {}", quote_ident(a))?;
8278 if !self.unnest_column_aliases.is_empty() {
8279 f.write_str(" (")?;
8280 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8281 if i > 0 {
8282 f.write_str(", ")?;
8283 }
8284 f.write_str("e_ident(c))?;
8285 }
8286 f.write_str(")")?;
8287 }
8288 }
8289 return Ok(());
8290 }
8291 // 7.38.1 S5.1 — a FROM-position table function must re-render
8292 // as the CALL, not its bare name: ARRAY(subquery) desugars by
8293 // re-parsing the subquery's canonical text, and a dropped
8294 // argument list turned `pg_options_to_table(x)` into a
8295 // relation lookup that does not exist.
8296 if let Some(call) = &self.table_fn_call {
8297 let (fn_name, args) = call.as_ref();
8298 write!(f, "{fn_name}(")?;
8299 for (i, a) in args.iter().enumerate() {
8300 if i > 0 {
8301 f.write_str(", ")?;
8302 }
8303 write!(f, "{a}")?;
8304 }
8305 f.write_str(")")?;
8306 if let Some(a) = &self.alias {
8307 write!(f, " AS {}", quote_ident(a))?;
8308 if !self.unnest_column_aliases.is_empty() {
8309 f.write_str("(")?;
8310 for (i, c) in self.unnest_column_aliases.iter().enumerate() {
8311 if i > 0 {
8312 f.write_str(", ")?;
8313 }
8314 write!(f, "{}", quote_ident(c))?;
8315 }
8316 f.write_str(")")?;
8317 }
8318 }
8319 return Ok(());
8320 }
8321 if let Some(args) = &self.generate_series_args {
8322 f.write_str("generate_series(")?;
8323 for (i, a) in args.iter().enumerate() {
8324 if i > 0 {
8325 f.write_str(", ")?;
8326 }
8327 write!(f, "{a}")?;
8328 }
8329 f.write_str(")")?;
8330 if let Some(a) = &self.alias {
8331 write!(f, " AS {}", quote_ident(a))?;
8332 }
8333 return Ok(());
8334 }
8335 write!(f, "{}", quote_ident(&self.name))?;
8336 if let Some(seg) = self.as_of_segment {
8337 write!(f, " AS OF SEGMENT {seg}")?;
8338 }
8339 if let Some(a) = &self.alias {
8340 write!(f, " AS {}", quote_ident(a))?;
8341 }
8342 Ok(())
8343 }
8344}
8345
8346impl fmt::Display for ColumnName {
8347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8348 if let Some(q) = &self.qualifier {
8349 write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
8350 } else {
8351 write!(f, "{}", quote_ident(&self.name))
8352 }
8353 }
8354}
8355
8356/// v7.39 (round 311) — render the left spine of an AND / OR chain
8357/// without re-parenthesising each step, so `((a AND b) AND c)` comes out
8358/// as `(a) AND (b) AND (c)` the way PG's deparse writes it. Only the
8359/// SAME operator flattens; anything else is an ordinary operand.
8360fn write_bool_chain(f: &mut fmt::Formatter<'_>, e: &Expr, op: BinOp) -> fmt::Result {
8361 if let Expr::Binary {
8362 lhs,
8363 op: inner,
8364 rhs,
8365 } = e
8366 && *inner == op
8367 {
8368 write_bool_chain(f, lhs, op)?;
8369 return write!(f, " {op} {rhs}");
8370 }
8371 write!(f, "{e}")
8372}
8373
8374/// v7.39 (round 311, V32) — PG's PRETTY deparse of an expression, the
8375/// form `pg_get_constraintdef(oid, true)` and friends return.
8376///
8377/// The default [`fmt::Display`] parenthesises every operator node, which
8378/// is what PG's non-pretty deparse does and what makes the text
8379/// round-trip. Pretty drops the pairs the grammar can put back, and the
8380/// rule is NOT plain precedence minimisation — measured against PG 18.4
8381/// across 37 shapes:
8382///
8383/// * the boolean layer follows precedence (NOT > AND > OR): an OR
8384/// under an AND keeps its parens, an AND under an OR does not, and a
8385/// comparison under any of them does not (`NOT a > 1`);
8386/// * an associative chain flattens completely, even where the source
8387/// nested it to the right (`a AND (b AND c)` prints as one chain);
8388/// * but an operand of a comparison or arithmetic operator keeps its
8389/// parens whenever it is itself an operator expression — so
8390/// `(a + b) > 10` and `(- a) + b`, even though precedence alone
8391/// would not require either. A cast, function call, column or
8392/// literal in that position does not (`a::text = t`,
8393/// `length(code) > 2`); a cast counts as compound exactly when the
8394/// thing it casts is (`((a + b)::text) = t`).
8395///
8396/// Anything outside that layer defers to `Display`, which is never
8397/// wrong — only more parenthesised than PG would print.
8398#[must_use]
8399pub fn pretty_expr(e: &Expr) -> String {
8400 let mut out = String::new();
8401 write_pretty(&mut out, e, PrettyParent::None, false, false);
8402 out
8403}
8404
8405/// v7.39 (round 527) — the same deparse, spelling a cast the way MySQL
8406/// writes it.
8407///
8408/// MariaDB names the offending expression in its out-of-range message
8409/// and quotes the user's own syntax: `cast(1 as unsigned) - 2`. SPG
8410/// answered `1::unsigned - 2` — PG's spelling, in a message going to a
8411/// MySQL client, for a cast the client had just written the other way.
8412#[must_use]
8413pub fn pretty_expr_mysql(e: &Expr) -> String {
8414 let mut out = String::new();
8415 write_pretty(&mut out, e, PrettyParent::None, false, true);
8416 out
8417}
8418
8419/// v7.39 (round 505) — how strongly an expression suggests its own column
8420/// name. A cast keeps its argument's name only when that name is STRONG;
8421/// otherwise the cast reports the type it casts to.
8422///
8423/// Deduced from measurement, not from a rulebook. `upper(s)::text` names
8424/// itself `upper` on PG18 but `(CASE WHEN a=1 THEN 1 END)::text` names
8425/// itself `text` — so `case` and a function name cannot be the same kind of
8426/// answer, even though a bare `CASE …` does report `case`.
8427#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8428enum NameStrength {
8429 /// Nothing to go on — PG reports `?column?`.
8430 None,
8431 /// A name, but one a cast overrides: `case`, or a type name.
8432 Weak,
8433 /// A name a cast keeps: a column, or the function that produced it.
8434 Strong,
8435}
8436
8437/// v7.39 (round 505) — the column name PG18 gives a projected expression
8438/// that carries no `AS` alias. `None` means `?column?`.
8439///
8440/// SPG used to print the parsed expression back out, which matched neither
8441/// oracle and made name-keyed row access miss on both wires:
8442///
8443/// | query | PG18 | SPG (before) |
8444/// |--------------|------------|--------------|
8445/// | `upper(s)` | `upper` | `upper(s)` |
8446/// | `a+b` | `?column?` | `(a + b)` |
8447/// | `'lit'` | `?column?` | `'lit'` |
8448/// | `CASE …` | `case` | `CASE WHEN (a = 1) THEN …` |
8449///
8450/// Every rule below is one of those measurements, taken with `\gdesc`
8451/// against PG18: a call is named for its function, a cast recurses into its
8452/// argument and falls back to the type, a scalar subquery takes the name of
8453/// the column it selects, and operators have no name at all.
8454#[must_use]
8455pub fn figure_column_name(expr: &Expr) -> Option<String> {
8456 let (name, _) = figure_name_inner(expr);
8457 name
8458}
8459
8460/// The name a function reports, which is not always the name SPG parsed it
8461/// under: `count(*)` is held as `count_star` so the star arity survives the
8462/// AST, and that internal spelling must not reach a client. PG18 reports
8463/// `count`.
8464/// v7.39.13 — public, because Describe was naming the same call from a
8465/// second map that did not have this entry.
8466///
8467/// `count(*)` is held as `count_star` so the star arity survives the
8468/// AST. The projection mapped it back and the extended protocol's
8469/// Describe did not, so `SELECT count(*) OVER ()` answered `count` in
8470/// the row stream and `count_star` to `\gdesc` — an ORM-visible column
8471/// name, and two answers to one question. Reported by sentori against
8472/// 7.39.12.
8473#[must_use]
8474pub fn canonical_function_name(name: &str) -> String {
8475 match name {
8476 "count_star" => "count".to_string(),
8477 other => other.to_ascii_lowercase(),
8478 }
8479}
8480
8481/// v7.38.7 — a cast target's `pg_type.typname`, for the name a cast
8482/// reports when its operand has none of its own. Only the spellings that
8483/// differ from what the user writes need an entry; everything else is
8484/// already its own typname.
8485fn cast_target_typname(target: &CastTarget) -> String {
8486 let written = target.to_string().to_ascii_lowercase();
8487 let base = written.strip_suffix("[]").unwrap_or(&written);
8488 let mapped = match base {
8489 "bigint" => "int8",
8490 "integer" | "int" => "int4",
8491 "smallint" => "int2",
8492 "boolean" => "bool",
8493 "double precision" => "float8",
8494 "real" => "float4",
8495 "character varying" => "varchar",
8496 "character" => "bpchar",
8497 "timestamp with time zone" => "timestamptz",
8498 "timestamp without time zone" => "timestamp",
8499 "time without time zone" => "time",
8500 "decimal" => "numeric",
8501 other => other,
8502 };
8503 if written.ends_with("[]") {
8504 alloc::format!("_{mapped}")
8505 } else {
8506 String::from(mapped)
8507 }
8508}
8509
8510fn figure_name_inner(expr: &Expr) -> (Option<String>, NameStrength) {
8511 let strong = |n: String| (Some(n), NameStrength::Strong);
8512 match expr {
8513 // A column keeps its own name, qualifier and all discarded:
8514 // `lbl.a` reports `a`.
8515 Expr::Column(c) => strong(c.name.clone()),
8516 // Calls are named for the function. This covers the shapes that
8517 // only LOOK like syntax — `EXTRACT(year FROM …)` reports
8518 // `extract`, `SUBSTRING(x FROM 1 FOR 2)` reports `substring` —
8519 // because PG resolves them to functions before naming them.
8520 Expr::FunctionCall { name, .. } | Expr::WindowFunction { name, .. } => {
8521 strong(canonical_function_name(name))
8522 }
8523 Expr::AggregateOrdered { call, .. } => figure_name_inner(call),
8524 Expr::Extract { .. } => strong("extract".to_string()),
8525 Expr::Exists { .. } => strong("exists".to_string()),
8526 Expr::Array(_) => strong("array".to_string()),
8527 // `(expr).field` is named for the field, as a column would be.
8528 Expr::FieldAccess { field, .. } => strong(field.clone()),
8529 // v7.39.12 — PostgreSQL names a subscript after its operand, so
8530 // `arr[1]` is `arr`. There was no arm, so it fell through to
8531 // `?column?`. Reported by sentori against 7.39.11 — the same
8532 // naming defect v7.38.20 closed, reached through a different
8533 // expression. Weak, like the field access above it: an outer
8534 // cast or function still names the column.
8535 Expr::ArraySubscript { target, .. } => (figure_name_inner(target).0, NameStrength::Weak),
8536 // A cast prefers its argument's name and settles for the type:
8537 // `upper(s)::text` is `upper`, `(a+b)::text` is `text`.
8538 Expr::Cast {
8539 expr: inner,
8540 target,
8541 } => match figure_name_inner(inner) {
8542 (Some(n), NameStrength::Strong) => strong(n),
8543 // v7.38.7 — the fallback is the target type's INTERNAL name,
8544 // which is what PG reports: `SELECT 7::bigint` is `int8`, not
8545 // the `bigint` the user typed. Measured on PG18 alongside
8546 // `CAST(7 AS bigint)`, which answers `int8` too.
8547 _ => (Some(cast_target_typname(target)), NameStrength::Weak),
8548 },
8549 // A scalar subquery reports whatever its single output column
8550 // reports: `(SELECT max(b) …)` is `max`, `(SELECT a+b …)` is not.
8551 Expr::ScalarSubquery(sel) => scalar_subquery_name(sel),
8552 // `CASE …` names itself, but weakly — a cast around it wins.
8553 Expr::Case { .. } => (Some("case".to_string()), NameStrength::Weak),
8554 // A literal that carries its own type names itself for that type:
8555 // `INTERVAL '1 day'` reports `interval`, while a bare `'1 day'`
8556 // reports nothing. Weak, like any other type name.
8557 Expr::Literal(Literal::Interval { .. }) => {
8558 (Some("interval".to_string()), NameStrength::Weak)
8559 }
8560 // A wrapper that adds no name of its own.
8561 Expr::Variadic(inner) => figure_name_inner(inner),
8562 Expr::NamedArg { expr: inner, .. } => figure_name_inner(inner),
8563 // Everything else — operators, comparisons, IS NULL, LIKE, IN,
8564 // literals, placeholders — reports `?column?`.
8565 _ => (None, NameStrength::None),
8566 }
8567}
8568
8569/// The name a scalar subquery's single projected column reports.
8570fn scalar_subquery_name(sel: &SelectStatement) -> (Option<String>, NameStrength) {
8571 match sel.items.as_slice() {
8572 [SelectItem::Expr { alias: Some(a), .. }] => (Some(a.clone()), NameStrength::Strong),
8573 [SelectItem::Expr { expr, alias: None }] => figure_name_inner(expr),
8574 _ => (None, NameStrength::None),
8575 }
8576}
8577
8578/// Binding power. Higher binds tighter; 0 means "no enclosing operator".
8579fn pretty_prec(e: &Expr) -> u8 {
8580 match e {
8581 Expr::Binary { op, .. } => match op {
8582 // v7.39 (round 407) — this deparse ladder mirrors the parser's:
8583 // OR < XOR < AND < NOT < comparison < additive < multiplicative.
8584 // XOR (MySQL-only) sits between OR and AND, so AND and everything
8585 // above shifted +1 to open rung 2 for it.
8586 BinOp::Or => 1,
8587 BinOp::LogicalXor => 2,
8588 BinOp::And => 3,
8589 BinOp::Add | BinOp::Sub | BinOp::Concat => 6,
8590 BinOp::Mul | BinOp::Div | BinOp::Mod => 7,
8591 // Everything else in this enum is a comparison-shaped
8592 // operator; they share one level, as in the grammar.
8593 _ => 5,
8594 },
8595 Expr::Unary { op, .. } => match op {
8596 UnOp::Not => 4,
8597 UnOp::Neg | UnOp::BitNot | UnOp::Plus => 8,
8598 },
8599 _ => u8::MAX,
8600 }
8601}
8602
8603/// Is this node an operator expression — the thing an arithmetic or
8604/// comparison parent keeps parentheses around? A cast inherits the
8605/// answer from what it casts.
8606fn pretty_is_compound(e: &Expr) -> bool {
8607 match e {
8608 Expr::Binary { .. } | Expr::Unary { .. } => true,
8609 Expr::Cast { expr, .. } => pretty_is_compound(expr),
8610 _ => false,
8611 }
8612}
8613
8614/// `parent` describes the enclosing operator: its binding power, and
8615/// whether it is a comparison (which keeps parens around any operator
8616/// operand) or a NOT (which keeps them at equal power too).
8617#[derive(Clone, Copy, PartialEq)]
8618enum PrettyParent {
8619 /// Nothing encloses this node.
8620 None,
8621 /// A comparison-shaped operator: an operator operand always keeps
8622 /// its parens, whatever precedence would allow.
8623 Comparison,
8624 /// Arithmetic / concatenation: precedence decides.
8625 Arith(u8),
8626 /// A boolean connective: precedence decides.
8627 Bool(u8),
8628 /// `NOT`: precedence decides, but equal power still needs parens so
8629 /// `NOT (NOT a > 1)` does not collapse.
8630 Not,
8631}
8632
8633fn write_pretty(out: &mut String, e: &Expr, parent: PrettyParent, is_rhs: bool, mysql: bool) {
8634 let prec = pretty_prec(e);
8635 let is_unary_sign = matches!(
8636 e,
8637 Expr::Unary {
8638 op: UnOp::Neg | UnOp::BitNot | UnOp::Plus,
8639 ..
8640 }
8641 );
8642 let needs = match parent {
8643 PrettyParent::None => false,
8644 PrettyParent::Comparison => pretty_is_compound(e),
8645 // A sign always keeps its parens under an operator — PG writes
8646 // `(- a) + b` even though precedence would not require it.
8647 PrettyParent::Arith(p) => {
8648 is_unary_sign
8649 || (matches!(e, Expr::Binary { .. } | Expr::Unary { .. })
8650 && (prec < p || (prec == p && is_rhs)))
8651 }
8652 PrettyParent::Bool(p) => matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec < p,
8653 PrettyParent::Not => {
8654 matches!(e, Expr::Binary { .. } | Expr::Unary { .. }) && prec <= pretty_prec_not()
8655 }
8656 };
8657 if needs {
8658 out.push('(');
8659 }
8660 match e {
8661 Expr::Binary { lhs, op, rhs } => {
8662 let child = match op {
8663 BinOp::And | BinOp::Or => PrettyParent::Bool(prec),
8664 BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod | BinOp::Concat => {
8665 PrettyParent::Arith(prec)
8666 }
8667 _ => PrettyParent::Comparison,
8668 };
8669 write_pretty(out, lhs, child, false, mysql);
8670 out.push(' ');
8671 out.push_str(&alloc::format!("{op}"));
8672 out.push(' ');
8673 // AND / OR are associative, so an explicitly right-nested
8674 // chain still prints as one chain.
8675 let rhs_is_rhs = !matches!(op, BinOp::And | BinOp::Or);
8676 write_pretty(out, rhs, child, rhs_is_rhs, mysql);
8677 }
8678 Expr::Unary { op, expr } => match op {
8679 UnOp::Not => {
8680 out.push_str("NOT ");
8681 write_pretty(out, expr, PrettyParent::Not, false, mysql);
8682 }
8683 UnOp::Neg => {
8684 out.push_str("- ");
8685 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8686 }
8687 UnOp::Plus => {
8688 out.push_str("+ ");
8689 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8690 }
8691 UnOp::BitNot => {
8692 out.push('~');
8693 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8694 }
8695 },
8696 Expr::Cast { expr, target } => {
8697 if mysql {
8698 // MySQL's own spelling, which is what its error messages
8699 // quote back.
8700 out.push_str("cast(");
8701 write_pretty(out, expr, PrettyParent::None, false, mysql);
8702 out.push_str(&alloc::format!(
8703 " as {})",
8704 target.to_string().to_lowercase()
8705 ));
8706 } else {
8707 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8708 out.push_str(&alloc::format!("::{target}"));
8709 }
8710 }
8711 Expr::IsNull { expr, negated } => {
8712 write_pretty(out, expr, PrettyParent::Comparison, false, mysql);
8713 out.push_str(if *negated { " IS NOT NULL" } else { " IS NULL" });
8714 }
8715 other => out.push_str(&alloc::format!("{other}")),
8716 }
8717 if needs {
8718 out.push(')');
8719 }
8720}
8721
8722const fn pretty_prec_not() -> u8 {
8723 // Must match `pretty_prec`'s `UnOp::Not` rung (v7.39 round 407: 3 → 4
8724 // when the XOR insertion shifted the deparse ladder up by one).
8725 4
8726}
8727
8728impl fmt::Display for Expr {
8729 #[allow(clippy::too_many_lines)]
8730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8731 match self {
8732 Self::Literal(l) => write!(f, "{l}"),
8733 Self::Column(c) => write!(f, "{c}"),
8734 Self::Placeholder(n) => write!(f, "${n}"),
8735 // Round-trips as the spelling PG's docs lead with.
8736 Self::NamedArg { name, expr } => write!(f, "{} := {expr}", quote_ident(name)),
8737 Self::Variadic(expr) => write!(f, "VARIADIC {expr}"),
8738 // Round-trips with the name quoted, which is how PG spells a
8739 // collation everywhere: `"en_US.utf8"`, `"C"`.
8740 Self::Collate { expr, collation } => {
8741 write!(f, "{expr} COLLATE {}", quote_ident(collation))
8742 }
8743 // v7.39 (round 311) — an AND / OR chain that nests to the
8744 // LEFT is one chain, and renders flat: `(a) AND (b) AND (c)`,
8745 // not `((a) AND (b)) AND (c)`. Explicit right nesting keeps
8746 // its parentheses, because that is a different grouping as
8747 // written. Both halves measured against PG 18.4's deparse,
8748 // which flattens a same-operator left chain at parse time and
8749 // leaves `a AND (b AND c)` alone.
8750 Self::Binary { lhs, op, rhs } if matches!(op, BinOp::And | BinOp::Or) => {
8751 f.write_str("(")?;
8752 write_bool_chain(f, lhs, *op)?;
8753 write!(f, " {op} {rhs}")?;
8754 f.write_str(")")
8755 }
8756 Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
8757 Self::Unary { op, expr } => match op {
8758 UnOp::Not => write!(f, "(NOT {expr})"),
8759 // A space after the sign, as PG's deparse writes it.
8760 UnOp::Neg => write!(f, "(- {expr})"),
8761 UnOp::Plus => write!(f, "(+ {expr})"),
8762 UnOp::BitNot => write!(f, "(~{expr})"),
8763 },
8764 // The OPERAND carries the parentheses, not the cast:
8765 // `(a)::text`, `((a + b))::text`. PG words it this way, and
8766 // it is what keeps `a::text = t` from reading as a cast of
8767 // the comparison.
8768 Self::Cast { expr, target } => write!(f, "({expr})::{target}"),
8769 Self::FieldAccess { base, field } => write!(f, "({base}).{field}"),
8770 Self::AggregateOrdered {
8771 call,
8772 order_by,
8773 distinct,
8774 filter,
8775 } => {
8776 let fmt_order_by = |f: &mut fmt::Formatter<'_>| -> fmt::Result {
8777 for (i, o) in order_by.iter().enumerate() {
8778 if i > 0 {
8779 f.write_str(", ")?;
8780 }
8781 write!(f, "{}", o.expr)?;
8782 if o.desc {
8783 f.write_str(" DESC")?;
8784 }
8785 match o.nulls_first {
8786 Some(true) => f.write_str(" NULLS FIRST")?,
8787 Some(false) => f.write_str(" NULLS LAST")?,
8788 None => {}
8789 }
8790 }
8791 Ok(())
8792 };
8793 // Ordered-set aggregates (`percentile_cont(f) WITHIN
8794 // GROUP (ORDER BY x)`) render the in-parens args as the
8795 // direct argument and the sort spec under WITHIN GROUP —
8796 // not as an in-argument ORDER BY.
8797 let ordered_set = matches!(
8798 call.as_ref(),
8799 Expr::FunctionCall { name, .. }
8800 if matches!(
8801 name.to_ascii_lowercase().as_str(),
8802 "percentile_cont" | "percentile_disc" | "mode"
8803 )
8804 );
8805 if ordered_set {
8806 write!(f, "{call} WITHIN GROUP (ORDER BY ")?;
8807 fmt_order_by(f)?;
8808 f.write_str(")")?;
8809 } else {
8810 // `name([DISTINCT ]args [ORDER BY …])` — peel the
8811 // inner call's parens to splice modifiers.
8812 let inner = alloc::format!("{call}");
8813 let body = inner.strip_suffix(')').unwrap_or(&inner);
8814 let (head, args_part) = body.split_once('(').unwrap_or((body, ""));
8815 write!(f, "{head}(")?;
8816 if *distinct {
8817 f.write_str("DISTINCT ")?;
8818 }
8819 write!(f, "{args_part}")?;
8820 if !order_by.is_empty() {
8821 f.write_str(" ORDER BY ")?;
8822 fmt_order_by(f)?;
8823 }
8824 f.write_str(")")?;
8825 }
8826 if let Some(cond) = filter {
8827 write!(f, " FILTER (WHERE {cond})")?;
8828 }
8829 Ok(())
8830 }
8831 Self::IsNull { expr, negated } => {
8832 if *negated {
8833 write!(f, "({expr} IS NOT NULL)")
8834 } else {
8835 write!(f, "({expr} IS NULL)")
8836 }
8837 }
8838 Self::BoolTest {
8839 expr,
8840 value,
8841 negated,
8842 } => {
8843 let word = match value {
8844 Some(true) => "TRUE",
8845 Some(false) => "FALSE",
8846 None => "UNKNOWN",
8847 };
8848 if *negated {
8849 write!(f, "({expr} IS NOT {word})")
8850 } else {
8851 write!(f, "({expr} IS {word})")
8852 }
8853 }
8854 Self::FunctionCall { name, args } => {
8855 write!(f, "{name}(")?;
8856 for (i, a) in args.iter().enumerate() {
8857 if i > 0 {
8858 f.write_str(", ")?;
8859 }
8860 write!(f, "{a}")?;
8861 }
8862 f.write_str(")")
8863 }
8864 Self::Like {
8865 expr,
8866 pattern,
8867 negated,
8868 case_insensitive,
8869 } => {
8870 let op = match (negated, case_insensitive) {
8871 (false, false) => "LIKE",
8872 (true, false) => "NOT LIKE",
8873 (false, true) => "ILIKE",
8874 (true, true) => "NOT ILIKE",
8875 };
8876 write!(f, "({expr} {op} {pattern})")
8877 }
8878 Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
8879 Self::WindowFunction {
8880 name,
8881 args,
8882 partition_by,
8883 order_by,
8884 frame,
8885 null_treatment,
8886 filter,
8887 } => {
8888 write!(f, "{name}(")?;
8889 for (i, a) in args.iter().enumerate() {
8890 if i > 0 {
8891 f.write_str(", ")?;
8892 }
8893 write!(f, "{a}")?;
8894 }
8895 f.write_str(")")?;
8896 // v7.37 D.40 — `FILTER (WHERE …)` sits between the arg list and
8897 // OVER; it round-trips so a window body's Display re-parses.
8898 if let Some(cond) = filter {
8899 write!(f, " FILTER (WHERE {cond})")?;
8900 }
8901 // v7.30.1 (mailrs round-24 class audit) — IGNORE
8902 // NULLS sits between the arg list and OVER; dropping
8903 // it reverted replayed queries to RESPECT NULLS.
8904 if matches!(null_treatment, NullTreatment::Ignore) {
8905 f.write_str(" IGNORE NULLS")?;
8906 }
8907 f.write_str(" OVER (")?;
8908 if !partition_by.is_empty() {
8909 f.write_str("PARTITION BY ")?;
8910 for (i, p) in partition_by.iter().enumerate() {
8911 if i > 0 {
8912 f.write_str(", ")?;
8913 }
8914 write!(f, "{p}")?;
8915 }
8916 }
8917 if !order_by.is_empty() {
8918 if !partition_by.is_empty() {
8919 f.write_str(" ")?;
8920 }
8921 f.write_str("ORDER BY ")?;
8922 for (i, (e, desc, nulls_first)) in order_by.iter().enumerate() {
8923 if i > 0 {
8924 f.write_str(", ")?;
8925 }
8926 write!(f, "{e}")?;
8927 if *desc {
8928 f.write_str(" DESC")?;
8929 }
8930 match nulls_first {
8931 Some(true) => f.write_str(" NULLS FIRST")?,
8932 Some(false) => f.write_str(" NULLS LAST")?,
8933 None => {}
8934 }
8935 }
8936 }
8937 if let Some(fr) = frame {
8938 if !partition_by.is_empty() || !order_by.is_empty() {
8939 f.write_str(" ")?;
8940 }
8941 let k = match fr.kind {
8942 FrameKind::Rows => "ROWS",
8943 FrameKind::Range => "RANGE",
8944 FrameKind::Groups => "GROUPS",
8945 };
8946 if let Some(end) = &fr.end {
8947 write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
8948 } else {
8949 write!(f, "{k} {}", fr.start)?;
8950 }
8951 }
8952 f.write_str(")")
8953 }
8954 Self::ScalarSubquery(s) => write!(f, "({s})"),
8955 Self::Exists { subquery, negated } => {
8956 if *negated {
8957 write!(f, "NOT EXISTS ({subquery})")
8958 } else {
8959 write!(f, "EXISTS ({subquery})")
8960 }
8961 }
8962 Self::InSubquery {
8963 expr,
8964 subquery,
8965 negated,
8966 } => {
8967 if *negated {
8968 write!(f, "({expr} NOT IN ({subquery}))")
8969 } else {
8970 write!(f, "({expr} IN ({subquery}))")
8971 }
8972 }
8973 Self::RowInSubquery {
8974 row,
8975 subquery,
8976 negated,
8977 } => {
8978 write!(f, "(")?;
8979 for (i, e) in row.iter().enumerate() {
8980 if i > 0 {
8981 write!(f, ", ")?;
8982 }
8983 write!(f, "{e}")?;
8984 }
8985 let kw = if *negated { ") NOT IN (" } else { ") IN (" };
8986 write!(f, "{kw}{subquery})")
8987 }
8988 Self::RowCmpSubquery { row, op, subquery } => {
8989 write!(f, "(")?;
8990 for (i, e) in row.iter().enumerate() {
8991 if i > 0 {
8992 write!(f, ", ")?;
8993 }
8994 write!(f, "{e}")?;
8995 }
8996 write!(f, ") {op} ({subquery})")
8997 }
8998 Self::InList {
8999 expr,
9000 list,
9001 negated,
9002 } => {
9003 let kw = if *negated { " NOT IN (" } else { " IN (" };
9004 write!(f, "({expr}{kw}")?;
9005 for (i, e) in list.iter().enumerate() {
9006 if i > 0 {
9007 f.write_str(", ")?;
9008 }
9009 write!(f, "{e}")?;
9010 }
9011 f.write_str("))")
9012 }
9013 Self::Array(items) => {
9014 f.write_str("ARRAY[")?;
9015 for (i, e) in items.iter().enumerate() {
9016 if i > 0 {
9017 f.write_str(", ")?;
9018 }
9019 write!(f, "{e}")?;
9020 }
9021 f.write_str("]")
9022 }
9023 Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
9024 Self::ArraySlice { target, lo, hi } => {
9025 write!(f, "({target}[")?;
9026 if let Some(l) = lo {
9027 write!(f, "{l}")?;
9028 }
9029 write!(f, ":")?;
9030 if let Some(h) = hi {
9031 write!(f, "{h}")?;
9032 }
9033 write!(f, "])")
9034 }
9035 Self::AnyAll {
9036 expr,
9037 op,
9038 array,
9039 is_any,
9040 } => {
9041 let kw = if *is_any { "ANY" } else { "ALL" };
9042 write!(f, "({expr} {op} {kw}({array}))")
9043 }
9044 Self::Case {
9045 operand,
9046 branches,
9047 else_branch,
9048 } => {
9049 f.write_str("CASE")?;
9050 if let Some(op) = operand {
9051 write!(f, " {op}")?;
9052 }
9053 for (w, t) in branches {
9054 write!(f, " WHEN {w} THEN {t}")?;
9055 }
9056 if let Some(e) = else_branch {
9057 write!(f, " ELSE {e}")?;
9058 }
9059 f.write_str(" END")
9060 }
9061 }
9062 }
9063}
9064
9065/// Render an exact decimal `unscaled / 10^scale`, keeping the scale
9066/// (trailing zeros): `(200, 2)` → `2.00`, `(1, 1)` → `0.1`, `(-15, 1)` → `-1.5`.
9067pub fn render_exact_decimal(unscaled: i128, scale: u16) -> alloc::string::String {
9068 use alloc::string::ToString;
9069 if scale == 0 {
9070 return alloc::format!("{unscaled}");
9071 }
9072 let neg = unscaled < 0;
9073 let digits = alloc::format!("{}", unscaled.unsigned_abs());
9074 let scale = scale as usize;
9075 let (int_part, frac_part) = if digits.len() > scale {
9076 (
9077 digits[..digits.len() - scale].to_string(),
9078 digits[digits.len() - scale..].to_string(),
9079 )
9080 } else {
9081 ("0".to_string(), alloc::format!("{digits:0>scale$}"))
9082 };
9083 alloc::format!("{}{int_part}.{frac_part}", if neg { "-" } else { "" })
9084}
9085
9086/// A single-quoted SQL string, with an embedded quote doubled.
9087fn write_quoted(f: &mut fmt::Formatter<'_>, s: &str) -> fmt::Result {
9088 f.write_str("'")?;
9089 for c in s.chars() {
9090 if c == '\'' {
9091 f.write_str("''")?;
9092 } else {
9093 write!(f, "{c}")?;
9094 }
9095 }
9096 f.write_str("'")
9097}
9098
9099impl fmt::Display for Literal {
9100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9101 match self {
9102 Self::Integer(n) => write!(f, "{n}"),
9103 Self::Float(x) => {
9104 let s = format!("{x}");
9105 // Default Display for an integral f64 (e.g. 1.0) emits "1",
9106 // which would round-trip back to Integer. Force a dot.
9107 if s.contains('.') || s.contains('e') || s.contains('E') {
9108 f.write_str(&s)
9109 } else {
9110 write!(f, "{s}.0")
9111 }
9112 }
9113 Self::Numeric { unscaled, scale } => {
9114 // Render the exact decimal `unscaled / 10^scale`, preserving
9115 // scale (trailing zeros) — round-trips to the same literal.
9116 f.write_str(&render_exact_decimal(*unscaled, *scale))
9117 }
9118 Self::NumericBig(s) => f.write_str(s),
9119 // Printed exactly as the text form was, so a reader cannot
9120 // tell whether the constant was decoded or not.
9121 Self::Timestamp { text, .. } | Self::Date { text, .. } => write_quoted(f, text),
9122 Self::String(s) => write_quoted(f, s),
9123 Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
9124 Self::Null => f.write_str("NULL"),
9125 // PG external array form. Display round-trip re-enters
9126 // through the column-typed text coerce, same as pgwire.
9127 Self::TextArray(items) => {
9128 f.write_str("'{")?;
9129 for (i, it) in items.iter().enumerate() {
9130 if i > 0 {
9131 f.write_str(",")?;
9132 }
9133 match it {
9134 None => f.write_str("NULL")?,
9135 Some(s) => {
9136 f.write_str("\"")?;
9137 for c in s.chars() {
9138 match c {
9139 // array-element escapes
9140 '"' | '\\' => write!(f, "\\{c}")?,
9141 // the OUTER wrapper is a SQL string
9142 // literal — embedded quotes must
9143 // double, or the rendered form
9144 // (WAL replay parses it back) is
9145 // invalid SQL
9146 '\'' => f.write_str("''")?,
9147 _ => write!(f, "{c}")?,
9148 }
9149 }
9150 f.write_str("\"")?;
9151 }
9152 }
9153 }
9154 f.write_str("}'")
9155 }
9156 Self::IntArray(items) => {
9157 f.write_str("'{")?;
9158 for (i, it) in items.iter().enumerate() {
9159 if i > 0 {
9160 f.write_str(",")?;
9161 }
9162 match it {
9163 None => f.write_str("NULL")?,
9164 Some(n) => write!(f, "{n}")?,
9165 }
9166 }
9167 f.write_str("}'")
9168 }
9169 Self::BigIntArray(items) => {
9170 f.write_str("'{")?;
9171 for (i, it) in items.iter().enumerate() {
9172 if i > 0 {
9173 f.write_str(",")?;
9174 }
9175 match it {
9176 None => f.write_str("NULL")?,
9177 Some(n) => write!(f, "{n}")?,
9178 }
9179 }
9180 f.write_str("}'")
9181 }
9182 Self::Vector(v) => {
9183 f.write_str("[")?;
9184 for (i, x) in v.iter().enumerate() {
9185 if i > 0 {
9186 f.write_str(", ")?;
9187 }
9188 let s = format!("{x}");
9189 // Mirror Float Display: force a dot so re-parse stays
9190 // numerically literal.
9191 if s.contains('.') || s.contains('e') || s.contains('E') {
9192 f.write_str(&s)?;
9193 } else {
9194 write!(f, "{s}.0")?;
9195 }
9196 }
9197 f.write_str("]")
9198 }
9199 Self::Interval { text, .. } => {
9200 f.write_str("INTERVAL '")?;
9201 for c in text.chars() {
9202 if c == '\'' {
9203 f.write_str("''")?;
9204 } else {
9205 write!(f, "{c}")?;
9206 }
9207 }
9208 f.write_str("'")
9209 }
9210 }
9211 }
9212}
9213
9214impl fmt::Display for BinOp {
9215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9216 f.write_str(match self {
9217 Self::Or => "OR",
9218 Self::And => "AND",
9219 Self::Eq => "=",
9220 Self::NotEq => "<>",
9221 Self::IsDistinctFrom => "IS DISTINCT FROM",
9222 Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
9223 Self::IntDiv => "DIV",
9224 Self::Lt => "<",
9225 Self::LtEq => "<=",
9226 Self::Gt => ">",
9227 Self::GtEq => ">=",
9228 Self::Add => "+",
9229 Self::Sub => "-",
9230 Self::Mul => "*",
9231 Self::Div => "/",
9232 Self::Mod => "%",
9233 Self::L2Distance => "<->",
9234 Self::GeomParallel => "?||",
9235 Self::OverLeft => "&<",
9236 Self::OverRight => "&>",
9237 Self::GeomPerp => "?-|",
9238 Self::GeomSameAs => "~=",
9239 Self::ClosestPoint => "##",
9240 Self::GeomHoriz => "?-",
9241 Self::InnerProduct => "<#>",
9242 Self::CosineDistance => "<=>",
9243 Self::Concat => "||",
9244 Self::BitOr => "|",
9245 Self::BitAnd => "&",
9246 Self::BitXor => "#",
9247 Self::LogicalXor => "xor",
9248 Self::JsonGet => "->",
9249 Self::JsonGetText => "->>",
9250 Self::JsonGetPath => "#>",
9251 Self::JsonGetPathText => "#>>",
9252 Self::JsonContains => "@>",
9253 Self::JsonPathExists => "@?",
9254 Self::JsonContainedBy => "<@",
9255 Self::JsonKeyExists => "?",
9256 Self::JsonKeysAny => "?|",
9257 Self::JsonKeysAll => "?&",
9258 Self::JsonDeletePath => "#-",
9259 Self::TsMatch => "@@",
9260 Self::InetContainedBy => "<<",
9261 Self::InetContainedByEq => "<<=",
9262 Self::InetContains => ">>",
9263 Self::InetContainsEq => ">>=",
9264 Self::InetOverlap => "&&",
9265 Self::Intersects => "?#",
9266 Self::IsBelow => "<^",
9267 Self::IsAbove => ">^",
9268 Self::PatternLt => "~<~",
9269 Self::PatternLtEq => "~<=~",
9270 Self::PatternGt => "~>~",
9271 Self::PatternGtEq => "~>=~",
9272 })
9273 }
9274}
9275
9276/// Quote `s` as a PG double-quoted identifier when required (keyword,
9277/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
9278/// Otherwise return it as-is. Returns an owned `String` to keep the call site
9279/// uniform.
9280pub(crate) fn quote_ident(s: &str) -> String {
9281 let needs_quote = match s.chars().next() {
9282 None => true,
9283 Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
9284 _ => {
9285 s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
9286 || s.chars().any(|c| c.is_ascii_uppercase())
9287 || is_keyword(s)
9288 }
9289 };
9290 if !needs_quote {
9291 return s.to_string();
9292 }
9293 let mut out = String::with_capacity(s.len() + 2);
9294 out.push('"');
9295 for c in s.chars() {
9296 if c == '"' {
9297 out.push_str("\"\"");
9298 } else {
9299 out.push(c);
9300 }
9301 }
9302 out.push('"');
9303 out
9304}
9305
9306fn is_keyword(s: &str) -> bool {
9307 matches!(
9308 &*s.to_ascii_lowercase(),
9309 "select"
9310 | "from"
9311 | "where"
9312 | "as"
9313 | "null"
9314 | "true"
9315 | "false"
9316 | "and"
9317 | "or"
9318 | "not"
9319 | "create"
9320 | "table"
9321 | "insert"
9322 | "into"
9323 | "values"
9324 | "index"
9325 | "on"
9326 | "begin"
9327 | "commit"
9328 | "rollback"
9329 | "is"
9330 | "between"
9331 | "in"
9332 | "like"
9333 | "group"
9334 | "distinct"
9335 | "union"
9336 | "all"
9337 | "join"
9338 | "inner"
9339 | "left"
9340 | "cross"
9341 | "outer"
9342 | "default"
9343 | "savepoint"
9344 | "release"
9345 | "to"
9346 | "having"
9347 | "show"
9348 | "extract"
9349 | "offset"
9350 | "asc"
9351 | "desc"
9352 | "interval"
9353 )
9354}
9355
9356#[cfg(test)]
9357mod tests {
9358 use super::*;
9359 use alloc::vec;
9360
9361 #[test]
9362 fn integer_literal_renders_without_dot() {
9363 assert_eq!(Literal::Integer(42).to_string(), "42");
9364 }
9365
9366 #[test]
9367 fn integral_float_keeps_dot() {
9368 assert_eq!(Literal::Float(1.0).to_string(), "1.0");
9369 assert_eq!(Literal::Float(1.5).to_string(), "1.5");
9370 assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
9371 }
9372
9373 #[test]
9374 fn string_literal_doubles_quote() {
9375 assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
9376 }
9377
9378 #[test]
9379 fn bool_and_null_render_uppercase() {
9380 assert_eq!(Literal::Bool(true).to_string(), "TRUE");
9381 assert_eq!(Literal::Bool(false).to_string(), "FALSE");
9382 assert_eq!(Literal::Null.to_string(), "NULL");
9383 }
9384
9385 #[test]
9386 fn binary_op_always_parenthesised() {
9387 let e = Expr::Binary {
9388 lhs: Box::new(Expr::Literal(Literal::Integer(1))),
9389 op: BinOp::Add,
9390 rhs: Box::new(Expr::Literal(Literal::Integer(2))),
9391 };
9392 assert_eq!(e.to_string(), "(1 + 2)");
9393 }
9394
9395 #[test]
9396 fn select_star_from_table() {
9397 let s = SelectStatement {
9398 locking: None,
9399 items: vec![SelectItem::Wildcard],
9400 from: Some(FromClause {
9401 primary: TableRef {
9402 name: "users".into(),
9403 alias: None,
9404 only: false,
9405 as_of_segment: None,
9406 unnest_expr: None,
9407 unnest_column_aliases: Vec::new(),
9408 with_ordinality: false,
9409 generate_series_args: None,
9410 lateral_subquery: None,
9411 jsonb_each_text_arg: None,
9412 table_fn_call: None,
9413 rows_from: None,
9414 json_table: None,
9415 scalar_fn_item: false,
9416 },
9417 joins: vec![],
9418 }),
9419 where_: None,
9420 group_by: None,
9421 group_by_all: false,
9422 having: None,
9423 unions: vec![],
9424 order_by: Vec::new(),
9425 limit: None,
9426 offset: None,
9427 limit_with_ties: false,
9428 window_check_exprs: Vec::new(),
9429 distinct: false,
9430 distinct_on: Vec::new(),
9431 ctes: vec![],
9432 };
9433 assert_eq!(s.to_string(), "SELECT * FROM users");
9434 }
9435
9436 #[test]
9437 fn quote_ident_for_uppercase_and_keyword() {
9438 assert_eq!(quote_ident("foo"), "foo");
9439 assert_eq!(quote_ident("Foo"), "\"Foo\"");
9440 assert_eq!(quote_ident("select"), "\"select\"");
9441 assert_eq!(quote_ident(""), "\"\"");
9442 assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
9443 }
9444}