spg_sql/ast.rs
1//! AST for the PG-dialect subset SPG accepts in v0.2.
2//!
3//! `Display` is implemented so that for any AST `a` produced by [`crate::parser`],
4//! re-parsing `format!("{a}")` yields a structurally equal AST. Binary and
5//! unary operators always emit parentheses to remove any precedence
6//! ambiguity — round-trip safety wins over prettiness.
7
8use alloc::boxed::Box;
9use alloc::format;
10use alloc::string::{String, ToString};
11use alloc::vec::Vec;
12use core::fmt;
13
14#[derive(Debug, Clone, PartialEq)]
15#[allow(clippy::large_enum_variant)] // Statement::Select dominates; Boxing would touch every match site
16pub enum Statement {
17 /// v7.14.0 — `DROP TABLE [IF EXISTS] name [, name…]
18 /// [CASCADE | RESTRICT]`. Engine removes the matching tables
19 /// (each one) from the catalog; IF EXISTS makes the drop
20 /// idempotent. CASCADE / RESTRICT trailers parsed silently
21 /// (SPG always cascades index drops on table drop).
22 DropTable {
23 names: Vec<String>,
24 if_exists: bool,
25 },
26 /// v7.14.0 — `DROP INDEX [IF EXISTS] name`. Removes the
27 /// matching index across whichever table holds it.
28 DropIndex {
29 name: String,
30 if_exists: bool,
31 },
32 /// v7.14.0 — empty / comment-only statement. The lexer strips
33 /// `--` line comments and `/* … */` block comments (including
34 /// the MySQL conditional `/*!NNNNN … */` form) before the
35 /// parser ever sees them; a SQL chunk that contains nothing
36 /// else lands here. Engine returns CommandOk no-op so
37 /// pg_dump / mysqldump preambles (`SET NAMES utf8mb4`
38 /// wrapped in conditional comments, etc.) load cleanly.
39 Empty,
40 Select(SelectStatement),
41 CreateTable(CreateTableStatement),
42 /// v7.9.15 — `CREATE EXTENSION [IF NOT EXISTS] <name>
43 /// [WITH SCHEMA <s>] [VERSION <v>] [CASCADE]` accepted as a
44 /// no-op so PG dumps that include extension declarations
45 /// (notably `pgvector`) load against SPG without splitting
46 /// init scripts. mailrs migration follow-up F3.
47 CreateExtension(String),
48 /// v7.9.27 — PG `DO $$ … $$ [LANGUAGE plpgsql];` block. SPG
49 /// has no PL/pgSQL; engine returns CommandOk no-op so
50 /// `pg_dump` output with idempotent DO migrations loads
51 /// against SPG without splitting scripts. The lexer
52 /// consumes the dollar-quoted body into a discarded
53 /// Token::String. mailrs migration follow-up H1.
54 DoBlock,
55 CreateIndex(CreateIndexStatement),
56 Insert(InsertStatement),
57 /// v4.4 — `UPDATE <table> SET col=expr [, ...] [WHERE cond]`.
58 Update(UpdateStatement),
59 /// v4.4 — `DELETE FROM <table> [WHERE cond]`.
60 Delete(DeleteStatement),
61 Begin,
62 Commit,
63 Rollback,
64 /// `SAVEPOINT <name>` — push a named savepoint onto the active TX's
65 /// stack so a later `ROLLBACK TO <name>` can undo just the work
66 /// since this point.
67 Savepoint(String),
68 /// `ROLLBACK TO [SAVEPOINT] <name>` — restore catalog state to the
69 /// named savepoint and discard later savepoints. Does not end the
70 /// transaction.
71 RollbackToSavepoint(String),
72 /// `RELEASE [SAVEPOINT] <name>` — discard a savepoint without
73 /// rolling back. Keeps the work done since then.
74 ReleaseSavepoint(String),
75 /// `SHOW TABLES` — return the list of tables in the catalog.
76 ShowTables,
77 /// `SHOW COLUMNS FROM <table>` — return one row per column with
78 /// its declared name / type / nullability.
79 ShowColumns(String),
80 /// `CREATE USER 'name' WITH PASSWORD 'pw' ROLE 'admin'` (v4.1).
81 /// Role is optional; defaults to `readonly` when omitted.
82 CreateUser(CreateUserStatement),
83 /// `DROP USER 'name'` (v4.1).
84 DropUser(String),
85 /// `SHOW USERS` (v4.1) — admin-only listing of (name, role).
86 ShowUsers,
87 /// v4.26 — `EXPLAIN [ANALYZE] <select>`. The engine returns a
88 /// single-column text table describing the rewritten plan tree
89 /// for `inner`. `analyze` triggers an actual exec to attach
90 /// observed row counts and elapsed micros to each node.
91 Explain(ExplainStatement),
92 /// v6.0.4 — `ALTER INDEX <name> REBUILD [WITH (encoding = ...)]`.
93 /// Synchronous rebuild of an NSW index. With the optional
94 /// encoding clause, every stored cell at the indexed column is
95 /// also re-encoded through `coerce_value` before the new graph
96 /// builds.
97 AlterIndex(AlterIndexStatement),
98 /// v6.7.2 — `ALTER TABLE <name> SET <setting> = <value>`.
99 /// The only setting in v6.7.2 is `hot_tier_bytes`, which
100 /// overrides the global `SPG_HOT_TIER_BYTES` freezer trigger
101 /// for the named table.
102 AlterTable(AlterTableStatement),
103 /// v6.1.2 — `CREATE PUBLICATION <name> [FOR ALL TABLES]`.
104 /// The catalog row lives in `spg_publications`. Publisher-side
105 /// WAL filtering arrives in v6.1.5.
106 CreatePublication(CreatePublicationStatement),
107 /// v6.1.2 — `DROP PUBLICATION <name>`. PG-compatible silent
108 /// no-op when the publication does not exist.
109 DropPublication(String),
110 /// v6.1.3 — `SHOW PUBLICATIONS`. Returns one row per
111 /// publication ordered by name with `(name, scope_summary,
112 /// table_count)` columns. The scope summary is the human-
113 /// readable form `ALL TABLES` / `FOR TABLE …` / `FOR ALL
114 /// TABLES EXCEPT …`; `table_count` is `NULL` for the
115 /// `AllTables` scope and the table-list length otherwise.
116 ShowPublications,
117 /// v6.1.4 — `CREATE SUBSCRIPTION <name> CONNECTION '<conn>'
118 /// PUBLICATION <pub_name> [, <pub_name> …]`. Catalog lands
119 /// in `spg_subscriptions`; when the subscription is
120 /// `enabled = true` (default) the server spawns a
121 /// background worker that connects to `conn` and drains the
122 /// requested publication(s) into the local engine.
123 CreateSubscription(CreateSubscriptionStatement),
124 /// v6.1.4 — `DROP SUBSCRIPTION <name>`. Like DROP
125 /// PUBLICATION, silent no-op when absent. Stops the
126 /// associated worker thread before removing the row.
127 DropSubscription(String),
128 /// v6.1.4 — `SHOW SUBSCRIPTIONS`. Returns one row per
129 /// subscription ordered by name with `(name, conn_str,
130 /// publications, enabled, last_received_pos)`.
131 ShowSubscriptions,
132 /// v6.1.7 — `WAIT FOR WAL POSITION <pos> [WITH TIMEOUT <ms>]`.
133 /// Blocks until the local server's apply position reaches
134 /// `<pos>` or `<ms>` elapses. Server-layer command: the
135 /// engine refuses it (`EngineError::Unsupported`) since
136 /// `lag_state` lives in `spg-server`'s `ServerState`.
137 WaitForWalPosition {
138 pos: u64,
139 /// `None` → wait forever; `Some(ms)` → return after `ms`
140 /// milliseconds even if the target isn't reached.
141 timeout_ms: Option<u64>,
142 },
143 /// v6.2.0 — `ANALYZE [<table>]`. Bare form walks every user
144 /// table; `ANALYZE <name>` re-stats just one. Populates
145 /// `spg_statistic` with per-column null_frac + n_distinct +
146 /// 100-bucket equi-depth histogram.
147 Analyze(Option<String>),
148 /// v6.7.3 — `COMPACT COLD SEGMENTS`. Walks every user table's
149 /// BTree-cold indices and merges small cold-tier segments
150 /// (size below `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, default
151 /// 4 MiB) into a single larger segment per (table, index).
152 /// `WHERE` predicate filtering on which tables to compact is
153 /// carved out of v6.7.3 (per V6_7_DESIGN.md STABILITY entry);
154 /// v6.7.3 only supports the bare form.
155 CompactColdSegments,
156 /// v7.12.1 — `SET <name> [TO|=] <value>`. Records a session
157 /// parameter on the engine; v7.12.1 honours
158 /// `default_text_search_config` (consumed by `to_tsvector` /
159 /// `plainto_tsquery` family when called without an explicit
160 /// config arg). All other names are accepted as a no-op so PG
161 /// dumps with `SET client_encoding`, `SET search_path` etc.
162 /// load cleanly.
163 SetParameter {
164 name: String,
165 value: SetValue,
166 },
167 /// v7.14.0 — `SET a = 1, b = 2, …` MySQL-flavoured
168 /// multi-assignment (mysqldump preamble uses
169 /// `SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS,
170 /// FOREIGN_KEY_CHECKS=0`). Engine applies each pair in
171 /// source order. Pairs whose LHS is a MySQL session/user
172 /// variable (`@VAR` / `@@VAR`) are recorded with the raw
173 /// name so the engine can ignore them; pairs whose LHS is
174 /// a recognised engine parameter (e.g. `FOREIGN_KEY_CHECKS`)
175 /// go through the regular `set_session_param` path.
176 SetParameterList(Vec<(String, SetValue)>),
177 /// v7.12.1 — `RESET <name>` / `RESET ALL`. Restores parameter
178 /// to its default. No-op for parameters SPG does not track.
179 ResetParameter(Option<String>),
180 /// v7.12.4 — `CREATE [OR REPLACE] FUNCTION name(args) RETURNS
181 /// <type> [LANGUAGE <lang>] AS $$ body $$ [LANGUAGE <lang>]`.
182 /// v7.12.4 ships `plpgsql` for `RETURNS TRIGGER` bodies (the
183 /// CREATE TRIGGER + AFTER/BEFORE row-level pipeline). Other
184 /// languages parse but error at exec time with a clear
185 /// unsupported message.
186 CreateFunction(CreateFunctionStatement),
187 /// v7.12.4 — `CREATE [OR REPLACE] TRIGGER name {BEFORE|AFTER}
188 /// {INSERT|UPDATE|DELETE} [OR ...] ON tbl FOR EACH ROW
189 /// EXECUTE {FUNCTION|PROCEDURE} fn_name()`. STATEMENT-level
190 /// triggers and column-list / WHEN clauses are out of scope
191 /// for v7.12.4.
192 CreateTrigger(CreateTriggerStatement),
193 /// v7.12.4 — `DROP TRIGGER [IF EXISTS] name ON tbl`. Silent
194 /// no-op when missing if `IF EXISTS` is set.
195 DropTrigger {
196 name: String,
197 table: String,
198 if_exists: bool,
199 },
200 /// v7.12.4 — `DROP FUNCTION [IF EXISTS] name`. Same shape as
201 /// DROP TRIGGER but global (no table scope).
202 DropFunction {
203 name: String,
204 if_exists: bool,
205 },
206}
207
208/// v7.12.1 — payload of a SET right-hand side. PG syntax accepts
209/// a string literal, an identifier (often a config name), an
210/// integer/float, or the bare `DEFAULT` keyword.
211#[derive(Debug, Clone, PartialEq)]
212pub enum SetValue {
213 String(String),
214 Ident(String),
215 Number(String),
216 Default,
217}
218
219/// v6.1.4 — `CREATE SUBSCRIPTION` AST node. v6.1.4 ships a
220/// single fixed-shape DDL; the WITH-clause options PG supports
221/// (`enabled`, `slot_name`, `streaming`, `binary`) are out of
222/// scope for v6.1.4 — `enabled` defaults to true and there are
223/// no other knobs to set in v6.1.x.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct CreateSubscriptionStatement {
226 pub name: String,
227 /// Connection string in PG keyword=value form (e.g.
228 /// `host=127.0.0.1 port=20002`). v6.1.4 only consumes the
229 /// `host` and `port` fields; the rest is reserved for
230 /// future v6.1.x options.
231 pub conn_str: String,
232 /// One or more publications on the remote side. Order is
233 /// preserved verbatim from the DDL; the worker requests them
234 /// in this order. v6.1.4 records the list; v6.1.5
235 /// publisher-side filtering enforces it.
236 pub publications: Vec<String>,
237}
238
239/// v6.1.2 — `CREATE PUBLICATION` AST node. The `scope` field uses
240/// the [`PublicationScope`] shape. v6.1.2 only accepted
241/// `AllTables`; v6.1.3 unlocks the `ForTables` / `AllTablesExcept`
242/// variants by flipping the parser gate (no AST migration).
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct CreatePublicationStatement {
245 pub name: String,
246 pub scope: PublicationScope,
247}
248
249/// v6.1.2 — Which tables a publication covers. v6.1.3 (this commit)
250/// flips the parser gate for the `ForTables` / `AllTablesExcept`
251/// variants — the on-disk shape, snapshot serialisation, and the
252/// AST round-trip Display path were already in place in v6.1.2
253/// so this is a parser-only widening.
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum PublicationScope {
256 AllTables,
257 ForTables(Vec<String>),
258 AllTablesExcept(Vec<String>),
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct AlterIndexStatement {
263 pub name: String,
264 pub target: AlterIndexTarget,
265}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum AlterIndexTarget {
269 /// `REBUILD [WITH (encoding = <enc>)]`. `encoding = None`
270 /// rebuilds the existing graph in place without touching the
271 /// column encoding; `Some(enc)` re-encodes every cell first.
272 Rebuild { encoding: Option<VecEncoding> },
273}
274
275/// v6.7.2 — `ALTER TABLE t SET <setting> = <value>`. v6.7.2 ships
276/// the single `hot_tier_bytes` setting; later v6.7.x sub-versions
277/// can add more SET subjects without changing the dispatch shape.
278#[derive(Debug, Clone, PartialEq)]
279pub struct AlterTableStatement {
280 pub name: String,
281 /// v7.13.2 — mailrs round-6 S1. One or more subactions
282 /// separated by commas in the source SQL. PG-semantic apply
283 /// is sequential; engine bails on first error (no
284 /// transactional rollback of completed subactions in v7.13).
285 /// Single-subaction shape stays a 1-element vec.
286 pub targets: Vec<AlterTableTarget>,
287}
288
289#[derive(Debug, Clone, PartialEq)]
290pub enum AlterTableTarget {
291 /// Per-table hot-tier byte budget override. The freezer
292 /// reads this before falling back to `SPG_HOT_TIER_BYTES`.
293 SetHotTierBytes(u64),
294 /// v7.6.8 — `ALTER TABLE t ADD CONSTRAINT name FOREIGN KEY
295 /// (cols) REFERENCES parent[(pcols)] [ON DELETE/UPDATE …]`.
296 /// Engine validates existing rows against the new constraint
297 /// before installing it.
298 AddForeignKey(ForeignKeyConstraint),
299 /// v7.6.8 — `ALTER TABLE t DROP CONSTRAINT [IF EXISTS] name`.
300 /// `if_exists` (v7.13.2 mailrs round-6 S7) makes the drop a
301 /// no-op when no FK with that name exists; otherwise raises.
302 DropForeignKey {
303 name: String,
304 if_exists: bool,
305 },
306 /// v7.13.0 — `ALTER TABLE t ADD [COLUMN] [IF NOT EXISTS] <col>
307 /// <type> [DEFAULT <expr>] [NOT NULL]`. mailrs round-5 G1
308 /// (20 migrate-*.sql hits). Engine appends the column to the
309 /// schema and back-fills every existing row with the DEFAULT
310 /// (or NULL when no DEFAULT and the column is nullable).
311 AddColumn {
312 column: ColumnDef,
313 if_not_exists: bool,
314 },
315 /// v7.13.0 — `ALTER TABLE t ALTER COLUMN <col> TYPE <ty>
316 /// [USING <expr>]` (mailrs round-5 G8). Engine rewrites every
317 /// existing row's column value by evaluating the optional
318 /// USING expression (default `col::<ty>`) and re-coercing
319 /// against the new column type.
320 AlterColumnType {
321 column: String,
322 new_type: ColumnTypeName,
323 using: Option<Expr>,
324 },
325 /// v7.13.3 — `ALTER TABLE t DROP [COLUMN] [IF EXISTS] <col>
326 /// [CASCADE | RESTRICT]` (mailrs round-7 S8). The column +
327 /// every row's value at that position is removed; any index
328 /// on the column is dropped. `if_exists` makes the drop a
329 /// no-op when the column is missing. `cascade` removes
330 /// dependents (FKs referencing the column, partial indexes
331 /// whose predicate names the column); without it, the engine
332 /// rejects when dependents exist.
333 DropColumn {
334 column: String,
335 if_exists: bool,
336 cascade: bool,
337 },
338 /// v7.14.0 — `ALTER TABLE t ADD CONSTRAINT name PRIMARY KEY
339 /// (cols)` / `ADD CONSTRAINT name UNIQUE (cols)` / `ADD
340 /// CONSTRAINT name CHECK (expr)` — table-level constraints
341 /// installed post-CREATE-TABLE. pg_dump emits PKs as a
342 /// separate ALTER TABLE statement, so this surface lets the
343 /// dump load straight through.
344 AddTableConstraint(TableConstraint),
345}
346
347#[derive(Debug, Clone, PartialEq)]
348pub struct ExplainStatement {
349 pub analyze: bool,
350 pub inner: Box<SelectStatement>,
351 /// v6.8.3 — `EXPLAIN (SUGGEST) <SELECT>` enables the index
352 /// advisor pass: after the regular plan tree, the engine
353 /// emits one suggestion line per column referenced in the
354 /// query's WHERE / JOIN that has no covering index on the
355 /// owning table.
356 pub suggest: bool,
357}
358
359#[derive(Debug, Clone, PartialEq, Eq)]
360pub struct CreateUserStatement {
361 pub name: String,
362 pub password: String,
363 /// One of `admin` / `readwrite` / `readonly`. Stored verbatim from
364 /// the parser; the engine validates against `Role::parse` so a
365 /// typo lands as a runtime error with a clear message rather than
366 /// a parse failure.
367 pub role: String,
368}
369
370/// v7.12.4 — `CREATE [OR REPLACE] FUNCTION`. v7.12.4 ships
371/// `RETURNS TRIGGER LANGUAGE plpgsql` as the primary use case
372/// (the row-level trigger body the CREATE TRIGGER below references).
373/// Non-trigger user-defined functions parse but error at execution
374/// time with a clear unsupported message; that surface lands in
375/// v7.12.5+.
376#[derive(Debug, Clone, PartialEq)]
377pub struct CreateFunctionStatement {
378 pub name: String,
379 /// `OR REPLACE` was present; an existing function with the
380 /// same name is overwritten instead of erroring.
381 pub or_replace: bool,
382 /// `(arg1 type1, ...)` — v7.12.4 only accepts the empty arg
383 /// list `()` (sufficient for trigger functions). Other shapes
384 /// parse and store the args but the executor refuses to call
385 /// them.
386 pub args: Vec<FunctionArg>,
387 /// `RETURNS <type>` — `trigger` is the supported shape for
388 /// v7.12.4; arbitrary return types parse to
389 /// [`FunctionReturn::Other`].
390 pub returns: FunctionReturn,
391 /// `LANGUAGE <lang>` clause. PG accepts the clause on either
392 /// side of `AS $$...$$`; the parser canonicalises to one slot.
393 /// `plpgsql` and `sql` are the two interesting values.
394 pub language: String,
395 /// `AS $$ ... $$` body. v7.12.4 parses PL/pgSQL bodies into
396 /// a structured AST; non-trigger / non-plpgsql bodies stay as
397 /// the raw source text so the v7.12.5+ executor can pick them
398 /// up without a parser rev.
399 pub body: FunctionBody,
400}
401
402/// v7.12.4 — one positional argument to a `CREATE FUNCTION`.
403#[derive(Debug, Clone, PartialEq)]
404pub struct FunctionArg {
405 /// `IN` / `OUT` / `INOUT` mode. v7.12.4 only accepts `IN`
406 /// (the default); `OUT` / `INOUT` parse but the executor
407 /// refuses them.
408 pub mode: FunctionArgMode,
409 /// Optional arg name. Trigger functions traditionally don't
410 /// name their args (they read NEW/OLD instead), so `None` is
411 /// the common case.
412 pub name: Option<String>,
413 /// Declared type, normalised to the SPG `DataType` mapping
414 /// where one exists. Unknown / extension types parse as a
415 /// raw string under [`FunctionArgType::Raw`].
416 pub ty: FunctionArgType,
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420pub enum FunctionArgMode {
421 In,
422 Out,
423 InOut,
424}
425
426#[derive(Debug, Clone, PartialEq)]
427pub enum FunctionArgType {
428 Typed(ColumnTypeName),
429 /// Unknown / extension types — kept as the parser-side raw
430 /// identifier so error messages can name them precisely.
431 Raw(String),
432}
433
434#[derive(Debug, Clone, PartialEq)]
435pub enum FunctionReturn {
436 /// `RETURNS TRIGGER` — the row-level trigger function shape.
437 /// v7.12.4 ships exactly this for execution.
438 Trigger,
439 /// `RETURNS VOID`. Parses; executor rejects in v7.12.4 unless
440 /// the function is unused (since v7.12.4 doesn't ship scalar
441 /// function invocation).
442 Void,
443 /// `RETURNS <type>` for any concrete data type. Reserved for
444 /// v7.12.5+'s scalar UDF surface.
445 Type(ColumnTypeName),
446 /// `RETURNS <ident>` for types SPG doesn't know — extension
447 /// types, RETURNS SETOF rows, RETURNS TABLE(...), etc.
448 Other(String),
449}
450
451#[derive(Debug, Clone, PartialEq)]
452pub enum FunctionBody {
453 /// v7.12.4 — parsed PL/pgSQL `BEGIN … END` block. The
454 /// trigger-function executor walks this directly without
455 /// re-parsing.
456 PlPgSql(PlPgSqlBlock),
457 /// Raw source text — parser couldn't (or didn't try to)
458 /// structure-parse the body. Used for `LANGUAGE sql`
459 /// functions and any PL/pgSQL body that contains v7.12.5+
460 /// features the v7.12.4 parser doesn't yet recognise. The
461 /// executor returns an unsupported error when invoked.
462 Raw(String),
463}
464
465/// v7.12.4 — PL/pgSQL `BEGIN ... END;` block. v7.12.6 widens
466/// from assignment + return to a real-PL/pgSQL surface:
467/// `DECLARE`-block local variables, `IF/ELSIF/ELSE/END IF`
468/// control flow, `RAISE` diagnostics, and embedded SQL
469/// statements that execute through the regular engine path.
470/// The remaining v7.12.x carve-out is loops (`LOOP/WHILE/FOR`),
471/// which mailrs's trigger doesn't need but other PG customers
472/// may; deferred to a future minor release.
473#[derive(Debug, Clone, PartialEq)]
474pub struct PlPgSqlBlock {
475 /// v7.12.6 — `DECLARE var TYPE [:= init_expr];` declarations
476 /// preceding `BEGIN`. Empty when the body opens directly with
477 /// `BEGIN`. Declarations execute in order; each may reference
478 /// earlier-declared locals in its init expression.
479 pub declarations: Vec<PlPgSqlDeclare>,
480 pub statements: Vec<PlPgSqlStmt>,
481}
482
483/// v7.12.6 — single `DECLARE` entry: variable name + declared
484/// type + optional initialiser. Variables default to SQL NULL
485/// when no init is given (matches PG).
486#[derive(Debug, Clone, PartialEq)]
487pub struct PlPgSqlDeclare {
488 pub name: String,
489 /// Declared SQL type (mapped to [`ColumnTypeName`] where SPG
490 /// knows it; raw text otherwise).
491 pub ty: FunctionArgType,
492 pub default: Option<Expr>,
493}
494
495#[derive(Debug, Clone, PartialEq)]
496pub enum PlPgSqlStmt {
497 /// `NEW.col := expr;` or `OLD.col := expr;`. OLD is parsed
498 /// for clarity in error reporting (PG also forbids it) — the
499 /// executor errors with a clear "OLD is read-only" message.
500 Assign { target: AssignTarget, value: Expr },
501 /// `RETURN <target>;` — trigger functions canonically return
502 /// `NEW` / `OLD` / `NULL`; v7.12.4 also accepts a bare
503 /// expression for forward compatibility with scalar UDFs.
504 Return(ReturnTarget),
505 /// v7.12.6 — `IF cond THEN body [ELSIF cond THEN body]*
506 /// [ELSE body] END IF;`. Branches are tried in order; first
507 /// truthy condition wins; the optional ELSE runs when no
508 /// condition matched.
509 If {
510 branches: Vec<(Expr, Vec<PlPgSqlStmt>)>,
511 else_branch: Vec<PlPgSqlStmt>,
512 },
513 /// v7.12.6 — `RAISE <level> '<fmt>' [, args]*;`. Level is one
514 /// of `NOTICE` / `WARNING` / `INFO` / `LOG` / `DEBUG`
515 /// (logging — observable side effect only) or `EXCEPTION`
516 /// (aborts the trigger and propagates as an error). v7.12.6
517 /// supports the basic format-string substitution PG uses
518 /// (`%` placeholders consumed positionally).
519 Raise {
520 level: RaiseLevel,
521 message: String,
522 args: Vec<Expr>,
523 },
524 /// v7.12.6 — embedded SQL statement inside the trigger body
525 /// (`INSERT INTO …`, `UPDATE …`, `DELETE FROM …`, `SELECT …`).
526 /// NEW.col / OLD.col references inside the embedded
527 /// statement's expression tree are substituted with the
528 /// current trigger context before the engine re-executes the
529 /// statement. Recursion depth into nested triggers is
530 /// bounded by the engine's existing trigger-fire guard.
531 EmbeddedSql(Box<Statement>),
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535pub enum RaiseLevel {
536 /// `RAISE NOTICE` — diagnostic message, observable in the
537 /// server log. Does not affect the trigger's outcome.
538 Notice,
539 /// `RAISE WARNING` — like NOTICE, slightly louder severity.
540 Warning,
541 /// `RAISE INFO` — like NOTICE, slightly quieter.
542 Info,
543 /// `RAISE LOG` — like NOTICE, lower priority.
544 Log,
545 /// `RAISE DEBUG` — like NOTICE, lowest priority.
546 Debug,
547 /// `RAISE EXCEPTION` — aborts the trigger function with the
548 /// given message, propagating up to the caller as a query-
549 /// level error.
550 Exception,
551}
552
553#[derive(Debug, Clone, PartialEq)]
554pub enum AssignTarget {
555 NewColumn(String),
556 OldColumn(String),
557 /// Reserved for v7.12.5 DECLARE'd local variables.
558 Local(String),
559}
560
561#[derive(Debug, Clone, PartialEq)]
562pub enum ReturnTarget {
563 /// `RETURN NEW;` — for BEFORE triggers, this is the row that
564 /// actually gets written (possibly with NEW.col mutations
565 /// applied). For AFTER triggers, the return value is ignored.
566 New,
567 /// `RETURN OLD;` — pass-through. For BEFORE DELETE this lets
568 /// the delete proceed; for BEFORE UPDATE / INSERT it's
569 /// equivalent to dropping the write.
570 Old,
571 /// `RETURN NULL;` — for BEFORE triggers, skips the write
572 /// entirely. For AFTER, the return value is ignored.
573 Null,
574 /// `RETURN <expr>;` — non-row return shape; reserved for the
575 /// scalar UDF surface in v7.12.5+. Executor errors when used
576 /// inside a trigger function.
577 Expr(Expr),
578}
579
580/// v7.12.4 — `CREATE [OR REPLACE] TRIGGER`. Always row-level
581/// (`FOR EACH ROW`) in v7.12.4 — statement-level triggers parse
582/// but the executor refuses them. `WHEN (cond)` clauses are out
583/// of scope; the trigger function can short-circuit on a leading
584/// IF inside its body once v7.12.5 lands IF.
585#[derive(Debug, Clone, PartialEq)]
586pub struct CreateTriggerStatement {
587 pub name: String,
588 pub or_replace: bool,
589 pub timing: TriggerTiming,
590 /// At least one event; `INSERT OR UPDATE OR DELETE` parses to
591 /// three entries in order.
592 pub events: Vec<TriggerEvent>,
593 pub table: String,
594 /// `FOR EACH ROW` vs `FOR EACH STATEMENT`. v7.12.4 ships
595 /// only `Row`; `Statement` parses but the executor refuses.
596 pub for_each: TriggerForEach,
597 /// Name of the function to invoke. v7.12.4 requires the
598 /// function to be `CREATE FUNCTION`'d earlier; forward
599 /// references (PG accepts) are deferred to v7.12.5.
600 pub function: String,
601 /// v7.13.0 — `UPDATE OF col, col, …` column-list filter
602 /// (mailrs round-5 G7). Non-empty only when the events list
603 /// contains UPDATE and the user wrote the column-list filter.
604 /// PG fires the trigger only when at least one of these
605 /// columns appears in the SET clause; SPG conservatively
606 /// fires on any UPDATE matching the listed columns or
607 /// rewriting them at the row level. Empty vec = no filter
608 /// (fire on every UPDATE).
609 pub update_columns: Vec<String>,
610}
611
612#[derive(Debug, Clone, Copy, PartialEq, Eq)]
613pub enum TriggerTiming {
614 /// Fires before the row is written; the trigger function's
615 /// return value (NEW or NULL) decides the row content and
616 /// whether the write proceeds at all.
617 Before,
618 /// Fires after the row is written; the return value is
619 /// ignored.
620 After,
621 /// `INSTEAD OF` is PG-VIEW-trigger-only and out of scope for
622 /// v7.12.4 (SPG has no updatable-view surface).
623 InsteadOf,
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq)]
627pub enum TriggerEvent {
628 Insert,
629 Update,
630 Delete,
631 /// `TRUNCATE` event parses; SPG has no TRUNCATE statement
632 /// so the trigger never fires.
633 Truncate,
634}
635
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
637pub enum TriggerForEach {
638 Row,
639 Statement,
640}
641
642#[derive(Debug, Clone, PartialEq)]
643pub struct CreateIndexStatement {
644 pub name: String,
645 pub table: String,
646 pub column: String,
647 /// Optional `USING <method>` clause. v2.0 recognises `hnsw` (NSW
648 /// graph for vector kNN); unspecified is the default B-tree index.
649 pub method: IndexMethod,
650 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
651 /// index name already exists, instead of raising `DuplicateIndex`.
652 pub if_not_exists: bool,
653 /// v6.8.0 — `INCLUDE (col1, col2, …)` columns. Identifies the
654 /// non-key columns the planner should treat as "covered" by
655 /// this index when checking whether a query can run as an
656 /// index-only scan. Empty when no `INCLUDE` clause was given.
657 pub included_columns: Vec<String>,
658 /// v6.8.1 — `WHERE <expr>` partial-index predicate. Only rows
659 /// for which `<expr>` evaluates truthy enter the index;
660 /// queries whose `WHERE` clause's canonical Display form
661 /// matches this expression's Display form can be served by the
662 /// partial index. Stored as a parsed `Expr` so the engine
663 /// re-uses the existing evaluation path; storage persists the
664 /// Display form on the catalog snapshot.
665 pub partial_predicate: Option<Expr>,
666 /// v6.8.2 — expression-based index. When `Some(expr)`, the
667 /// index key is the result of `expr` evaluated on each row
668 /// (e.g. `CREATE INDEX … (lower(name))`). The `column`
669 /// field still names the *primary* column the expression
670 /// touches so existing planner shortcuts that resolve a
671 /// column position stay valid. `None` = plain
672 /// column-reference index (the legacy shape).
673 pub expression: Option<Expr>,
674 /// v7.9.14 — extra column names after the leading column in a
675 /// multi-column `CREATE INDEX … (a, b, c)`. mailrs F2. The
676 /// planner today still only uses the leading column for index
677 /// seeks; the extras are tracked verbatim so the same DDL
678 /// round-trips through WAL replay + catalog snapshot, and so
679 /// the engine can emit a clear warning at INDEX CREATE time
680 /// that only the leading column is currently honoured.
681 /// Composite BTree index keys land in v7.10.
682 pub extra_columns: Vec<String>,
683 /// v7.9.29 — `CREATE UNIQUE INDEX …`. When true the engine
684 /// enforces uniqueness on the indexed key (combined with the
685 /// `partial_predicate` filter — only rows where the predicate
686 /// evaluates truthy enter the uniqueness check). Standard SQL
687 /// and PG's canonical way to express conditional uniqueness.
688 /// mailrs K1.
689 pub is_unique: bool,
690}
691
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub enum IndexMethod {
694 /// Default — B-tree over `IndexKey`. Used for equality / range
695 /// lookups on scalar columns.
696 BTree,
697 /// `USING hnsw` — NSW graph for kNN over a vector column.
698 Hnsw,
699 /// v6.7.1 — `USING brin` — Block Range INdex. Per-segment
700 /// metadata that records (min_key, max_key) for each page in a
701 /// cold-tier segment, on the indexed column. The optimizer
702 /// can use these summaries to skip pages whose range does NOT
703 /// overlap a query's WHERE predicate. BRIN indexes carry no
704 /// in-memory data — the summaries live in the segment v2
705 /// envelope's sidecar. Created via the standard
706 /// `CREATE INDEX … USING brin (col)` syntax.
707 Brin,
708 /// v7.12.3 — `USING gin` — inverted index over a `tsvector`
709 /// column. Posting lists map `lexeme word` → row locators; the
710 /// planner uses them to narrow `WHERE col @@ tsquery` to the
711 /// candidate rows whose vectors contain a matching term, then
712 /// re-evaluates the full `@@` semantics on each candidate.
713 /// Replaces the v7.9.26b `USING gin` → BTree fallback that
714 /// silently degraded to a full scan at query time.
715 Gin,
716}
717
718#[derive(Debug, Clone, PartialEq)]
719pub struct CreateTableStatement {
720 pub name: String,
721 pub columns: Vec<ColumnDef>,
722 /// `IF NOT EXISTS` — engine returns `CommandOk` no-op when the
723 /// table name already exists, instead of raising `DuplicateTable`.
724 pub if_not_exists: bool,
725 /// v7.6.0 — table-level `FOREIGN KEY (...) REFERENCES ...`
726 /// constraints. Column-level `REFERENCES` (single-column inline
727 /// form) is normalised into this vec at parse time so the engine
728 /// sees one uniform list.
729 pub foreign_keys: Vec<ForeignKeyConstraint>,
730 /// v7.9.18 — table-level constraints: `PRIMARY KEY (a, b)` and
731 /// `UNIQUE (a, b, ...)`. mailrs migration follow-up G1 + G6.
732 /// Engine resolves each into a BTree index named after the
733 /// constraint's leading column at CREATE TABLE time; INSERT
734 /// path enforces composite uniqueness via row scan on the
735 /// leading column index.
736 pub table_constraints: Vec<TableConstraint>,
737}
738
739/// v7.9.18 — table-level constraint at the end of a CREATE TABLE
740/// column list. Either a composite PRIMARY KEY or a UNIQUE
741/// (single- or multi-column).
742#[derive(Debug, Clone, PartialEq)]
743pub enum TableConstraint {
744 /// `PRIMARY KEY (col1, col2, ...)`. Implies NOT NULL on each
745 /// referenced column. Engine builds a BTree index named
746 /// `<table>_pkey` and enforces composite uniqueness on INSERT.
747 PrimaryKey {
748 name: Option<String>,
749 columns: Vec<String>,
750 },
751 /// `UNIQUE (col1, col2, ...)`. Engine builds a BTree index
752 /// named `<table>_<leading_col>_key` (single-column) or
753 /// `<table>_<leading_col>_<…>_key` (composite) and enforces
754 /// uniqueness on INSERT.
755 Unique {
756 name: Option<String>,
757 columns: Vec<String>,
758 /// v7.13.0 — `NULLS NOT DISTINCT` modifier (mailrs round-5
759 /// G10). PG 15+ flips the NULL handling so any number of
760 /// NULL rows collide on the constraint. Default is
761 /// `false` (NULLS DISTINCT, standard SQL behaviour).
762 nulls_not_distinct: bool,
763 },
764 /// v7.13.0 — `CHECK (<expr>)` table-level constraint
765 /// (mailrs round-5 G3). Column-level inline CHECKs fold into
766 /// this same variant at parse time. Engine evaluates the
767 /// predicate against each INSERT/UPDATE candidate row; a
768 /// false / NULL result rejects the mutation.
769 Check {
770 name: Option<String>,
771 expr: Expr,
772 },
773}
774
775#[derive(Debug, Clone, PartialEq)]
776pub struct ColumnDef {
777 pub name: String,
778 pub ty: ColumnTypeName,
779 pub nullable: bool,
780 /// `DEFAULT <expr>` literal supplied at CREATE TABLE. Engine
781 /// evaluates this once (with an empty row) and caches the resulting
782 /// `Value` on the column schema.
783 pub default: Option<Expr>,
784 /// MySQL-style `AUTO_INCREMENT` — the engine maintains a counter
785 /// per such column and fills the slot when INSERT leaves it
786 /// unbound (omitted from a column-list INSERT or explicitly NULL).
787 pub auto_increment: bool,
788 /// v7.9.13 — inline `PRIMARY KEY` column constraint. mailrs
789 /// migration follow-up F1. Implies `NOT NULL`. Engine creates
790 /// an implicit BTree index named `<table>_pkey` over this
791 /// column at CREATE TABLE time, satisfying the parent-side
792 /// index requirement for any FOREIGN KEY pointing at it.
793 pub is_primary_key: bool,
794 /// v7.13.0 — inline `UNIQUE` column constraint
795 /// (mailrs round-5 G2). The CREATE TABLE handler folds this
796 /// into a single-column `TableConstraint::Unique` so the
797 /// engine path stays uniform with table-level UNIQUE.
798 pub is_unique: bool,
799 /// v7.13.0 — inline `CHECK (<expr>)` column constraint
800 /// (mailrs round-5 G3). Stored alongside the column so the
801 /// CREATE TABLE handler can fold these into table-level
802 /// CHECK constraints. Multiple inline CHECKs on the same
803 /// column are concatenated with AND at the table level.
804 pub check: Option<Expr>,
805}
806
807/// v7.6.0 — A single FOREIGN KEY constraint. Both column-level
808/// `REFERENCES` and table-level `FOREIGN KEY (...) REFERENCES ...`
809/// parse into this shape — the column-level form has a single-entry
810/// `columns` / `parent_columns`.
811#[derive(Debug, Clone, PartialEq)]
812pub struct ForeignKeyConstraint {
813 /// Optional `CONSTRAINT <name>` prefix. Engine ignores the name
814 /// today but parses + stores it so a future ALTER TABLE DROP
815 /// CONSTRAINT can target by name (v7.6.8).
816 pub name: Option<String>,
817 /// Local columns participating in the FK (≥ 1).
818 pub columns: Vec<String>,
819 /// Referenced parent table.
820 pub parent_table: String,
821 /// Referenced parent columns. Must have the same arity as
822 /// `columns`; engine validates parent has a PK / UNIQUE index
823 /// on exactly this column set (v7.6.1).
824 pub parent_columns: Vec<String>,
825 /// `ON DELETE` action. Defaults to `Restrict` if absent.
826 pub on_delete: FkAction,
827 /// `ON UPDATE` action. Defaults to `Restrict` if absent.
828 pub on_update: FkAction,
829}
830
831/// v7.6.0 — Referential action for `ON DELETE` / `ON UPDATE`.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833pub enum FkAction {
834 /// Reject the parent mutation if any child row references it.
835 /// SQL spec default; SPG default when no clause is given.
836 Restrict,
837 /// Recursively propagate the parent's delete / update to the
838 /// child rows. Same TX.
839 Cascade,
840 /// Set the child FK column(s) to NULL. Requires the FK columns
841 /// to be NULL-able.
842 SetNull,
843 /// Set the child FK column(s) to their declared DEFAULT.
844 /// Requires the child column(s) to have DEFAULT.
845 SetDefault,
846 /// SQL spec `NO ACTION` (deferred check). SPG treats this as
847 /// `Restrict` because the single-writer model has no deferred
848 /// constraint window; the keyword is accepted for compatibility.
849 NoAction,
850}
851
852/// In-cell encoding for a `VECTOR(N)` column. v6.0.1 added the
853/// optional `USING <encoding>` clause; omitting it keeps the
854/// pre-v6 `F32` default. `Sq8` quantises each cell to a per-vector
855/// affine `(min, max, [u8; dim])` triple (4× compression). `F16`
856/// (v6.0.3, DDL keyword `HALF`) stores each element as IEEE-754
857/// binary16 (2× compression, ~3 decimal digits of precision).
858#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
859pub enum VecEncoding {
860 /// IEEE-754 binary32. Pre-v6 default; matches pgvector's
861 /// uncompressed `vector` type wire / storage layout.
862 #[default]
863 F32,
864 /// v6.0.1 SQ8 — per-vector affine 8-bit quantisation. See
865 /// `spg_storage::quantize::Sq8Vector` for the math + recall
866 /// envelope (≥ 0.95 on Gaussian / unit-sphere corpora at
867 /// dim ≥ 32).
868 Sq8,
869 /// v6.0.3 halfvec — IEEE-754 binary16 (half-precision)
870 /// per-element. DDL keyword `HALF` (pgvector convention).
871 /// Bit-exact dequantise to f32 at the storage layer; no
872 /// rerank pass needed for kNN search.
873 F16,
874}
875
876impl fmt::Display for VecEncoding {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
878 match self {
879 Self::F32 => f.write_str("F32"),
880 Self::Sq8 => f.write_str("SQ8"),
881 // pgvector convention: DDL keyword is `HALF`, not `F16`.
882 Self::F16 => f.write_str("HALF"),
883 }
884 }
885}
886
887/// SQL-level type names. The mapping to the storage runtime's `DataType`
888/// happens in `spg-engine` — keeping `spg-sql` free of storage deps.
889#[derive(Debug, Clone, Copy, PartialEq, Eq)]
890pub enum ColumnTypeName {
891 SmallInt,
892 Int,
893 BigInt,
894 Float,
895 Text,
896 /// `VARCHAR(N)` — TEXT capped at N Unicode characters.
897 Varchar(u32),
898 /// `CHAR(N)` — TEXT right-padded with spaces to exactly N characters.
899 Char(u32),
900 Bool,
901 /// pgvector fixed-dimension `VECTOR(N)`. v6.0.1 added the
902 /// `USING <encoding>` clause; omitting it surfaces as
903 /// `encoding = VecEncoding::F32` (the pre-v6 default).
904 Vector {
905 dim: u32,
906 encoding: VecEncoding,
907 },
908 /// `NUMERIC` / `NUMERIC(p)` / `NUMERIC(p, s)` — exact decimal.
909 /// Bare `NUMERIC` and `NUMERIC(p)` both surface with `scale=0`.
910 Numeric(u8, u8),
911 /// `DATE` — calendar day, no time-of-day component.
912 Date,
913 /// `TIMESTAMP` / `MySQL` `DATETIME` — instant with microsecond
914 /// precision.
915 Timestamp,
916 /// v7.9.2 `TIMESTAMPTZ` / `TIMESTAMP WITH TIME ZONE`. SPG
917 /// stores all timestamps as UTC microseconds-since-epoch and
918 /// does not carry per-row offset (PG's internal representation
919 /// is the same — TZ is a display convention). The distinction
920 /// from `TIMESTAMP` exists for the PG-wire layer to advertise
921 /// OID 1184 so sqlx-style clients decode into
922 /// `chrono::DateTime<Utc>` instead of `NaiveDateTime`.
923 Timestamptz,
924 /// v4.9 `JSON` — text-backed JSON document. No parse-time
925 /// validation; the engine round-trips the literal verbatim.
926 /// PG OID 114 on the wire.
927 Json,
928 /// v7.9.0 `JSONB` — same storage shape as Json, advertised as
929 /// PG OID 3802 on the wire so sqlx-style binary-typed clients
930 /// decode without a custom type registration.
931 Jsonb,
932 /// v7.10.4 `BYTES` / `BYTEA` — raw binary blob. PG wire OID 17.
933 /// Literal forms (decoded by the engine at coercion time):
934 /// - PG hex form: `'\xDEADBEEF'`
935 /// - Escape form: `'foo\\000bar'` (backslash octal triples)
936 Bytes,
937 /// v7.10.10 `TEXT[]` — single-dimension TEXT array. PG wire
938 /// OID 1009. Literal forms accepted by the parser:
939 /// - `ARRAY['a', 'b', NULL]`
940 /// - `'{a,b,NULL}'::TEXT[]` (engine decodes the external
941 /// form at coerce time)
942 TextArray,
943 /// v7.11.13 `INT[]` — single-dimension i32 array. PG wire OID
944 /// 1007. Same literal forms as TEXT[] (substituting integer
945 /// elements).
946 IntArray,
947 /// v7.11.13 `BIGINT[]` — single-dimension i64 array. PG wire
948 /// OID 1016.
949 BigIntArray,
950 /// v7.12.0 `tsvector` — PG full-text search lexeme set. PG
951 /// wire OID 3614. Literal: `'foo:1 bar:2'::tsvector` (PG
952 /// external form). G-CRIT-3.
953 TsVector,
954 /// v7.12.0 `tsquery` — PG full-text search parse tree. PG
955 /// wire OID 3615.
956 TsQuery,
957}
958
959impl fmt::Display for ColumnTypeName {
960 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
961 match self {
962 Self::SmallInt => f.write_str("SMALLINT"),
963 Self::Int => f.write_str("INT"),
964 Self::BigInt => f.write_str("BIGINT"),
965 Self::Float => f.write_str("FLOAT"),
966 Self::Text => f.write_str("TEXT"),
967 Self::Varchar(n) => write!(f, "VARCHAR({n})"),
968 Self::Char(n) => write!(f, "CHAR({n})"),
969 Self::Bool => f.write_str("BOOL"),
970 Self::Vector { dim, encoding } => match encoding {
971 VecEncoding::F32 => write!(f, "VECTOR({dim})"),
972 VecEncoding::Sq8 => write!(f, "VECTOR({dim}) USING SQ8"),
973 VecEncoding::F16 => write!(f, "VECTOR({dim}) USING HALF"),
974 },
975 Self::Json => f.write_str("JSON"),
976 Self::Jsonb => f.write_str("JSONB"),
977 Self::Bytes => f.write_str("BYTEA"),
978 Self::TextArray => f.write_str("TEXT[]"),
979 Self::IntArray => f.write_str("INT[]"),
980 Self::BigIntArray => f.write_str("BIGINT[]"),
981 Self::TsVector => f.write_str("TSVECTOR"),
982 Self::TsQuery => f.write_str("TSQUERY"),
983 Self::Numeric(p, s) => {
984 if *s == 0 {
985 write!(f, "NUMERIC({p})")
986 } else {
987 write!(f, "NUMERIC({p}, {s})")
988 }
989 }
990 Self::Date => f.write_str("DATE"),
991 Self::Timestamp => f.write_str("TIMESTAMP"),
992 Self::Timestamptz => f.write_str("TIMESTAMPTZ"),
993 }
994 }
995}
996
997/// `UPDATE <table> SET col = expr [, ...] [WHERE cond]`. v4.4 — the
998/// engine evaluates `expr` per matched row in the table's row order
999/// and rewrites cells in place. Indexed columns are dropped + re-
1000/// inserted into the affected B-tree on each row change.
1001#[derive(Debug, Clone, PartialEq)]
1002pub struct UpdateStatement {
1003 pub table: String,
1004 pub assignments: Vec<(String, Expr)>,
1005 pub where_: Option<Expr>,
1006 /// v7.9.4 — `RETURNING <projection>`. None = no RETURNING
1007 /// clause (legacy CommandComplete path). Some = engine
1008 /// evaluates the projection over each mutated row and
1009 /// streams the result as a Rows QueryResult.
1010 pub returning: Option<Vec<SelectItem>>,
1011}
1012
1013/// `DELETE FROM <table> [WHERE cond]`. v4.4 — removes matched rows
1014/// from the active catalog and prunes them from every index.
1015#[derive(Debug, Clone, PartialEq)]
1016pub struct DeleteStatement {
1017 pub table: String,
1018 pub where_: Option<Expr>,
1019 /// v7.9.4 — `RETURNING <projection>`.
1020 pub returning: Option<Vec<SelectItem>>,
1021}
1022
1023#[derive(Debug, Clone, PartialEq)]
1024pub struct InsertStatement {
1025 pub table: String,
1026 /// Optional column list — `INSERT INTO t (a, b) VALUES (...)`. When
1027 /// `None`, every tuple is positional and must match the table arity.
1028 /// When `Some`, the engine maps each tuple slot to the named column and
1029 /// fills the rest with NULL (must be nullable).
1030 pub columns: Option<Vec<String>>,
1031 /// One or more `(expr, expr, ...)` tuples — the multi-row VALUES form.
1032 /// v1.3+ accepts `INSERT INTO t VALUES (a), (b)`. Empty when
1033 /// `select_source` is `Some` (the engine builds rows from the
1034 /// inner SELECT result set instead).
1035 pub rows: Vec<Vec<Expr>>,
1036 /// v7.13.0 — `INSERT INTO t [(cols)] SELECT …` (mailrs
1037 /// round-5 G4). When present, `rows` is empty and the engine
1038 /// materialises the SELECT result, coerces each output tuple to
1039 /// the target column types, and inserts as a single batch.
1040 pub select_source: Option<Box<SelectStatement>>,
1041 /// v7.9.7 — `ON CONFLICT (cols) DO { NOTHING | UPDATE SET … }`
1042 /// upsert clause. None = legacy INSERT (conflict raises a
1043 /// DuplicateKey error). mailrs migration blocker #2.
1044 pub on_conflict: Option<OnConflictClause>,
1045 /// v7.9.4 — `RETURNING <projection>`.
1046 pub returning: Option<Vec<SelectItem>>,
1047}
1048
1049/// v7.9.7 — INSERT upsert clause: `ON CONFLICT (target) DO action`.
1050#[derive(Debug, Clone, PartialEq)]
1051pub struct OnConflictClause {
1052 /// Local columns that identify the conflict (must match a
1053 /// UNIQUE / PRIMARY KEY index on the target table). Empty
1054 /// list means the user wrote `ON CONFLICT DO …` without a
1055 /// target — engine picks the table's first BTree index by
1056 /// convention.
1057 pub target_columns: Vec<String>,
1058 /// The action on conflict.
1059 pub action: OnConflictAction,
1060}
1061
1062/// v7.9.7 — action on conflict.
1063#[derive(Debug, Clone, PartialEq)]
1064pub enum OnConflictAction {
1065 /// `DO NOTHING` — INSERT proceeds for non-conflicting rows,
1066 /// silently skips conflicting ones.
1067 Nothing,
1068 /// `DO UPDATE SET col = expr [, …] [WHERE cond]`. `assignments`
1069 /// may reference `EXCLUDED.col` to read the incoming row's
1070 /// value (engine wires `EXCLUDED` as a virtual table).
1071 Update {
1072 assignments: Vec<(String, Expr)>,
1073 where_: Option<Expr>,
1074 },
1075}
1076
1077#[derive(Debug, Clone, PartialEq)]
1078pub struct SelectStatement {
1079 /// v4.11: `WITH name AS (SELECT ...) [, ...]` common-table
1080 /// expressions, materialised once at query start before the
1081 /// body SELECT runs. Empty for a regular SELECT. Non-recursive
1082 /// only — no `WITH RECURSIVE` for v4.x.
1083 pub ctes: Vec<Cte>,
1084 pub distinct: bool,
1085 pub items: Vec<SelectItem>,
1086 pub from: Option<FromClause>,
1087 pub where_: Option<Expr>,
1088 pub group_by: Option<Vec<Expr>>,
1089 /// v6.4.1 — `GROUP BY ALL` shortcut: when true, the planner
1090 /// expands `group_by` to every non-aggregate SELECT-list item
1091 /// before the executor runs. Mutually exclusive with an
1092 /// explicit `group_by` list (the parser sets exactly one).
1093 pub group_by_all: bool,
1094 /// `HAVING <expr>` — filter applied *after* `GROUP BY` aggregation.
1095 /// Supports aggregate calls (e.g. `HAVING count(*) > 1`); the
1096 /// aggregate executor resolves them through the same synthetic
1097 /// schema used for the SELECT items.
1098 pub having: Option<Expr>,
1099 /// UNION / UNION ALL chain. Empty for a plain SELECT. Each peer is
1100 /// itself a `SelectStatement` with `order_by = None` and `limit =
1101 /// None` (the parser enforces that — ORDER BY / LIMIT belong to the
1102 /// top of the chain).
1103 pub unions: Vec<(UnionKind, SelectStatement)>,
1104 /// v6.4.0 — multi-key ORDER BY. Empty `Vec` means no ORDER BY.
1105 /// Keys are matched left-to-right: first key decides, ties break
1106 /// to the second, etc.
1107 pub order_by: Vec<OrderBy>,
1108 /// `LIMIT <n>` — bound on row output. `n` is an integer
1109 /// literal **or** (v7.9.24) a placeholder `$N` resolved
1110 /// against the prepared-statement Bind values. mailrs
1111 /// migration follow-up H2.
1112 pub limit: Option<LimitExpr>,
1113 /// `OFFSET <n>` — drop the first `n` rows after ORDER BY but
1114 /// before LIMIT (so `LIMIT 10 OFFSET 5` keeps rows 6..=15).
1115 pub offset: Option<LimitExpr>,
1116}
1117
1118/// v7.9.24 — LIMIT / OFFSET value. Integer literal at parse
1119/// time or a placeholder `$N` resolved during extended-query
1120/// Bind. mailrs migration follow-up H2.
1121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1122pub enum LimitExpr {
1123 /// `LIMIT 10` — value known at parse time.
1124 Literal(u32),
1125 /// `LIMIT $N` — the 1-based parameter index, resolved against
1126 /// the bind values when the prepared statement executes.
1127 Placeholder(u16),
1128}
1129
1130impl fmt::Display for LimitExpr {
1131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132 match self {
1133 Self::Literal(n) => write!(f, "{n}"),
1134 Self::Placeholder(n) => write!(f, "${n}"),
1135 }
1136 }
1137}
1138
1139impl LimitExpr {
1140 /// Convenience for the simple-query path where no placeholders
1141 /// can possibly exist. Returns the literal value or `None` if
1142 /// this is a placeholder (caller must surface as Unsupported).
1143 pub fn as_literal(self) -> Option<u32> {
1144 match self {
1145 Self::Literal(n) => Some(n),
1146 Self::Placeholder(_) => None,
1147 }
1148 }
1149}
1150
1151/// v7.9.24 — extract LIMIT / OFFSET as a `u32` literal. After
1152/// the engine's `substitute_placeholders` pass these are
1153/// always Literal; in the simple-query path a Placeholder
1154/// shape returns None (executor surfaces as
1155/// "LIMIT/OFFSET ${n} requires prepared-statement binding").
1156impl SelectStatement {
1157 #[must_use]
1158 pub fn limit_literal(&self) -> Option<u32> {
1159 self.limit.and_then(LimitExpr::as_literal)
1160 }
1161 #[must_use]
1162 pub fn offset_literal(&self) -> Option<u32> {
1163 self.offset.and_then(LimitExpr::as_literal)
1164 }
1165}
1166
1167#[derive(Debug, Clone, PartialEq)]
1168pub struct Cte {
1169 pub name: String,
1170 pub body: SelectStatement,
1171 /// v4.22: `WITH RECURSIVE` — set when the WITH clause had the
1172 /// RECURSIVE keyword. Applies to every CTE in the clause per
1173 /// PG semantics. A non-recursive body in a RECURSIVE WITH is
1174 /// allowed; the engine just runs it once.
1175 pub recursive: bool,
1176 /// v4.22: optional `WITH name(a, b, c)` column-name list. When
1177 /// non-empty, these override the body's output column names
1178 /// position-by-position; the engine errors out if the count
1179 /// doesn't match the body's projection width.
1180 pub column_overrides: Vec<String>,
1181}
1182
1183#[derive(Debug, Clone, PartialEq)]
1184pub struct OrderBy {
1185 pub expr: Expr,
1186 /// `false` = ASC (default), `true` = DESC.
1187 pub desc: bool,
1188}
1189
1190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1191pub enum UnionKind {
1192 /// `UNION` — dedupes the combined set.
1193 Distinct,
1194 /// `UNION ALL` — concatenates without dedup.
1195 All,
1196}
1197
1198#[derive(Debug, Clone, PartialEq)]
1199pub enum SelectItem {
1200 Wildcard,
1201 Expr { expr: Expr, alias: Option<String> },
1202}
1203
1204#[derive(Debug, Clone, PartialEq)]
1205pub struct TableRef {
1206 pub name: String,
1207 pub alias: Option<String>,
1208 /// v6.10.2 — `AS OF SEGMENT '<id>'` cold-tier time-travel.
1209 /// When `Some(id)`, the scan restricts to rows that live in
1210 /// segment `<id>` only — useful for forensic inspection of a
1211 /// specific freezer-emitted segment without exposing the hot
1212 /// tier. `AS OF TIMESTAMP <ts>` (PG-flavoured time travel)
1213 /// is STABILITY carve-out for v6.10 — needs the freezer to
1214 /// stamp each segment with a wall-clock at creation time.
1215 pub as_of_segment: Option<u32>,
1216 /// v7.11.7 — `FROM unnest(<expr>) [AS] <alias>` set-returning
1217 /// source. When `Some`, `name` is the alias (defaulting to
1218 /// `"unnest"` when no `AS` is given) and the engine builds a
1219 /// synthetic single-column table by evaluating the expression
1220 /// once at SELECT entry. Each TEXT[] element becomes one row;
1221 /// NULL elements become NULL cells. v7.11 supported
1222 /// uncorrelated UNNEST only as the FROM primary; v7.13.2
1223 /// (mailrs round-6 S5) widens to UNNEST in any FROM-list
1224 /// position (cross-join with regular tables).
1225 pub unnest_expr: Option<Box<Expr>>,
1226 /// v7.13.2 — mailrs round-6 S5. PG-standard
1227 /// `UNNEST(<arr>) AS alias(col_name)` column-list aliasing:
1228 /// when non-empty, the first entry overrides the projected
1229 /// column name for the unnested column. Empty = fall back to
1230 /// the table alias (pre-v7.13.2 behaviour).
1231 pub unnest_column_aliases: Vec<String>,
1232}
1233
1234/// FROM clause shape. v1.10 accepts a primary table plus a flat list of
1235/// joined peers — `FROM a [, b]* [INNER|LEFT] JOIN c ON expr ...`. The
1236/// joins evaluate left-associatively in nested-loop order.
1237#[derive(Debug, Clone, PartialEq)]
1238pub struct FromClause {
1239 pub primary: TableRef,
1240 pub joins: Vec<FromJoin>,
1241}
1242
1243#[derive(Debug, Clone, PartialEq)]
1244pub struct FromJoin {
1245 pub kind: JoinKind,
1246 pub table: TableRef,
1247 /// Required for INNER/LEFT; must be `None` for CROSS / comma-list.
1248 pub on: Option<Expr>,
1249}
1250
1251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1252pub enum JoinKind {
1253 Inner,
1254 Left,
1255 Cross,
1256}
1257
1258#[derive(Debug, Clone, PartialEq)]
1259pub enum Expr {
1260 Literal(Literal),
1261 Column(ColumnName),
1262 /// v6.1.1 — `$N` parameter placeholder for the extended query
1263 /// protocol. The number is 1-based per PostgreSQL convention.
1264 /// Evaluation looks up `params[N-1]` from the prepared-statement
1265 /// bind buffer; out-of-range indices raise a runtime error
1266 /// (same shape as a column-not-found miss).
1267 Placeholder(u16),
1268 Binary {
1269 lhs: Box<Expr>,
1270 op: BinOp,
1271 rhs: Box<Expr>,
1272 },
1273 Unary {
1274 op: UnOp,
1275 expr: Box<Expr>,
1276 },
1277 /// PG-style `expr::TYPE` cast. v1.3 supports VECTOR, INT, BIGINT, FLOAT,
1278 /// TEXT, BOOL targets; engine coerces at evaluation time.
1279 Cast {
1280 expr: Box<Expr>,
1281 target: CastTarget,
1282 },
1283 /// Postfix `IS NULL` / `IS NOT NULL`. Returns BOOL.
1284 IsNull {
1285 expr: Box<Expr>,
1286 negated: bool,
1287 },
1288 /// Function call `name(args...)`. v1.4 supports a small built-in set
1289 /// (length, upper, lower, abs, coalesce); unknown names error at eval
1290 /// time so the parser stays open for v1.5 aggregates.
1291 FunctionCall {
1292 name: String,
1293 args: Vec<Expr>,
1294 },
1295 /// SQL `LIKE` predicate. `pattern` evaluates to text at runtime;
1296 /// wildcards are `%` (any run) and `_` (one char), backslash escapes
1297 /// the next char (so `\%` matches a literal `%`).
1298 Like {
1299 expr: Box<Expr>,
1300 pattern: Box<Expr>,
1301 negated: bool,
1302 },
1303 /// v4.12 window function call: `name(args) OVER (PARTITION BY
1304 /// ... ORDER BY ...)`. Supports `ROW_NUMBER` / `RANK` /
1305 /// `DENSE_RANK` and the partition-aware aggregates `SUM` /
1306 /// `AVG` / `COUNT` / `MIN` / `MAX`. The window frame defaults to "entire partition" for
1307 /// unordered windows and "from start of partition through
1308 /// current row" for ordered windows — no explicit ROWS /
1309 /// RANGE clause in v4.12 MVP.
1310 WindowFunction {
1311 name: String,
1312 args: Vec<Expr>,
1313 partition_by: Vec<Expr>,
1314 order_by: Vec<(Expr, bool /* desc */)>,
1315 /// v4.20 explicit frame. `None` means "use the default":
1316 /// whole-partition when unordered, running aggregate from
1317 /// partition start through current row when ordered.
1318 frame: Option<WindowFrame>,
1319 /// v6.4.2 — `IGNORE NULLS` / `RESPECT NULLS` modifier on
1320 /// LAG / LEAD / FIRST_VALUE / LAST_VALUE. Default is
1321 /// `Respect` (PG / ANSI default — NULLs participate). Other
1322 /// window functions ignore this flag.
1323 null_treatment: NullTreatment,
1324 },
1325 /// v4.10 scalar subquery — `(SELECT ...)` used in expression
1326 /// position. Must return exactly one row × one column at eval
1327 /// time; the engine errors out otherwise. Uncorrelated only —
1328 /// the inner SELECT cannot reference outer columns.
1329 ScalarSubquery(Box<SelectStatement>),
1330 /// v4.10 `[NOT] EXISTS (SELECT ...)`. Returns Bool. Inner
1331 /// projection is ignored; only row-count matters.
1332 Exists {
1333 subquery: Box<SelectStatement>,
1334 negated: bool,
1335 },
1336 /// v4.10 `expr [NOT] IN (SELECT ...)`. Inner SELECT must
1337 /// project exactly one column; membership is tested by Eq
1338 /// against each row's value (NULL handling follows ANSI:
1339 /// NULL ∈ list ⇒ NULL ; otherwise present ⇒ true).
1340 InSubquery {
1341 expr: Box<Expr>,
1342 subquery: Box<SelectStatement>,
1343 negated: bool,
1344 },
1345 /// `EXTRACT(<field> FROM <source>)` — pull an integer component
1346 /// out of a `DATE` or `TIMESTAMP`. Parsed as its own AST node
1347 /// because the `FROM` keyword is what separates the two halves,
1348 /// not a comma.
1349 Extract {
1350 field: ExtractField,
1351 source: Box<Expr>,
1352 },
1353 /// v7.10.10 — `ARRAY[expr, expr, …]` array constructor. Each
1354 /// element is evaluated independently; NULLs are allowed.
1355 /// v7.10 supports only single-dimension TEXT[] semantically;
1356 /// non-text elements coerce at engine evaluation time when
1357 /// the surrounding context (column type / cast) makes the
1358 /// target clear.
1359 Array(Vec<Expr>),
1360 /// v7.10.10 — array subscript `arr[i]`. PG 1-based; the
1361 /// engine returns NULL for out-of-range indices.
1362 ArraySubscript {
1363 target: Box<Expr>,
1364 index: Box<Expr>,
1365 },
1366 /// v7.10.12 — `expr op ANY(arr)` and `expr op ALL(arr)`. The
1367 /// operator is the comparison binary op (Eq / Ne / Lt / …);
1368 /// the engine desugars: `ANY` returns true if any element
1369 /// satisfies; `ALL` returns true only if every element does.
1370 /// NULL handling follows PG's three-valued logic.
1371 AnyAll {
1372 expr: Box<Expr>,
1373 op: BinOp,
1374 array: Box<Expr>,
1375 /// `true` = ANY, `false` = ALL.
1376 is_any: bool,
1377 },
1378 /// v7.13.0 — `CASE WHEN <cond> THEN <val> ... ELSE <val> END`
1379 /// (searched form, `operand` is None) and
1380 /// `CASE <expr> WHEN <val> THEN <val> ... END` (simple form,
1381 /// `operand` is the lead expression compared against each
1382 /// branch's match). Each `(when_expr, then_expr)` branch
1383 /// stays as written; engine short-circuits on the first match.
1384 /// `else_branch` is `None` when no ELSE; evaluates to NULL.
1385 /// mailrs round-5 G9.
1386 Case {
1387 operand: Option<Box<Expr>>,
1388 branches: Vec<(Expr, Expr)>,
1389 else_branch: Option<Box<Expr>>,
1390 },
1391}
1392
1393/// v6.4.2 — null treatment on `LAG` / `LEAD` / `FIRST_VALUE` /
1394/// `LAST_VALUE`. PG / ANSI default is `Respect` — NULLs participate
1395/// in the offset walk. `Ignore` causes the function to skip NULL
1396/// values in the argument expression, returning the next non-NULL.
1397#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1398pub enum NullTreatment {
1399 #[default]
1400 Respect,
1401 Ignore,
1402}
1403
1404/// v4.20 explicit window frame: `ROWS|RANGE BETWEEN <bound> AND
1405/// <bound>`. `end` is `None` for the shorthand "ROWS <bound>"
1406/// where end implicitly = CURRENT ROW.
1407#[derive(Debug, Clone, PartialEq, Eq)]
1408pub struct WindowFrame {
1409 pub kind: FrameKind,
1410 pub start: FrameBound,
1411 pub end: Option<FrameBound>,
1412}
1413
1414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1415pub enum FrameKind {
1416 Rows,
1417 Range,
1418}
1419
1420#[derive(Debug, Clone, PartialEq, Eq)]
1421pub enum FrameBound {
1422 UnboundedPreceding,
1423 OffsetPreceding(u64),
1424 CurrentRow,
1425 OffsetFollowing(u64),
1426 UnboundedFollowing,
1427}
1428
1429impl fmt::Display for FrameBound {
1430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1431 match self {
1432 Self::UnboundedPreceding => f.write_str("UNBOUNDED PRECEDING"),
1433 Self::OffsetPreceding(n) => write!(f, "{n} PRECEDING"),
1434 Self::CurrentRow => f.write_str("CURRENT ROW"),
1435 Self::OffsetFollowing(n) => write!(f, "{n} FOLLOWING"),
1436 Self::UnboundedFollowing => f.write_str("UNBOUNDED FOLLOWING"),
1437 }
1438 }
1439}
1440
1441#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1442pub enum ExtractField {
1443 Year,
1444 Month,
1445 Day,
1446 Hour,
1447 Minute,
1448 Second,
1449 Microsecond,
1450}
1451
1452impl fmt::Display for ExtractField {
1453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454 f.write_str(match self {
1455 Self::Year => "YEAR",
1456 Self::Month => "MONTH",
1457 Self::Day => "DAY",
1458 Self::Hour => "HOUR",
1459 Self::Minute => "MINUTE",
1460 Self::Second => "SECOND",
1461 Self::Microsecond => "MICROSECOND",
1462 })
1463 }
1464}
1465
1466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1467pub enum CastTarget {
1468 Int,
1469 BigInt,
1470 Float,
1471 Text,
1472 Bool,
1473 Vector,
1474 Date,
1475 Timestamp,
1476 /// v7.9.25 — `::INTERVAL` and `::TIMESTAMPTZ`. mailrs follow-up
1477 /// H3a. Engine reuses the existing runtime-interval / timestamp
1478 /// paths (parse the text input, return the matching Value).
1479 Interval,
1480 Timestamptz,
1481 /// v7.9.25 — `::JSON` and `::JSONB`. SPG already has both
1482 /// types (v7.9.0); the cast just routes Text→Json with the
1483 /// requested OID for the wire layer.
1484 Json,
1485 Jsonb,
1486 /// v7.9.26 — `::regtype` / `::regclass`. Parsed for PG dump
1487 /// compatibility; engine surfaces as Unsupported with a
1488 /// hint to use `SHOW TABLES` or `spg_table_ddl`. mailrs F3b.
1489 RegType,
1490 RegClass,
1491 /// v7.10.11 — `::TEXT[]`. Engine decodes the LHS Text into
1492 /// the PG external array form `{a,b,NULL}`.
1493 TextArray,
1494 /// v7.11.13 — `::INT[]` / `::BIGINT[]`. Decodes PG external
1495 /// `{1,2,3}` or widens a `TextArray` whose elements are
1496 /// integer-shaped.
1497 IntArray,
1498 BigIntArray,
1499 /// v7.12.0 — `::tsvector` / `::tsquery`. Decodes the PG
1500 /// external form text representation. Used by pg_dump output
1501 /// and by `WHERE col @@ 'term'::tsquery` literal patterns.
1502 TsVector,
1503 TsQuery,
1504}
1505
1506impl fmt::Display for CastTarget {
1507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1508 f.write_str(match self {
1509 Self::Int => "int",
1510 Self::BigInt => "bigint",
1511 Self::Float => "float",
1512 Self::Text => "text",
1513 Self::Bool => "bool",
1514 Self::Vector => "vector",
1515 Self::Interval => "interval",
1516 Self::Timestamptz => "timestamptz",
1517 Self::Json => "json",
1518 Self::Jsonb => "jsonb",
1519 Self::RegType => "regtype",
1520 Self::RegClass => "regclass",
1521 Self::Date => "date",
1522 Self::Timestamp => "timestamp",
1523 Self::TextArray => "TEXT[]",
1524 Self::IntArray => "INT[]",
1525 Self::BigIntArray => "BIGINT[]",
1526 Self::TsVector => "tsvector",
1527 Self::TsQuery => "tsquery",
1528 })
1529 }
1530}
1531
1532#[derive(Debug, Clone, PartialEq)]
1533pub enum Literal {
1534 Integer(i64),
1535 Float(f64),
1536 String(String),
1537 Bool(bool),
1538 Null,
1539 /// pgvector-style array literal, e.g. `[1, 2.5, -3]`.
1540 Vector(Vec<f32>),
1541 /// `INTERVAL '<n> <unit> [<n> <unit> ...]'` — calendar-aware span.
1542 /// Split into a months part (because a month is not a fixed number of
1543 /// days) and a microseconds part (everything sub-month). `text` keeps
1544 /// the original spelling so Display round-trips byte-for-byte.
1545 Interval {
1546 months: i32,
1547 micros: i64,
1548 text: String,
1549 },
1550}
1551
1552#[derive(Debug, Clone, PartialEq, Eq)]
1553pub struct ColumnName {
1554 pub qualifier: Option<String>,
1555 pub name: String,
1556}
1557
1558#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1559pub enum BinOp {
1560 Or,
1561 And,
1562 Eq,
1563 NotEq,
1564 /// v7.9.27b — PG `a IS DISTINCT FROM b` / `a IS NOT DISTINCT
1565 /// FROM b`. NULL-safe equality: NULL IS NOT DISTINCT FROM
1566 /// NULL → true, NULL IS DISTINCT FROM NULL → false. The
1567 /// non-NULL behaviour matches `<>` / `=` exactly. Common in
1568 /// PG-style JOIN ON predicates and pg_dump output.
1569 IsDistinctFrom,
1570 IsNotDistinctFrom,
1571 Lt,
1572 LtEq,
1573 Gt,
1574 GtEq,
1575 Add,
1576 Sub,
1577 Mul,
1578 Div,
1579 /// pgvector L2 (Euclidean) distance `<->`. Defined for two vector
1580 /// operands of equal dimension; engine returns `Value::Float(d)`.
1581 L2Distance,
1582 /// pgvector inner-product `<#>` — returns `-Σ aᵢ bᵢ` so "smaller =
1583 /// more similar" remains true (matches pgvector's published convention).
1584 InnerProduct,
1585 /// pgvector cosine distance `<=>` — `1 - (a·b)/(|a| |b|)`.
1586 CosineDistance,
1587 /// SQL string concatenation `||`. NULL propagates.
1588 Concat,
1589 /// v4.14 `json -> key` — element access by string key (object)
1590 /// or integer index (array). Returns a JSON value.
1591 JsonGet,
1592 /// v4.14 `json ->> key` — same access, returns the result as
1593 /// TEXT (unwraps a top-level JSON string; renders other scalars
1594 /// as their canonical text).
1595 JsonGetText,
1596 /// v6.4.5 `json #> path_text` — walk the path encoded as a PG
1597 /// text array literal like `'{a,0,b}'`. Returns JSON.
1598 JsonGetPath,
1599 /// v6.4.5 `json #>> path_text` — same walk, returns TEXT.
1600 JsonGetPathText,
1601 /// v6.4.5 `json @> sub_json` — containment. Returns BOOL; true
1602 /// when every key/value in `sub_json` is structurally present in
1603 /// the left side. Matches PG semantics (top-level + recursive).
1604 JsonContains,
1605 /// v7.12.2 `tsvector @@ tsquery` — FTS match. Returns BOOL;
1606 /// 3VL on NULL. Symmetric: PG also accepts `tsquery @@
1607 /// tsvector` and engine eval normalises either ordering.
1608 TsMatch,
1609}
1610
1611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1612pub enum UnOp {
1613 Not,
1614 Neg,
1615}
1616
1617// --- Display impls (round-trip-safe) --------------------------------------
1618
1619impl fmt::Display for Statement {
1620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1621 match self {
1622 Self::Empty => Ok(()),
1623 Self::DropTable { names, if_exists } => {
1624 f.write_str("DROP TABLE ")?;
1625 if *if_exists {
1626 f.write_str("IF EXISTS ")?;
1627 }
1628 for (i, n) in names.iter().enumerate() {
1629 if i > 0 {
1630 f.write_str(", ")?;
1631 }
1632 write!(f, "{}", quote_ident(n))?;
1633 }
1634 Ok(())
1635 }
1636 Self::DropIndex { name, if_exists } => {
1637 f.write_str("DROP INDEX ")?;
1638 if *if_exists {
1639 f.write_str("IF EXISTS ")?;
1640 }
1641 write!(f, "{}", quote_ident(name))
1642 }
1643 Self::Select(s) => s.fmt(f),
1644 Self::CreateTable(s) => s.fmt(f),
1645 Self::CreateIndex(s) => s.fmt(f),
1646 Self::Insert(s) => s.fmt(f),
1647 Self::Update(s) => s.fmt(f),
1648 Self::Delete(s) => s.fmt(f),
1649 Self::Begin => f.write_str("BEGIN"),
1650 Self::Commit => f.write_str("COMMIT"),
1651 Self::Rollback => f.write_str("ROLLBACK"),
1652 Self::Savepoint(n) => write!(f, "SAVEPOINT {}", quote_ident(n)),
1653 Self::RollbackToSavepoint(n) => write!(f, "ROLLBACK TO SAVEPOINT {}", quote_ident(n)),
1654 Self::ReleaseSavepoint(n) => write!(f, "RELEASE SAVEPOINT {}", quote_ident(n)),
1655 Self::ShowTables => f.write_str("SHOW TABLES"),
1656 Self::ShowColumns(t) => write!(f, "SHOW COLUMNS FROM {}", quote_ident(t)),
1657 Self::CreateUser(s) => write!(
1658 f,
1659 "CREATE USER {} WITH PASSWORD '<redacted>' ROLE '{}'",
1660 quote_ident(&s.name),
1661 s.role
1662 ),
1663 Self::DropUser(n) => write!(f, "DROP USER {}", quote_ident(n)),
1664 Self::ShowUsers => f.write_str("SHOW USERS"),
1665 Self::ShowPublications => f.write_str("SHOW PUBLICATIONS"),
1666 Self::ShowSubscriptions => f.write_str("SHOW SUBSCRIPTIONS"),
1667 Self::CreateSubscription(s) => {
1668 write!(
1669 f,
1670 "CREATE SUBSCRIPTION {} CONNECTION '{}' PUBLICATION ",
1671 quote_ident(&s.name),
1672 s.conn_str.replace('\'', "''")
1673 )?;
1674 for (i, p) in s.publications.iter().enumerate() {
1675 if i > 0 {
1676 f.write_str(", ")?;
1677 }
1678 write!(f, "{}", quote_ident(p))?;
1679 }
1680 Ok(())
1681 }
1682 Self::DropSubscription(name) => {
1683 write!(f, "DROP SUBSCRIPTION {}", quote_ident(name))
1684 }
1685 Self::WaitForWalPosition { pos, timeout_ms } => {
1686 write!(f, "WAIT FOR WAL POSITION {pos}")?;
1687 if let Some(ms) = timeout_ms {
1688 write!(f, " WITH TIMEOUT {ms}")?;
1689 }
1690 Ok(())
1691 }
1692 Self::Analyze(None) => f.write_str("ANALYZE"),
1693 Self::Analyze(Some(t)) => write!(f, "ANALYZE {}", quote_ident(t)),
1694 Self::CompactColdSegments => f.write_str("COMPACT COLD SEGMENTS"),
1695 Self::Explain(e) => {
1696 if e.suggest {
1697 write!(f, "EXPLAIN (SUGGEST) {}", e.inner)
1698 } else if e.analyze {
1699 write!(f, "EXPLAIN ANALYZE {}", e.inner)
1700 } else {
1701 write!(f, "EXPLAIN {}", e.inner)
1702 }
1703 }
1704 Self::AlterIndex(a) => {
1705 write!(f, "ALTER INDEX {} ", quote_ident(&a.name))?;
1706 match a.target {
1707 AlterIndexTarget::Rebuild { encoding } => {
1708 f.write_str("REBUILD")?;
1709 if let Some(enc) = encoding {
1710 write!(f, " WITH (encoding = {enc})")?;
1711 }
1712 Ok(())
1713 }
1714 }
1715 }
1716 Self::AlterTable(a) => {
1717 write!(f, "ALTER TABLE {} ", quote_ident(&a.name))?;
1718 for (i, t) in a.targets.iter().enumerate() {
1719 if i > 0 {
1720 f.write_str(", ")?;
1721 }
1722 fmt_alter_target(f, t)?;
1723 }
1724 Ok(())
1725 }
1726 Self::CreatePublication(p) => {
1727 write!(f, "CREATE PUBLICATION {}", quote_ident(&p.name))?;
1728 match &p.scope {
1729 PublicationScope::AllTables => f.write_str(" FOR ALL TABLES"),
1730 PublicationScope::ForTables(ts) => {
1731 f.write_str(" FOR TABLE ")?;
1732 for (i, t) in ts.iter().enumerate() {
1733 if i > 0 {
1734 f.write_str(", ")?;
1735 }
1736 write!(f, "{}", quote_ident(t))?;
1737 }
1738 Ok(())
1739 }
1740 PublicationScope::AllTablesExcept(ts) => {
1741 f.write_str(" FOR ALL TABLES EXCEPT ")?;
1742 for (i, t) in ts.iter().enumerate() {
1743 if i > 0 {
1744 f.write_str(", ")?;
1745 }
1746 write!(f, "{}", quote_ident(t))?;
1747 }
1748 Ok(())
1749 }
1750 }
1751 }
1752 Self::CreateExtension(name) => {
1753 write!(f, "CREATE EXTENSION IF NOT EXISTS {}", quote_ident(name))
1754 }
1755 Self::DoBlock => f.write_str("DO $$ /* SPG no-op */ $$"),
1756 Self::DropPublication(name) => {
1757 write!(f, "DROP PUBLICATION {}", quote_ident(name))
1758 }
1759 Self::SetParameter { name, value } => {
1760 write!(f, "SET {name} = ")?;
1761 match value {
1762 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''")),
1763 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s),
1764 SetValue::Default => f.write_str("DEFAULT"),
1765 }
1766 }
1767 Self::SetParameterList(pairs) => {
1768 f.write_str("SET ")?;
1769 for (i, (name, value)) in pairs.iter().enumerate() {
1770 if i > 0 {
1771 f.write_str(", ")?;
1772 }
1773 write!(f, "{name} = ")?;
1774 match value {
1775 SetValue::String(s) => write!(f, "'{}'", s.replace('\'', "''"))?,
1776 SetValue::Ident(s) | SetValue::Number(s) => f.write_str(s)?,
1777 SetValue::Default => f.write_str("DEFAULT")?,
1778 }
1779 }
1780 Ok(())
1781 }
1782 Self::ResetParameter(None) => f.write_str("RESET ALL"),
1783 Self::ResetParameter(Some(name)) => write!(f, "RESET {name}"),
1784 Self::CreateFunction(s) => s.fmt(f),
1785 Self::CreateTrigger(s) => s.fmt(f),
1786 Self::DropTrigger {
1787 name,
1788 table,
1789 if_exists,
1790 } => {
1791 f.write_str("DROP TRIGGER ")?;
1792 if *if_exists {
1793 f.write_str("IF EXISTS ")?;
1794 }
1795 write!(f, "{} ON {}", quote_ident(name), quote_ident(table))
1796 }
1797 Self::DropFunction { name, if_exists } => {
1798 f.write_str("DROP FUNCTION ")?;
1799 if *if_exists {
1800 f.write_str("IF EXISTS ")?;
1801 }
1802 write!(f, "{}", quote_ident(name))
1803 }
1804 }
1805 }
1806}
1807
1808impl fmt::Display for CreateFunctionStatement {
1809 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1810 f.write_str("CREATE ")?;
1811 if self.or_replace {
1812 f.write_str("OR REPLACE ")?;
1813 }
1814 write!(f, "FUNCTION {}(", quote_ident(&self.name))?;
1815 for (i, arg) in self.args.iter().enumerate() {
1816 if i > 0 {
1817 f.write_str(", ")?;
1818 }
1819 match arg.mode {
1820 FunctionArgMode::In => {}
1821 FunctionArgMode::Out => f.write_str("OUT ")?,
1822 FunctionArgMode::InOut => f.write_str("INOUT ")?,
1823 }
1824 if let Some(name) = &arg.name {
1825 write!(f, "{} ", quote_ident(name))?;
1826 }
1827 match &arg.ty {
1828 FunctionArgType::Typed(t) => write!(f, "{t}")?,
1829 FunctionArgType::Raw(s) => f.write_str(s)?,
1830 }
1831 }
1832 f.write_str(") RETURNS ")?;
1833 match &self.returns {
1834 FunctionReturn::Trigger => f.write_str("TRIGGER")?,
1835 FunctionReturn::Void => f.write_str("VOID")?,
1836 FunctionReturn::Type(t) => write!(f, "{t}")?,
1837 FunctionReturn::Other(s) => f.write_str(s)?,
1838 }
1839 write!(f, " LANGUAGE {} AS $$", self.language)?;
1840 match &self.body {
1841 FunctionBody::PlPgSql(b) => write!(f, "\n{b}\n")?,
1842 FunctionBody::Raw(s) => f.write_str(s)?,
1843 }
1844 f.write_str("$$")
1845 }
1846}
1847
1848impl fmt::Display for PlPgSqlBlock {
1849 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1850 if !self.declarations.is_empty() {
1851 f.write_str("DECLARE\n")?;
1852 for d in &self.declarations {
1853 write!(f, " {} ", quote_ident(&d.name))?;
1854 match &d.ty {
1855 FunctionArgType::Typed(t) => write!(f, "{t}")?,
1856 FunctionArgType::Raw(s) => f.write_str(s)?,
1857 }
1858 if let Some(e) = &d.default {
1859 write!(f, " := {e}")?;
1860 }
1861 f.write_str(";\n")?;
1862 }
1863 }
1864 f.write_str("BEGIN\n")?;
1865 for stmt in &self.statements {
1866 writeln!(f, " {stmt};")?;
1867 }
1868 f.write_str("END")
1869 }
1870}
1871
1872impl fmt::Display for PlPgSqlStmt {
1873 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1874 match self {
1875 Self::Assign { target, value } => write!(f, "{target} := {value}"),
1876 Self::Return(t) => match t {
1877 ReturnTarget::New => f.write_str("RETURN NEW"),
1878 ReturnTarget::Old => f.write_str("RETURN OLD"),
1879 ReturnTarget::Null => f.write_str("RETURN NULL"),
1880 ReturnTarget::Expr(e) => write!(f, "RETURN {e}"),
1881 },
1882 Self::If {
1883 branches,
1884 else_branch,
1885 } => {
1886 for (i, (cond, body)) in branches.iter().enumerate() {
1887 if i == 0 {
1888 write!(f, "IF {cond} THEN ")?;
1889 } else {
1890 write!(f, " ELSIF {cond} THEN ")?;
1891 }
1892 for (j, s) in body.iter().enumerate() {
1893 if j > 0 {
1894 f.write_str("; ")?;
1895 }
1896 write!(f, "{s}")?;
1897 }
1898 }
1899 if !else_branch.is_empty() {
1900 f.write_str(" ELSE ")?;
1901 for (j, s) in else_branch.iter().enumerate() {
1902 if j > 0 {
1903 f.write_str("; ")?;
1904 }
1905 write!(f, "{s}")?;
1906 }
1907 }
1908 f.write_str(" END IF")
1909 }
1910 Self::Raise {
1911 level,
1912 message,
1913 args,
1914 } => {
1915 let lvl = match level {
1916 RaiseLevel::Notice => "NOTICE",
1917 RaiseLevel::Warning => "WARNING",
1918 RaiseLevel::Info => "INFO",
1919 RaiseLevel::Log => "LOG",
1920 RaiseLevel::Debug => "DEBUG",
1921 RaiseLevel::Exception => "EXCEPTION",
1922 };
1923 write!(f, "RAISE {lvl} '{}'", message.replace('\'', "''"))?;
1924 for a in args {
1925 write!(f, ", {a}")?;
1926 }
1927 Ok(())
1928 }
1929 Self::EmbeddedSql(s) => write!(f, "{s}"),
1930 }
1931 }
1932}
1933
1934impl fmt::Display for AssignTarget {
1935 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1936 match self {
1937 Self::NewColumn(c) => write!(f, "NEW.{}", quote_ident(c)),
1938 Self::OldColumn(c) => write!(f, "OLD.{}", quote_ident(c)),
1939 Self::Local(n) => f.write_str(n),
1940 }
1941 }
1942}
1943
1944impl fmt::Display for CreateTriggerStatement {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 f.write_str("CREATE ")?;
1947 if self.or_replace {
1948 f.write_str("OR REPLACE ")?;
1949 }
1950 write!(f, "TRIGGER {} ", quote_ident(&self.name))?;
1951 match self.timing {
1952 TriggerTiming::Before => f.write_str("BEFORE")?,
1953 TriggerTiming::After => f.write_str("AFTER")?,
1954 TriggerTiming::InsteadOf => f.write_str("INSTEAD OF")?,
1955 }
1956 for (i, e) in self.events.iter().enumerate() {
1957 if i == 0 {
1958 f.write_str(" ")?;
1959 } else {
1960 f.write_str(" OR ")?;
1961 }
1962 match e {
1963 TriggerEvent::Insert => f.write_str("INSERT")?,
1964 TriggerEvent::Update => {
1965 f.write_str("UPDATE")?;
1966 if !self.update_columns.is_empty() {
1967 f.write_str(" OF ")?;
1968 for (j, col) in self.update_columns.iter().enumerate() {
1969 if j > 0 {
1970 f.write_str(", ")?;
1971 }
1972 f.write_str("e_ident(col))?;
1973 }
1974 }
1975 }
1976 TriggerEvent::Delete => f.write_str("DELETE")?,
1977 TriggerEvent::Truncate => f.write_str("TRUNCATE")?,
1978 }
1979 }
1980 write!(f, " ON {} FOR EACH ", quote_ident(&self.table))?;
1981 match self.for_each {
1982 TriggerForEach::Row => f.write_str("ROW")?,
1983 TriggerForEach::Statement => f.write_str("STATEMENT")?,
1984 }
1985 write!(f, " EXECUTE FUNCTION {}()", quote_ident(&self.function))
1986 }
1987}
1988
1989impl fmt::Display for CreateIndexStatement {
1990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1991 if self.is_unique {
1992 f.write_str("CREATE UNIQUE INDEX ")?;
1993 } else {
1994 f.write_str("CREATE INDEX ")?;
1995 }
1996 if self.if_not_exists {
1997 f.write_str("IF NOT EXISTS ")?;
1998 }
1999 write!(
2000 f,
2001 "{} ON {} ",
2002 quote_ident(&self.name),
2003 quote_ident(&self.table)
2004 )?;
2005 match self.method {
2006 IndexMethod::Hnsw => f.write_str("USING hnsw ")?,
2007 IndexMethod::Brin => f.write_str("USING brin ")?,
2008 IndexMethod::Gin => f.write_str("USING gin ")?,
2009 IndexMethod::BTree => {}
2010 }
2011 if let Some(expr) = &self.expression {
2012 write!(f, "({})", expr)?;
2013 } else if self.extra_columns.is_empty() {
2014 write!(f, "({})", quote_ident(&self.column))?;
2015 } else {
2016 // v7.9.14 — multi-column key. Emit each column quoted
2017 // so the round-tripped form re-parses to identical AST.
2018 f.write_str("(")?;
2019 write!(f, "{}", quote_ident(&self.column))?;
2020 for c in &self.extra_columns {
2021 write!(f, ", {}", quote_ident(c))?;
2022 }
2023 f.write_str(")")?;
2024 }
2025 if !self.included_columns.is_empty() {
2026 f.write_str(" INCLUDE (")?;
2027 for (i, c) in self.included_columns.iter().enumerate() {
2028 if i > 0 {
2029 f.write_str(", ")?;
2030 }
2031 write!(f, "{}", quote_ident(c))?;
2032 }
2033 f.write_str(")")?;
2034 }
2035 if let Some(pred) = &self.partial_predicate {
2036 write!(f, " WHERE {}", pred)?;
2037 }
2038 Ok(())
2039 }
2040}
2041
2042impl fmt::Display for CreateTableStatement {
2043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2044 f.write_str("CREATE TABLE ")?;
2045 if self.if_not_exists {
2046 f.write_str("IF NOT EXISTS ")?;
2047 }
2048 write!(f, "{} (", quote_ident(&self.name))?;
2049 for (i, col) in self.columns.iter().enumerate() {
2050 if i > 0 {
2051 f.write_str(", ")?;
2052 }
2053 write!(f, "{col}")?;
2054 }
2055 // v7.6.0 — render FK constraints in table-level form, after
2056 // the column list. WAL replay round-trips through Display, so
2057 // every FK must serialise here for replay to reconstruct the
2058 // schema bit-for-bit.
2059 for fk in &self.foreign_keys {
2060 f.write_str(", ")?;
2061 write!(f, "{fk}")?;
2062 }
2063 // v7.13.0 — render table-level constraints (PRIMARY KEY /
2064 // UNIQUE / CHECK) so WAL replay reconstructs them. Inline
2065 // column-level UNIQUE / CHECK get lifted to this list at
2066 // parse time, so emitting only here avoids double-counting.
2067 for tc in &self.table_constraints {
2068 f.write_str(", ")?;
2069 write!(f, "{tc}")?;
2070 }
2071 f.write_str(")")
2072 }
2073}
2074
2075fn fmt_alter_target(f: &mut fmt::Formatter<'_>, t: &AlterTableTarget) -> fmt::Result {
2076 match t {
2077 AlterTableTarget::SetHotTierBytes(n) => {
2078 write!(f, "SET hot_tier_bytes = {n}")
2079 }
2080 AlterTableTarget::AddForeignKey(fk) => write!(f, "ADD {fk}"),
2081 AlterTableTarget::DropForeignKey { name, if_exists } => {
2082 f.write_str("DROP CONSTRAINT ")?;
2083 if *if_exists {
2084 f.write_str("IF EXISTS ")?;
2085 }
2086 write!(f, "{}", quote_ident(name))
2087 }
2088 AlterTableTarget::AddColumn {
2089 column,
2090 if_not_exists,
2091 } => {
2092 f.write_str("ADD COLUMN ")?;
2093 if *if_not_exists {
2094 f.write_str("IF NOT EXISTS ")?;
2095 }
2096 write!(f, "{} {}", quote_ident(&column.name), column.ty)?;
2097 if !column.nullable {
2098 f.write_str(" NOT NULL")?;
2099 }
2100 if let Some(d) = &column.default {
2101 write!(f, " DEFAULT {d}")?;
2102 }
2103 if column.auto_increment {
2104 f.write_str(" AUTO_INCREMENT")?;
2105 }
2106 if column.is_primary_key {
2107 f.write_str(" PRIMARY KEY")?;
2108 }
2109 Ok(())
2110 }
2111 AlterTableTarget::AlterColumnType {
2112 column,
2113 new_type,
2114 using,
2115 } => {
2116 write!(f, "ALTER COLUMN {} TYPE {new_type}", quote_ident(column))?;
2117 if let Some(u) = using {
2118 write!(f, " USING {u}")?;
2119 }
2120 Ok(())
2121 }
2122 AlterTableTarget::DropColumn {
2123 column,
2124 if_exists,
2125 cascade,
2126 } => {
2127 f.write_str("DROP COLUMN ")?;
2128 if *if_exists {
2129 f.write_str("IF EXISTS ")?;
2130 }
2131 write!(f, "{}", quote_ident(column))?;
2132 if *cascade {
2133 f.write_str(" CASCADE")?;
2134 }
2135 Ok(())
2136 }
2137 AlterTableTarget::AddTableConstraint(tc) => {
2138 write!(f, "ADD {tc}")
2139 }
2140 }
2141}
2142
2143impl fmt::Display for TableConstraint {
2144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2145 match self {
2146 Self::PrimaryKey { name, columns } => {
2147 if let Some(n) = name {
2148 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
2149 }
2150 f.write_str("PRIMARY KEY (")?;
2151 for (i, c) in columns.iter().enumerate() {
2152 if i > 0 {
2153 f.write_str(", ")?;
2154 }
2155 f.write_str("e_ident(c))?;
2156 }
2157 f.write_str(")")
2158 }
2159 Self::Unique {
2160 name,
2161 columns,
2162 nulls_not_distinct,
2163 } => {
2164 if let Some(n) = name {
2165 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
2166 }
2167 f.write_str("UNIQUE ")?;
2168 if *nulls_not_distinct {
2169 f.write_str("NULLS NOT DISTINCT ")?;
2170 }
2171 f.write_str("(")?;
2172 for (i, c) in columns.iter().enumerate() {
2173 if i > 0 {
2174 f.write_str(", ")?;
2175 }
2176 f.write_str("e_ident(c))?;
2177 }
2178 f.write_str(")")
2179 }
2180 Self::Check { name, expr } => {
2181 if let Some(n) = name {
2182 write!(f, "CONSTRAINT {} ", quote_ident(n))?;
2183 }
2184 write!(f, "CHECK ({expr})")
2185 }
2186 }
2187 }
2188}
2189
2190impl fmt::Display for ForeignKeyConstraint {
2191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2192 if let Some(name) = &self.name {
2193 write!(f, "CONSTRAINT {} ", quote_ident(name))?;
2194 }
2195 f.write_str("FOREIGN KEY (")?;
2196 for (i, c) in self.columns.iter().enumerate() {
2197 if i > 0 {
2198 f.write_str(", ")?;
2199 }
2200 f.write_str("e_ident(c))?;
2201 }
2202 write!(f, ") REFERENCES {}", quote_ident(&self.parent_table))?;
2203 if !self.parent_columns.is_empty() {
2204 f.write_str(" (")?;
2205 for (i, c) in self.parent_columns.iter().enumerate() {
2206 if i > 0 {
2207 f.write_str(", ")?;
2208 }
2209 f.write_str("e_ident(c))?;
2210 }
2211 f.write_str(")")?;
2212 }
2213 // Only render non-default actions to keep Display output
2214 // close to user input. SPG's default is RESTRICT (matches
2215 // SQL spec).
2216 if self.on_delete != FkAction::Restrict {
2217 write!(f, " ON DELETE {}", self.on_delete)?;
2218 }
2219 if self.on_update != FkAction::Restrict {
2220 write!(f, " ON UPDATE {}", self.on_update)?;
2221 }
2222 Ok(())
2223 }
2224}
2225
2226impl fmt::Display for FkAction {
2227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2228 match self {
2229 Self::Restrict => f.write_str("RESTRICT"),
2230 Self::Cascade => f.write_str("CASCADE"),
2231 Self::SetNull => f.write_str("SET NULL"),
2232 Self::SetDefault => f.write_str("SET DEFAULT"),
2233 Self::NoAction => f.write_str("NO ACTION"),
2234 }
2235 }
2236}
2237
2238impl fmt::Display for ColumnDef {
2239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2240 write!(f, "{} {}", quote_ident(&self.name), self.ty)?;
2241 if let Some(d) = &self.default {
2242 write!(f, " DEFAULT {d}")?;
2243 }
2244 if self.auto_increment {
2245 f.write_str(" AUTO_INCREMENT")?;
2246 }
2247 if !self.nullable {
2248 f.write_str(" NOT NULL")?;
2249 }
2250 Ok(())
2251 }
2252}
2253
2254impl fmt::Display for InsertStatement {
2255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2256 write!(f, "INSERT INTO {}", quote_ident(&self.table))?;
2257 if let Some(cols) = &self.columns {
2258 f.write_str(" (")?;
2259 for (i, c) in cols.iter().enumerate() {
2260 if i > 0 {
2261 f.write_str(", ")?;
2262 }
2263 f.write_str("e_ident(c))?;
2264 }
2265 f.write_str(")")?;
2266 }
2267 // v7.13.0 — INSERT…SELECT renders as `... SELECT …`,
2268 // skipping the VALUES list (mailrs round-5 G4).
2269 if let Some(sel) = &self.select_source {
2270 write!(f, " {sel}")?;
2271 } else {
2272 f.write_str(" VALUES ")?;
2273 for (ri, row) in self.rows.iter().enumerate() {
2274 if ri > 0 {
2275 f.write_str(", ")?;
2276 }
2277 f.write_str("(")?;
2278 for (i, v) in row.iter().enumerate() {
2279 if i > 0 {
2280 f.write_str(", ")?;
2281 }
2282 write!(f, "{v}")?;
2283 }
2284 f.write_str(")")?;
2285 }
2286 }
2287 Ok(())
2288 }
2289}
2290
2291impl fmt::Display for UpdateStatement {
2292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2293 write!(f, "UPDATE {} SET ", quote_ident(&self.table))?;
2294 for (i, (col, expr)) in self.assignments.iter().enumerate() {
2295 if i > 0 {
2296 f.write_str(", ")?;
2297 }
2298 write!(f, "{} = {expr}", quote_ident(col))?;
2299 }
2300 if let Some(w) = &self.where_ {
2301 write!(f, " WHERE {w}")?;
2302 }
2303 Ok(())
2304 }
2305}
2306
2307impl fmt::Display for DeleteStatement {
2308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2309 write!(f, "DELETE FROM {}", quote_ident(&self.table))?;
2310 if let Some(w) = &self.where_ {
2311 write!(f, " WHERE {w}")?;
2312 }
2313 Ok(())
2314 }
2315}
2316
2317impl fmt::Display for SelectStatement {
2318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2319 write_bare_select(self, f)?;
2320 for (kind, peer) in &self.unions {
2321 f.write_str(match kind {
2322 UnionKind::Distinct => " UNION ",
2323 UnionKind::All => " UNION ALL ",
2324 })?;
2325 write_bare_select(peer, f)?;
2326 }
2327 if !self.order_by.is_empty() {
2328 f.write_str(" ORDER BY ")?;
2329 for (i, o) in self.order_by.iter().enumerate() {
2330 if i > 0 {
2331 f.write_str(", ")?;
2332 }
2333 write!(f, "{}", o.expr)?;
2334 if o.desc {
2335 f.write_str(" DESC")?;
2336 }
2337 }
2338 }
2339 if let Some(n) = &self.limit {
2340 write!(f, " LIMIT {n}")?;
2341 }
2342 if let Some(o) = &self.offset {
2343 write!(f, " OFFSET {o}")?;
2344 }
2345 Ok(())
2346 }
2347}
2348
2349fn write_bare_select(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2350 f.write_str("SELECT ")?;
2351 if s.distinct {
2352 f.write_str("DISTINCT ")?;
2353 }
2354 write_bare_select_body(s, f)
2355}
2356
2357fn write_bare_select_body(s: &SelectStatement, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2358 for (i, item) in s.items.iter().enumerate() {
2359 if i > 0 {
2360 f.write_str(", ")?;
2361 }
2362 write!(f, "{item}")?;
2363 }
2364 if let Some(t) = &s.from {
2365 write!(f, " FROM {t}")?;
2366 }
2367 if let Some(e) = &s.where_ {
2368 write!(f, " WHERE {e}")?;
2369 }
2370 if let Some(gs) = &s.group_by {
2371 f.write_str(" GROUP BY ")?;
2372 for (i, g) in gs.iter().enumerate() {
2373 if i > 0 {
2374 f.write_str(", ")?;
2375 }
2376 write!(f, "{g}")?;
2377 }
2378 }
2379 if let Some(h) = &s.having {
2380 write!(f, " HAVING {h}")?;
2381 }
2382 Ok(())
2383}
2384
2385impl fmt::Display for SelectItem {
2386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2387 match self {
2388 Self::Wildcard => f.write_str("*"),
2389 Self::Expr { expr, alias } => {
2390 write!(f, "{expr}")?;
2391 if let Some(a) = alias {
2392 write!(f, " AS {}", quote_ident(a))?;
2393 }
2394 Ok(())
2395 }
2396 }
2397 }
2398}
2399
2400impl fmt::Display for FromClause {
2401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2402 write!(f, "{}", self.primary)?;
2403 for j in &self.joins {
2404 match j.kind {
2405 JoinKind::Inner => write!(f, " INNER JOIN {}", j.table)?,
2406 JoinKind::Left => write!(f, " LEFT JOIN {}", j.table)?,
2407 JoinKind::Cross => write!(f, " CROSS JOIN {}", j.table)?,
2408 }
2409 if let Some(on) = &j.on {
2410 write!(f, " ON {on}")?;
2411 }
2412 }
2413 Ok(())
2414 }
2415}
2416
2417impl fmt::Display for TableRef {
2418 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2419 write!(f, "{}", quote_ident(&self.name))?;
2420 if let Some(a) = &self.alias {
2421 write!(f, " AS {}", quote_ident(a))?;
2422 }
2423 Ok(())
2424 }
2425}
2426
2427impl fmt::Display for ColumnName {
2428 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2429 if let Some(q) = &self.qualifier {
2430 write!(f, "{}.{}", quote_ident(q), quote_ident(&self.name))
2431 } else {
2432 write!(f, "{}", quote_ident(&self.name))
2433 }
2434 }
2435}
2436
2437impl fmt::Display for Expr {
2438 #[allow(clippy::too_many_lines)]
2439 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2440 match self {
2441 Self::Literal(l) => write!(f, "{l}"),
2442 Self::Column(c) => write!(f, "{c}"),
2443 Self::Placeholder(n) => write!(f, "${n}"),
2444 Self::Binary { lhs, op, rhs } => write!(f, "({lhs} {op} {rhs})"),
2445 Self::Unary { op, expr } => match op {
2446 UnOp::Not => write!(f, "(NOT {expr})"),
2447 UnOp::Neg => write!(f, "(-{expr})"),
2448 },
2449 Self::Cast { expr, target } => write!(f, "({expr}::{target})"),
2450 Self::IsNull { expr, negated } => {
2451 if *negated {
2452 write!(f, "({expr} IS NOT NULL)")
2453 } else {
2454 write!(f, "({expr} IS NULL)")
2455 }
2456 }
2457 Self::FunctionCall { name, args } => {
2458 write!(f, "{name}(")?;
2459 for (i, a) in args.iter().enumerate() {
2460 if i > 0 {
2461 f.write_str(", ")?;
2462 }
2463 write!(f, "{a}")?;
2464 }
2465 f.write_str(")")
2466 }
2467 Self::Like {
2468 expr,
2469 pattern,
2470 negated,
2471 } => {
2472 if *negated {
2473 write!(f, "({expr} NOT LIKE {pattern})")
2474 } else {
2475 write!(f, "({expr} LIKE {pattern})")
2476 }
2477 }
2478 Self::Extract { field, source } => write!(f, "EXTRACT({field} FROM {source})"),
2479 Self::WindowFunction {
2480 name,
2481 args,
2482 partition_by,
2483 order_by,
2484 frame,
2485 null_treatment: _,
2486 } => {
2487 write!(f, "{name}(")?;
2488 for (i, a) in args.iter().enumerate() {
2489 if i > 0 {
2490 f.write_str(", ")?;
2491 }
2492 write!(f, "{a}")?;
2493 }
2494 f.write_str(") OVER (")?;
2495 if !partition_by.is_empty() {
2496 f.write_str("PARTITION BY ")?;
2497 for (i, p) in partition_by.iter().enumerate() {
2498 if i > 0 {
2499 f.write_str(", ")?;
2500 }
2501 write!(f, "{p}")?;
2502 }
2503 }
2504 if !order_by.is_empty() {
2505 if !partition_by.is_empty() {
2506 f.write_str(" ")?;
2507 }
2508 f.write_str("ORDER BY ")?;
2509 for (i, (e, desc)) in order_by.iter().enumerate() {
2510 if i > 0 {
2511 f.write_str(", ")?;
2512 }
2513 write!(f, "{e}")?;
2514 if *desc {
2515 f.write_str(" DESC")?;
2516 }
2517 }
2518 }
2519 if let Some(fr) = frame {
2520 if !partition_by.is_empty() || !order_by.is_empty() {
2521 f.write_str(" ")?;
2522 }
2523 let k = match fr.kind {
2524 FrameKind::Rows => "ROWS",
2525 FrameKind::Range => "RANGE",
2526 };
2527 if let Some(end) = &fr.end {
2528 write!(f, "{k} BETWEEN {} AND {}", fr.start, end)?;
2529 } else {
2530 write!(f, "{k} {}", fr.start)?;
2531 }
2532 }
2533 f.write_str(")")
2534 }
2535 Self::ScalarSubquery(s) => write!(f, "({s})"),
2536 Self::Exists { subquery, negated } => {
2537 if *negated {
2538 write!(f, "NOT EXISTS ({subquery})")
2539 } else {
2540 write!(f, "EXISTS ({subquery})")
2541 }
2542 }
2543 Self::InSubquery {
2544 expr,
2545 subquery,
2546 negated,
2547 } => {
2548 if *negated {
2549 write!(f, "({expr} NOT IN ({subquery}))")
2550 } else {
2551 write!(f, "({expr} IN ({subquery}))")
2552 }
2553 }
2554 Self::Array(items) => {
2555 f.write_str("ARRAY[")?;
2556 for (i, e) in items.iter().enumerate() {
2557 if i > 0 {
2558 f.write_str(", ")?;
2559 }
2560 write!(f, "{e}")?;
2561 }
2562 f.write_str("]")
2563 }
2564 Self::ArraySubscript { target, index } => write!(f, "({target}[{index}])"),
2565 Self::AnyAll {
2566 expr,
2567 op,
2568 array,
2569 is_any,
2570 } => {
2571 let kw = if *is_any { "ANY" } else { "ALL" };
2572 write!(f, "({expr} {op} {kw}({array}))")
2573 }
2574 Self::Case {
2575 operand,
2576 branches,
2577 else_branch,
2578 } => {
2579 f.write_str("CASE")?;
2580 if let Some(op) = operand {
2581 write!(f, " {op}")?;
2582 }
2583 for (w, t) in branches {
2584 write!(f, " WHEN {w} THEN {t}")?;
2585 }
2586 if let Some(e) = else_branch {
2587 write!(f, " ELSE {e}")?;
2588 }
2589 f.write_str(" END")
2590 }
2591 }
2592 }
2593}
2594
2595impl fmt::Display for Literal {
2596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2597 match self {
2598 Self::Integer(n) => write!(f, "{n}"),
2599 Self::Float(x) => {
2600 let s = format!("{x}");
2601 // Default Display for an integral f64 (e.g. 1.0) emits "1",
2602 // which would round-trip back to Integer. Force a dot.
2603 if s.contains('.') || s.contains('e') || s.contains('E') {
2604 f.write_str(&s)
2605 } else {
2606 write!(f, "{s}.0")
2607 }
2608 }
2609 Self::String(s) => {
2610 f.write_str("'")?;
2611 for c in s.chars() {
2612 if c == '\'' {
2613 f.write_str("''")?;
2614 } else {
2615 write!(f, "{c}")?;
2616 }
2617 }
2618 f.write_str("'")
2619 }
2620 Self::Bool(b) => f.write_str(if *b { "TRUE" } else { "FALSE" }),
2621 Self::Null => f.write_str("NULL"),
2622 Self::Vector(v) => {
2623 f.write_str("[")?;
2624 for (i, x) in v.iter().enumerate() {
2625 if i > 0 {
2626 f.write_str(", ")?;
2627 }
2628 let s = format!("{x}");
2629 // Mirror Float Display: force a dot so re-parse stays
2630 // numerically literal.
2631 if s.contains('.') || s.contains('e') || s.contains('E') {
2632 f.write_str(&s)?;
2633 } else {
2634 write!(f, "{s}.0")?;
2635 }
2636 }
2637 f.write_str("]")
2638 }
2639 Self::Interval { text, .. } => {
2640 f.write_str("INTERVAL '")?;
2641 for c in text.chars() {
2642 if c == '\'' {
2643 f.write_str("''")?;
2644 } else {
2645 write!(f, "{c}")?;
2646 }
2647 }
2648 f.write_str("'")
2649 }
2650 }
2651 }
2652}
2653
2654impl fmt::Display for BinOp {
2655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2656 f.write_str(match self {
2657 Self::Or => "OR",
2658 Self::And => "AND",
2659 Self::Eq => "=",
2660 Self::NotEq => "<>",
2661 Self::IsDistinctFrom => "IS DISTINCT FROM",
2662 Self::IsNotDistinctFrom => "IS NOT DISTINCT FROM",
2663 Self::Lt => "<",
2664 Self::LtEq => "<=",
2665 Self::Gt => ">",
2666 Self::GtEq => ">=",
2667 Self::Add => "+",
2668 Self::Sub => "-",
2669 Self::Mul => "*",
2670 Self::Div => "/",
2671 Self::L2Distance => "<->",
2672 Self::InnerProduct => "<#>",
2673 Self::CosineDistance => "<=>",
2674 Self::Concat => "||",
2675 Self::JsonGet => "->",
2676 Self::JsonGetText => "->>",
2677 Self::JsonGetPath => "#>",
2678 Self::JsonGetPathText => "#>>",
2679 Self::JsonContains => "@>",
2680 Self::TsMatch => "@@",
2681 })
2682 }
2683}
2684
2685/// Quote `s` as a PG double-quoted identifier when required (keyword,
2686/// non-folded case, leading digit, embedded non-`[A-Za-z0-9_]`, empty).
2687/// Otherwise return it as-is. Returns an owned `String` to keep the call site
2688/// uniform.
2689fn quote_ident(s: &str) -> String {
2690 let needs_quote = match s.chars().next() {
2691 None => true,
2692 Some(c) if !c.is_ascii_alphabetic() && c != '_' => true,
2693 _ => {
2694 s.chars().any(|c| !(c.is_ascii_alphanumeric() || c == '_'))
2695 || s.chars().any(|c| c.is_ascii_uppercase())
2696 || is_keyword(s)
2697 }
2698 };
2699 if !needs_quote {
2700 return s.to_string();
2701 }
2702 let mut out = String::with_capacity(s.len() + 2);
2703 out.push('"');
2704 for c in s.chars() {
2705 if c == '"' {
2706 out.push_str("\"\"");
2707 } else {
2708 out.push(c);
2709 }
2710 }
2711 out.push('"');
2712 out
2713}
2714
2715fn is_keyword(s: &str) -> bool {
2716 matches!(
2717 &*s.to_ascii_lowercase(),
2718 "select"
2719 | "from"
2720 | "where"
2721 | "as"
2722 | "null"
2723 | "true"
2724 | "false"
2725 | "and"
2726 | "or"
2727 | "not"
2728 | "create"
2729 | "table"
2730 | "insert"
2731 | "into"
2732 | "values"
2733 | "index"
2734 | "on"
2735 | "begin"
2736 | "commit"
2737 | "rollback"
2738 | "is"
2739 | "between"
2740 | "in"
2741 | "like"
2742 | "group"
2743 | "distinct"
2744 | "union"
2745 | "all"
2746 | "join"
2747 | "inner"
2748 | "left"
2749 | "cross"
2750 | "outer"
2751 | "default"
2752 | "savepoint"
2753 | "release"
2754 | "to"
2755 | "having"
2756 | "show"
2757 | "extract"
2758 | "offset"
2759 | "asc"
2760 | "desc"
2761 | "interval"
2762 )
2763}
2764
2765#[cfg(test)]
2766mod tests {
2767 use super::*;
2768 use alloc::vec;
2769
2770 #[test]
2771 fn integer_literal_renders_without_dot() {
2772 assert_eq!(Literal::Integer(42).to_string(), "42");
2773 }
2774
2775 #[test]
2776 fn integral_float_keeps_dot() {
2777 assert_eq!(Literal::Float(1.0).to_string(), "1.0");
2778 assert_eq!(Literal::Float(1.5).to_string(), "1.5");
2779 assert_eq!(Literal::Float(2.5e-3).to_string(), "0.0025");
2780 }
2781
2782 #[test]
2783 fn string_literal_doubles_quote() {
2784 assert_eq!(Literal::String("it's".into()).to_string(), "'it''s'");
2785 }
2786
2787 #[test]
2788 fn bool_and_null_render_uppercase() {
2789 assert_eq!(Literal::Bool(true).to_string(), "TRUE");
2790 assert_eq!(Literal::Bool(false).to_string(), "FALSE");
2791 assert_eq!(Literal::Null.to_string(), "NULL");
2792 }
2793
2794 #[test]
2795 fn binary_op_always_parenthesised() {
2796 let e = Expr::Binary {
2797 lhs: Box::new(Expr::Literal(Literal::Integer(1))),
2798 op: BinOp::Add,
2799 rhs: Box::new(Expr::Literal(Literal::Integer(2))),
2800 };
2801 assert_eq!(e.to_string(), "(1 + 2)");
2802 }
2803
2804 #[test]
2805 fn select_star_from_table() {
2806 let s = SelectStatement {
2807 items: vec![SelectItem::Wildcard],
2808 from: Some(FromClause {
2809 primary: TableRef {
2810 name: "users".into(),
2811 alias: None,
2812 as_of_segment: None,
2813 unnest_expr: None,
2814 unnest_column_aliases: Vec::new(),
2815 },
2816 joins: vec![],
2817 }),
2818 where_: None,
2819 group_by: None,
2820 group_by_all: false,
2821 having: None,
2822 unions: vec![],
2823 order_by: Vec::new(),
2824 limit: None,
2825 offset: None,
2826 distinct: false,
2827 ctes: vec![],
2828 };
2829 assert_eq!(s.to_string(), "SELECT * FROM users");
2830 }
2831
2832 #[test]
2833 fn quote_ident_for_uppercase_and_keyword() {
2834 assert_eq!(quote_ident("foo"), "foo");
2835 assert_eq!(quote_ident("Foo"), "\"Foo\"");
2836 assert_eq!(quote_ident("select"), "\"select\"");
2837 assert_eq!(quote_ident(""), "\"\"");
2838 assert_eq!(quote_ident("a\"b"), "\"a\"\"b\"");
2839 }
2840}