Skip to main content

uqa_sql/
ast.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Internal SQL AST. Lifts the relevant subset of the `libpg_query`
8//! protobuf tree into a Rust enum the compiler walks. Statements not
9//! yet supported parse cleanly but compile to
10//! [`crate::SQLError::Unsupported`].
11
12use serde::{Deserialize, Serialize};
13
14mod acl_role_specification;
15mod array_access;
16mod assignment_target;
17mod composites;
18mod constraints;
19mod cte;
20mod domains;
21mod enum_functions;
22mod enums;
23mod events;
24mod expressions;
25mod foreign_wrappers;
26mod from;
27mod function_binding;
28mod identity_sequence;
29mod indexes;
30mod interval;
31mod legacy_dispatch;
32mod locking;
33mod namespaces;
34mod object_acl;
35mod overriding;
36mod pattern_operator;
37mod ranges;
38mod referenced_partition;
39mod relation_hierarchy;
40mod relation_lifecycle;
41mod retained_literal;
42mod retained_rows;
43pub use retained_literal::RetainedInputLiteral;
44mod role_specification;
45mod routine_attributes;
46mod routine_security;
47mod routines;
48mod sequence;
49mod sequence_declaration;
50mod table_alteration;
51mod type_lifecycle;
52mod type_privileges;
53mod types;
54
55pub use acl_role_specification::AclRoleSpecification;
56pub use array_access::{ArrayAccess, ArraySliceBounds, MAX_ARRAY_SUBSCRIPT_DIMENSIONS};
57pub use assignment_target::{AssignmentStep, AssignmentTarget, AssignmentTargets};
58pub use composites::*;
59pub use constraints::*;
60pub use cte::*;
61pub use domains::*;
62pub use enum_functions::EnumFunctionOperation;
63pub use enums::*;
64pub use events::*;
65pub use expressions::*;
66pub use foreign_wrappers::*;
67pub use from::*;
68pub use function_binding::*;
69pub use identity_sequence::{DeferredSQLError, IdentitySequenceDeclaration, IdentitySequenceName};
70pub use indexes::*;
71pub use interval::*;
72pub use locking::*;
73pub use namespaces::*;
74pub use object_acl::ObjectAclEntry;
75pub use overriding::OverridingKind;
76pub use pattern_operator::PatternOperator;
77pub use ranges::*;
78pub use referenced_partition::ReferencedPartitionConstraint;
79pub use relation_hierarchy::*;
80pub use relation_lifecycle::*;
81pub use retained_rows::RetainedRowSource;
82pub use role_specification::RoleSpecification;
83pub use routine_attributes::*;
84pub use routine_security::*;
85pub use routines::*;
86pub use sequence::*;
87pub use sequence_declaration::{SequenceDeclaration, SequenceOptionValue};
88pub use table_alteration::*;
89pub use type_lifecycle::*;
90pub use type_privileges::*;
91pub use types::*;
92
93const fn default_include_descendants() -> bool {
94    true
95}
96
97const fn default_true() -> bool {
98    true
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
102pub enum GeneratedColumnKind {
103    Virtual,
104    Stored,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct GeneratedColumn {
109    pub kind: GeneratedColumnKind,
110    pub expression: Box<Expr>,
111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
112    pub function_dependencies: Vec<GeneratedFunctionDependency>,
113}
114
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
116pub struct IndexColumnOrder {
117    pub descending: bool,
118    pub nulls_first: bool,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct CreateIndex {
123    #[serde(default)]
124    pub included_columns: Vec<String>,
125    #[serde(default)]
126    pub column_order: Vec<IndexColumnOrder>,
127    #[serde(default)]
128    pub predicate: Option<Box<Expr>>,
129    pub name: Option<String>,
130    pub table: String,
131    /// `gin`, `btree`, `ivf`, `hnsw`, `rtree`, ...
132    pub access_method: String,
133    pub columns: Vec<IndexKey>,
134    #[serde(default)]
135    pub unique: bool,
136    #[serde(default)]
137    pub nulls_not_distinct: bool,
138    /// `CREATE INDEX IF NOT EXISTS`.
139    pub if_not_exists: bool,
140    /// Storage parameters from `WITH (k = v, ...)`. Stored verbatim;
141    /// known keys (`analyzer`, `lists`, `probes`, ...)
142    /// are interpreted by the engine.
143    pub options: Vec<(String, String)>,
144    /// Explicit option namespaces retained for declaration-time validation.
145    #[serde(default, skip_serializing_if = "Vec::is_empty")]
146    pub option_namespaces: Vec<String>,
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct DropStmt {
151    pub kind: DropKind,
152    pub names: Vec<String>,
153    pub if_exists: bool,
154    pub cascade: bool,
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
158pub enum DropKind {
159    ForeignWrapper,
160    Table,
161    ForeignTable,
162    Index,
163    View,
164    MaterializedView,
165    Schema,
166    Sequence,
167    Domain,
168    /// `DROP TYPE`, which removes user-defined types of every implemented kind.
169    Type,
170    ForeignServer,
171}
172
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174pub struct InsertStmt {
175    pub table: String,
176    /// Whether `table` is a stored catalog identity rather than a name to resolve in the executing session.
177    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
178    pub target_relation_bound: bool,
179    /// SQL-visible target relation name: explicit alias, otherwise the local relation name.
180    pub target_qualifier: String,
181    /// The alias written for the target relation, which deparsing prints even when it equals the relation's name.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub target_alias: Option<String>,
184    #[serde(default = "default_include_descendants")]
185    pub include_descendants: bool,
186    pub columns: Vec<AssignmentTarget>,
187    /// `OVERRIDING SYSTEM VALUE` or `OVERRIDING USER VALUE`; `None` without the clause.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub overriding: Option<OverridingKind>,
190    /// Common table expressions defined with `WITH [RECURSIVE] ...`.
191    pub with: Vec<CTE>,
192    /// Inline `VALUES (...) (...)` rows. `DEFAULT VALUES` is represented by one empty row; the vector itself is empty only for `INSERT ... SELECT`, whose query is in `select_source`.
193    pub rows: Vec<Vec<ValueExpr>>,
194    /// Populated when the statement is `INSERT INTO t (...) SELECT ...`.
195    /// The engine materialises the inner select first and then writes
196    /// each row through the standard INSERT path.
197    pub select_source: Option<Box<SelectStmt>>,
198    /// `ON CONFLICT (...) DO ...` clause. `None` for plain
199    /// `INSERT INTO ... VALUES ...` without conflict handling.
200    pub on_conflict: Option<OnConflict>,
201    /// `RETURNING ...` projection list. Empty when absent.
202    pub returning: Vec<Projection>,
203    /// `PostgreSQL` 18 names for the old and new row images visible to
204    /// `RETURNING`. The defaults are `old` and `new`.
205    pub returning_aliases: ReturningAliases,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209pub struct ReturningAliases {
210    pub old: String,
211    pub new: String,
212    #[serde(default)]
213    pub old_explicit: bool,
214    #[serde(default)]
215    pub new_explicit: bool,
216}
217
218impl Default for ReturningAliases {
219    fn default() -> Self {
220        Self {
221            old: "old".into(),
222            new: "new".into(),
223            old_explicit: false,
224            new_explicit: false,
225        }
226    }
227}
228
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230pub struct OnConflict {
231    #[serde(default)]
232    pub predicate: Option<Box<Expr>>,
233    #[serde(default)]
234    pub constraint: Option<String>,
235    /// Conflict target columns parsed from the `ON CONFLICT (col, ...)`
236    /// list. Empty when the clause uses `ON CONFLICT DO NOTHING` with
237    /// no target.
238    pub conflict_columns: Vec<String>,
239    #[serde(default)]
240    pub expressions: Vec<Expr>,
241    pub action: OnConflictAction,
242}
243
244#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
245pub enum OnConflictAction {
246    /// `DO NOTHING` -- skip conflicting rows silently.
247    Nothing,
248    /// `DO UPDATE SET col = expr [, ...] [WHERE pred]` -- apply the
249    /// listed assignments to the existing row when the conflict
250    /// target matches.
251    Update {
252        assignments: Vec<(AssignmentTargets, Expr)>,
253        r#where: Option<Box<Expr>>,
254    },
255}
256
257#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
258pub struct SelectStmt {
259    /// Named declarations followed by deduplicated anonymous specifications, in analysis order.
260    #[serde(default, skip_serializing_if = "Vec::is_empty")]
261    pub windows: Vec<WindowDefinition>,
262    pub projections: Vec<Projection>,
263    /// Rows owned by a `VALUES` query body. `PostgreSQL` represents `VALUES`
264    /// through the same query node used for `SELECT`, so nested query bodies
265    /// such as CTEs and set-operation branches must retain them here.
266    #[serde(default, skip_serializing_if = "Vec::is_empty")]
267    pub values: Vec<Vec<Expr>>,
268    pub from: Option<FromClause>,
269    pub r#where: Option<Expr>,
270    pub group_by: Vec<Expr>,
271    /// Expanded GROUPING SETS / ROLLUP / CUBE specification. When
272    /// non-empty the executor produces one row per grouping set;
273    /// `group_by` is treated as a single grouping set in that case.
274    /// Each inner Vec lists the grouping-key expressions for that
275    /// set (an empty inner Vec means the global grand-total bucket).
276    pub grouping_sets: Vec<Vec<Expr>>,
277    /// `GROUP BY DISTINCT` -- remove duplicate grouping sets after grouping expressions have been resolved against their input types.
278    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
279    pub group_distinct: bool,
280    /// `HAVING <expr>`. Evaluated against each aggregated row and
281    /// filters out groups whose predicate is falsy. Mirrors PG's
282    /// `havingClause`.
283    pub having: Option<Expr>,
284    pub order_by: Vec<OrderBy>,
285    /// `LIMIT <expr>`. Stored as an expression so `LIMIT $1` and any
286    /// other constant-folding integer expression resolves at execute
287    /// time. `None` means no LIMIT clause was supplied.
288    pub limit: Option<Expr>,
289    /// `FETCH ... WITH TIES`. The row-count expression remains in [`Self::limit`]; this flag extends the boundary through every row whose complete `ORDER BY` key equals the last requested row.
290    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
291    pub with_ties: bool,
292    /// `OFFSET <expr>`. Same shape as [`SelectStmt::limit`].
293    pub offset: Option<Expr>,
294    /// Common table expressions defined with `WITH [RECURSIVE] ...`.
295    pub with: Vec<CTE>,
296    /// Optional set operation: `Some` for UNION / INTERSECT / EXCEPT.
297    /// Parsed statements carry both operands in [`SetOp`]; `left` remains
298    /// optional only for backward-compatible deserialization.
299    pub set_op: Option<Box<SetOp>>,
300    /// `SELECT DISTINCT` -- de-duplicate the final result rows. Set by
301    /// the compiler whenever the parsed `distinct_clause` is non-empty.
302    pub distinct: bool,
303    /// `SELECT DISTINCT ON (<expr>, ...)` keys. Empty for plain
304    /// `SELECT DISTINCT`.
305    pub distinct_on: Vec<Expr>,
306    /// `FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE }` row-locking clauses, in source order. Empty when the query does not lock rows.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub locking: Vec<LockingClause>,
309}
310
311#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
312pub struct SetOp {
313    pub kind: SetOpKind,
314    pub all: bool,
315    /// Explicit left-hand subtree. Parsed set operations are left-associative,
316    /// so a chain such as `a UNION b UNION c` carries `(a UNION b)` here
317    /// instead of flattening it back to only `a`.
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub left: Option<Box<SelectStmt>>,
320    pub right: SelectStmt,
321    /// `ORDER BY` applied to the combined `lhs <op> rhs` result.
322    /// Distinct from the LHS / RHS branches' own `ORDER BY`.
323    pub combined_order_by: Vec<OrderBy>,
324    /// `LIMIT` applied to the combined result. `None` means no
325    /// outer LIMIT clause was supplied.
326    pub combined_limit: Option<Expr>,
327    /// Whether the combined set-operation limit is `FETCH ... WITH TIES`.
328    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
329    pub combined_with_ties: bool,
330    /// `OFFSET` applied to the combined result.
331    pub combined_offset: Option<Expr>,
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
335pub enum SetOpKind {
336    Union,
337    Intersect,
338    Except,
339}
340
341/// `DISCARD` target. Mirrors `PostgreSQL`'s `DiscardMode`.
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
343pub enum DiscardTarget {
344    All,
345    Plans,
346    Sequences,
347    Temp,
348}
349
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
351pub struct UpdateStmt {
352    pub table: String,
353    /// Whether `table` is a stored catalog identity rather than a name to resolve in the executing session.
354    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
355    pub target_relation_bound: bool,
356    pub target_qualifier: String,
357    /// The alias written for the target relation, which deparsing prints even when it equals the relation's name.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub target_alias: Option<String>,
360    #[serde(default = "default_include_descendants")]
361    pub include_descendants: bool,
362    pub assignments: Vec<(AssignmentTargets, Expr)>,
363    pub r#where: Option<Expr>,
364    /// Common table expressions defined with `WITH [RECURSIVE] ...`.
365    pub with: Vec<CTE>,
366    /// `UPDATE t SET ... FROM other [JOIN ...]` -- the engine joins
367    /// the target with this clause before applying the assignments.
368    pub from: Option<FromClause>,
369    /// `RETURNING ...` projection list. Empty when absent.
370    pub returning: Vec<Projection>,
371    pub returning_aliases: ReturningAliases,
372}
373
374#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
375pub struct DeleteStmt {
376    pub table: String,
377    /// Whether `table` is a stored catalog identity rather than a name to resolve in the executing session.
378    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
379    pub target_relation_bound: bool,
380    pub target_qualifier: String,
381    /// The alias written for the target relation, which deparsing prints even when it equals the relation's name.
382    #[serde(default, skip_serializing_if = "Option::is_none")]
383    pub target_alias: Option<String>,
384    #[serde(default = "default_include_descendants")]
385    pub include_descendants: bool,
386    pub r#where: Option<Expr>,
387    /// Common table expressions defined with `WITH [RECURSIVE] ...`.
388    pub with: Vec<CTE>,
389    /// `DELETE FROM t USING other [JOIN ...]` -- the engine joins
390    /// the target with this clause and deletes target rows whose
391    /// joined image satisfies WHERE.
392    pub using: Option<FromClause>,
393    /// `RETURNING ...` projection list. Empty when absent.
394    pub returning: Vec<Projection>,
395    pub returning_aliases: ReturningAliases,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399pub struct SetConstraintName {
400    pub catalog: Option<String>,
401    pub schema: Option<String>,
402    pub name: String,
403}
404
405/// One parser-normalized `VACUUM` option. Execution validates options before rejecting transaction blocks, then resolves relation targets, matching `PostgreSQL`'s diagnostic order.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407pub struct VacuumOption {
408    pub name: String,
409    pub value: Option<VacuumOptionValue>,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
413pub enum VacuumOptionValue {
414    Boolean(bool),
415    Integer(i32),
416    String(String),
417}
418
419/// One relation (and optional ANALYZE column list) named by `VACUUM`.
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
421pub struct VacuumTarget {
422    pub catalog: Option<String>,
423    pub table: String,
424    #[serde(default = "default_include_descendants")]
425    pub include_descendants: bool,
426    #[serde(default, skip_serializing_if = "Vec::is_empty")]
427    pub columns: Vec<String>,
428}
429
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431pub struct VacuumStmt {
432    #[serde(default, skip_serializing_if = "Vec::is_empty")]
433    pub options: Vec<VacuumOption>,
434    #[serde(default, skip_serializing_if = "Vec::is_empty")]
435    pub targets: Vec<VacuumTarget>,
436}
437
438#[derive(Debug, Clone, Serialize, Deserialize)]
439pub enum Statement {
440    CreateDomain(CreateDomain),
441    AlterDomain(AlterDomain),
442    CreateShellType(String),
443    CommentType(CommentType),
444    CreateEnum(CreateEnum),
445    CreateCompositeType(CreateCompositeType),
446    AlterEnum(AlterEnum),
447    AlterTypeObject(AlterTypeObject),
448    GrantType(GrantTypeStmt),
449    CreateTable(CreateTable),
450    CreateTableIfNotExists(DeferredCreateTable),
451    CreateIndex(CreateIndex),
452    RenameIndex(RenameIndexStmt),
453    Insert(InsertStmt),
454    /// `SelectStmt` is the largest variant by far (CTEs + set-ops + n-ary
455    /// expression trees), so we box it to keep the enum's stack footprint
456    /// proportional to the smaller variants.
457    Select(Box<SelectStmt>),
458    Update(UpdateStmt),
459    Delete(DeleteStmt),
460    Drop(DropStmt),
461    AlterTable(AlterTableStmt),
462    AlterForeignTable(AlterForeignTableStmt),
463    AlterView(AlterViewStmt),
464    /// `CREATE [OR REPLACE] VIEW name [(column_name, ...)] AS SELECT ...`. The body is the underlying `SelectStmt`; views are materialised lazily on every reference (no row caching).
465    CreateView {
466        name: String,
467        #[serde(default)]
468        column_names: Vec<String>,
469        body: Box<SelectStmt>,
470        or_replace: bool,
471        #[serde(default)]
472        persistence: RelationPersistence,
473        /// Validated `PostgreSQL` view reloptions in declaration order.
474        #[serde(default, skip_serializing_if = "Vec::is_empty")]
475        options: Vec<(String, String)>,
476    },
477    /// `CREATE MATERIALIZED VIEW ... AS SELECT ... [WITH [NO] DATA]`.
478    CreateMaterializedView {
479        name: String,
480        #[serde(default)]
481        column_names: Vec<String>,
482        #[serde(default)]
483        if_not_exists: bool,
484        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
485        with_no_data: bool,
486        #[serde(default, skip_serializing_if = "Vec::is_empty")]
487        options: Vec<(String, String)>,
488        body: Box<SelectStmt>,
489    },
490    /// `REFRESH MATERIALIZED VIEW [CONCURRENTLY] name [WITH [NO] DATA]`.
491    RefreshMaterializedView {
492        name: String,
493        concurrently: bool,
494        with_no_data: bool,
495    },
496    /// `CREATE SCHEMA [IF NOT EXISTS] [name] [AUTHORIZATION role]`; an omitted name binds to the resolved owner.
497    CreateSchema {
498        name: Option<String>,
499        if_not_exists: bool,
500        #[serde(default, skip_serializing_if = "Option::is_none")]
501        authorization: Option<SchemaAuthorization>,
502    },
503    AlterSchemaOwner {
504        name: String,
505        new_owner: RoleSpecification,
506    },
507    /// `ALTER SCHEMA name RENAME TO new_name` keeps the namespace's identity and privileges under the new name; every object it holds follows.
508    RenameSchema {
509        name: String,
510        new_name: String,
511    },
512    /// `NOTIFY channel [, 'payload']` queues one asynchronous notification for delivery when the outer transaction commits.
513    Notify {
514        channel: String,
515        payload: String,
516    },
517    /// `LISTEN channel` transactionally subscribes the current SQL session.
518    Listen {
519        channel: String,
520    },
521    /// `UNLISTEN channel | *` transactionally removes one or every subscription. `None` represents `*`.
522    Unlisten {
523        channel: Option<String>,
524    },
525    /// `SET <name> [TO|=] <value>` - runtime parameter assignment.
526    /// The engine gives `search_path` resolution semantics and stores other
527    /// parameters in the logical session for subsequent `SHOW` statements.
528    SetVariable {
529        name: String,
530        value: String,
531        #[serde(default)]
532        local: bool,
533        #[serde(default)]
534        is_default: bool,
535    },
536    /// `RESET <name>` restores one runtime parameter to its session default.
537    ResetVariable {
538        name: String,
539    },
540    /// `RESET ALL` restores every resettable runtime parameter.
541    ResetAllVariables,
542    /// `SET CONSTRAINTS { ALL | name [, ...] } { DEFERRED | IMMEDIATE }`. An empty constraint list represents `ALL`; qualified names retain their SQL spelling so execution can apply schema-search semantics.
543    SetConstraints {
544        constraints: Vec<SetConstraintName>,
545        deferred: bool,
546    },
547    /// `SHOW <variable>` - return the runtime parameter as one
548    /// `(name -> value)` row.
549    ShowVariable {
550        name: String,
551    },
552    /// `DISCARD [ALL|PLANS|SEQUENCES|TEMP|TEMPORARY]` - clear session state.
553    /// The engine resets session variables, prepared statements, sequence state, and the current session's temporary relations as requested.
554    Discard {
555        target: DiscardTarget,
556    },
557    /// `LOAD 'library'` - load a shared library into the session. The
558    /// engine embeds its extension surface, so libraries it provides
559    /// natively (Apache AGE) load as no-ops and unknown libraries fail
560    /// like a missing `$libdir` file.
561    Load {
562        library: String,
563    },
564    /// `EXPLAIN ...`. Carries the inner statement so the engine can
565    /// emit the planner output.
566    Explain {
567        analyze: bool,
568        verbose: bool,
569        format: Option<String>,
570        body: Box<Statement>,
571    },
572    /// `ANALYZE [table]`. The engine refreshes per-column statistics
573    /// for cardinality estimation; the AST simply records the target.
574    Analyze {
575        table: Option<String>,
576    },
577    /// `VACUUM [options] [relations]`. Execution validates options, rejects transaction blocks, then resolves targets and dispatches storage maintenance in `PostgreSQL` order.
578    Vacuum(VacuumStmt),
579    /// `LOCK [TABLE] [ONLY] name [IN mode MODE] [NOWAIT]`.
580    LockTable(LockTableStmt),
581    /// `TRUNCATE TABLE t1, t2 ...`. Wipes the listed table hierarchies unless
582    /// a target uses `ONLY`.
583    Truncate {
584        tables: Vec<TruncateTarget>,
585        cascade: bool,
586        #[serde(default)]
587        restart_identity: bool,
588    },
589    /// `BEGIN` / `COMMIT` / `ROLLBACK` / `SAVEPOINT name`.
590    Transaction(TransactionStmt),
591    /// `DECLARE name [BINARY] [SCROLL] CURSOR [WITH HOLD] FOR query`.
592    DeclareCursor(DeclareCursorStmt),
593    /// `FETCH` or `MOVE` over a named SQL cursor.
594    FetchCursor(FetchCursorStmt),
595    /// `CLOSE name` or `CLOSE ALL`. `None` represents `ALL`.
596    CloseCursor {
597        name: Option<String>,
598    },
599    /// `CREATE SEQUENCE name [START n] [INCREMENT n]`.
600    CreateSequence(CreateSequence),
601    /// `ALTER SEQUENCE name [RESTART [WITH n]] [INCREMENT [BY] n]
602    /// [START [WITH] n]`.
603    AlterSequence(AlterSequence),
604    /// `CREATE TABLE name AS SELECT ...`.
605    CreateTableAs {
606        name: String,
607        if_not_exists: bool,
608        #[serde(default, skip_serializing_if = "Vec::is_empty")]
609        column_names: Vec<String>,
610        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
611        with_no_data: bool,
612        /// Written as `SELECT ... INTO`, which `PostgreSQL` tags `SELECT INTO`.
613        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
614        select_into: bool,
615        #[serde(default)]
616        persistence: RelationPersistence,
617        #[serde(default)]
618        on_commit: OnCommitAction,
619        body: Box<SelectStmt>,
620    },
621    /// `PREPARE name AS <inner>`.
622    Prepare {
623        name: String,
624        #[serde(default)]
625        parameter_types: Vec<ColumnType>,
626        body: Box<Statement>,
627    },
628    /// `EXECUTE name (param1, param2, ...)`.
629    Execute {
630        name: String,
631        params: Vec<Expr>,
632    },
633    /// `DEALLOCATE name | DEALLOCATE ALL`. `None` means ALL.
634    Deallocate {
635        name: Option<String>,
636    },
637    /// `SELECT * FROM (VALUES ...) [AS alias]` -- a standalone VALUES
638    /// statement (also reachable from a SET-OP body).
639    Values {
640        rows: Vec<Vec<Expr>>,
641    },
642    /// `CREATE FOREIGN DATA WRAPPER name [HANDLER ...] [VALIDATOR ...] [OPTIONS ...]`.
643    CreateForeignWrapper(CreateForeignWrapper),
644    /// `CREATE SERVER name FOREIGN DATA WRAPPER type OPTIONS (...)`.
645    CreateForeignServer(CreateForeignServer),
646    /// `CREATE FOREIGN TABLE name (...) SERVER server OPTIONS (...)`.
647    CreateForeignTable(CreateForeignTable),
648    /// A SQL foreign-table definition retains its original declaration until execution checks its creation namespace.
649    #[serde(alias = "CreateForeignTableIfNotExists")]
650    CreateForeignTableDefinition(DeferredCreateForeignTable),
651    /// `MERGE INTO target USING source ON cond WHEN MATCHED THEN ...
652    /// WHEN NOT MATCHED THEN ...`. SQL:2003 conditional UPSERT.
653    Merge(MergeStmt),
654    /// `CREATE [OR REPLACE] FUNCTION | PROCEDURE ...`. Boxed: the
655    /// definition (parameters + body source) dwarfs other variants.
656    CreateFunction(Box<CreateFunction>),
657    /// `DROP FUNCTION | PROCEDURE [IF EXISTS] name[(args)] [, ...]`.
658    DropFunction(DropFunctionStmt),
659    /// `ALTER FUNCTION | PROCEDURE | ROUTINE name[(input_types)]` volatility and null-input attributes.
660    AlterRoutine(AlterRoutineStmt),
661    AlterRoutineOwner(AlterRoutineOwnerStmt),
662    RenameRoutine(RenameRoutineStmt),
663    GrantRoutine(GrantRoutineStmt),
664    GrantTable(GrantTableStmt),
665    GrantSequence(GrantSequenceStmt),
666    GrantDatabase(GrantDatabaseStmt),
667    GrantSchema(GrantSchemaStmt),
668    GrantRole(GrantRoleStmt),
669    CreateRole(CreateRoleStmt),
670    AlterRole(AlterRoleStmt),
671    RenameRole(RenameRoleStmt),
672    DropRole(DropRoleStmt),
673    /// `CREATE [OR REPLACE] TRIGGER ... ON relation`.
674    CreateTrigger(CreateTrigger),
675    /// `DROP TRIGGER [IF EXISTS] name ON relation`.
676    DropTrigger(DropTrigger),
677    /// `CREATE [OR REPLACE] RULE ... ON relation`.
678    CreateRule(CreateRule),
679    /// `DROP RULE [IF EXISTS] name ON relation`.
680    DropRule(DropRule),
681    /// `DO [LANGUAGE lang] $$ ... $$` - anonymous code block.
682    DoBlock {
683        language: String,
684        body: String,
685    },
686    /// `CALL proc(args)` - procedure invocation. `OUT` / `INOUT`
687    /// parameters shape the result row.
688    Call {
689        name: String,
690        args: Vec<Expr>,
691    },
692}
693
694#[derive(Debug, Clone, Serialize, Deserialize)]
695pub struct TruncateTarget {
696    pub table: String,
697    #[serde(default = "default_include_descendants")]
698    pub include_descendants: bool,
699}
700
701#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
702pub struct MergeTargetColumnBinding {
703    pub object_id: [u8; 16],
704    /// Original target position for reconstructing a removed attribute's catalog name.
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    pub attribute_number: Option<i16>,
707    /// Domain identities used by non-DEFAULT assignment coercions, including after target deletion.
708    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
709    pub domain_dependencies: std::collections::BTreeSet<u32>,
710}
711
712#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
713pub struct MergeStmt {
714    #[serde(default)]
715    pub with: Vec<CTE>,
716    pub target: String,
717    pub target_qualifier: String,
718    pub target_alias: Option<String>,
719    /// Creation-bound write targets in a stored body. Removed identities retain their expressions and dependencies but receive no writes.
720    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
721    pub target_column_bindings: std::collections::BTreeMap<String, MergeTargetColumnBinding>,
722    #[serde(default = "default_include_descendants")]
723    pub include_descendants: bool,
724    pub source: FromClause,
725    pub join_condition: Expr,
726    pub when_clauses: Vec<MergeWhen>,
727    /// `MERGE ... RETURNING ...` projection list. Empty when absent.
728    pub returning: Vec<Projection>,
729    pub returning_aliases: ReturningAliases,
730}
731
732#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
733pub enum MergeWhen {
734    /// `WHEN MATCHED [AND <cond>] THEN UPDATE SET ...`.
735    UpdateMatched {
736        condition: Option<Expr>,
737        assignments: Vec<(AssignmentTargets, Expr)>,
738    },
739    /// `WHEN MATCHED [AND <cond>] THEN DELETE`.
740    DeleteMatched { condition: Option<Expr> },
741    /// `WHEN NOT MATCHED BY SOURCE [AND <cond>] THEN UPDATE SET ...`.
742    UpdateNotMatchedBySource {
743        condition: Option<Expr>,
744        assignments: Vec<(AssignmentTargets, Expr)>,
745    },
746    /// `WHEN NOT MATCHED BY SOURCE [AND <cond>] THEN DELETE`.
747    DeleteNotMatchedBySource { condition: Option<Expr> },
748    /// `WHEN NOT MATCHED [AND <cond>] THEN INSERT (cols) [OVERRIDING ...] VALUES (vals)`.
749    InsertNotMatched {
750        condition: Option<Expr>,
751        columns: Vec<AssignmentTarget>,
752        #[serde(default, skip_serializing_if = "Option::is_none")]
753        overriding: Option<OverridingKind>,
754        values: Vec<Expr>,
755    },
756    /// `WHEN MATCHED [AND <cond>] THEN DO NOTHING`.
757    NothingMatched { condition: Option<Expr> },
758    /// `WHEN NOT MATCHED [AND <cond>] THEN DO NOTHING`.
759    NothingNotMatched { condition: Option<Expr> },
760    /// `WHEN NOT MATCHED BY SOURCE [AND <cond>] THEN DO NOTHING`.
761    NothingNotMatchedBySource { condition: Option<Expr> },
762}
763
764#[derive(Debug, Clone, Serialize, Deserialize)]
765pub struct CreateForeignServer {
766    pub name: String,
767    pub fdw_type: String,
768    #[serde(default)]
769    pub server_type: Option<String>,
770    #[serde(default)]
771    pub version: Option<String>,
772    pub options: Vec<(String, String)>,
773    pub if_not_exists: bool,
774}
775
776#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct CreateForeignTable {
778    pub name: String,
779    pub server_name: String,
780    pub columns: Vec<ColumnDef>,
781    #[serde(default)]
782    pub checks: Vec<TableCheck>,
783    /// Written NOT NULL declarations, including column clauses, retained until CHECK analysis succeeds. Older lowered definitions already encode these constraints in their columns.
784    #[serde(default, skip_serializing_if = "Option::is_none")]
785    pub not_null_declarations: Option<Vec<NotNullDeclaration>>,
786    pub options: Vec<(String, String)>,
787    pub if_not_exists: bool,
788}
789
790/// A syntactically valid `CREATE FOREIGN TABLE` whose definition is analyzed after its creation namespace, skipping an existing target only when requested.
791#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
792pub struct DeferredCreateForeignTable {
793    pub name: String,
794    pub server_name: String,
795    pub definition_sql: String,
796    /// Older deferred definitions always came from `IF NOT EXISTS`.
797    #[serde(default = "default_true")]
798    pub if_not_exists: bool,
799}
800
801#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
802pub enum TransactionIsolationLevel {
803    ReadUncommitted,
804    ReadCommitted,
805    RepeatableRead,
806    Serializable,
807}
808
809impl TransactionIsolationLevel {
810    #[must_use]
811    pub const fn as_str(self) -> &'static str {
812        match self {
813            Self::ReadUncommitted => "read uncommitted",
814            Self::ReadCommitted => "read committed",
815            Self::RepeatableRead => "repeatable read",
816            Self::Serializable => "serializable",
817        }
818    }
819}
820
821#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
822pub struct TransactionCharacteristics {
823    pub isolation: Option<TransactionIsolationLevel>,
824    pub read_only: Option<bool>,
825    pub deferrable: Option<bool>,
826}
827
828#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
829pub enum TransactionStmt {
830    Begin,
831    BeginWithCharacteristics(TransactionCharacteristics),
832    Commit,
833    CommitAndChain,
834    Rollback,
835    RollbackAndChain,
836    SetCharacteristics(TransactionCharacteristics),
837    SetSessionCharacteristics(TransactionCharacteristics),
838    SetSnapshot(String),
839    Savepoint(String),
840    ReleaseSavepoint(String),
841    RollbackToSavepoint(String),
842}
843
844#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
845pub enum CursorDirection {
846    Forward,
847    Backward,
848    Absolute,
849    Relative,
850}
851
852#[derive(Debug, Clone, Serialize, Deserialize)]
853pub struct DeclareCursorStmt {
854    pub name: String,
855    pub binary: bool,
856    /// `None` lets the query determine scrollability, while `Some(true)` and `Some(false)` represent explicit `SCROLL` and `NO SCROLL`.
857    pub scroll: Option<bool>,
858    pub hold: bool,
859    pub query: Box<SelectStmt>,
860}
861
862#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
863pub struct FetchCursorStmt {
864    pub name: String,
865    pub direction: CursorDirection,
866    /// `PostgreSQL` uses `i64::MAX` for `ALL`; negative counts reverse `FORWARD` and `BACKWARD`.
867    pub count: i64,
868    pub move_only: bool,
869}
870
871#[cfg(test)]
872mod tests;