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