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