Skip to main content

uqa_sql/plan/
model.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Serializable relational, command, source, and scalar plan data model.
8
9use super::{NullsOrder, ScalarExpr, SetOpKind};
10use crate::catalog::roles::RoleReference;
11
12const fn default_include_descendants() -> bool {
13    true
14}
15
16/// One fully lowered SQL statement.
17///
18/// There is deliberately no `Legacy`, `Opaque`, or raw-`Statement` variant:
19/// adding a SQL statement kind must update the exhaustive lowerer and the
20/// physical driver.
21#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
22pub enum UnifiedPlan {
23    Query(Box<QueryPlan>),
24    Command(Box<CommandPlan>),
25}
26
27/// A relational query with its CTE scope and one relational root.
28#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
29pub struct QueryPlan {
30    /// Whether relation references in this tree are stored catalog identities rather than names that must be resolved in the executing session.
31    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
32    pub relations_bound: bool,
33    pub ctes: Vec<CtePlan>,
34    pub root: RelationalPlan,
35}
36
37/// A named query child owned by a [`QueryPlan`].
38#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
39pub struct CtePlan {
40    pub name: String,
41    pub columns: Vec<String>,
42    pub recursive: bool,
43    #[serde(default)]
44    pub materialization: crate::ast::CteMaterialization,
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub search: Option<CteSearchPlan>,
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub cycle: Option<CteCyclePlan>,
49    #[serde(flatten)]
50    pub body: CtePlanBody,
51}
52
53/// A relational CTE or a command whose RETURNING relation feeds its consumers.
54#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
55pub enum CtePlanBody {
56    #[serde(rename = "query")]
57    Query(Box<QueryPlan>),
58    #[serde(rename = "command")]
59    Command(Box<CommandPlan>),
60}
61
62impl CtePlanBody {
63    pub fn query(&self) -> Option<&QueryPlan> {
64        match self {
65            Self::Query(query) => Some(query),
66            Self::Command(_) => None,
67        }
68    }
69
70    pub fn query_mut(&mut self) -> Option<&mut QueryPlan> {
71        match self {
72            Self::Query(query) => Some(query),
73            Self::Command(_) => None,
74        }
75    }
76
77    pub const fn modifies_data(&self) -> bool {
78        matches!(self, Self::Command(_))
79    }
80
81    /// Whether this WITH definition exposes a relation to its consumers.
82    pub fn returns_rows(&self) -> bool {
83        match self {
84            Self::Query(_) => true,
85            Self::Command(command) => command
86                .returning()
87                .is_some_and(|returning| !returning.is_empty()),
88        }
89    }
90
91    pub fn into_plan(self) -> UnifiedPlan {
92        match self {
93            Self::Query(query) => UnifiedPlan::Query(query),
94            Self::Command(command) => UnifiedPlan::Command(command),
95        }
96    }
97}
98
99impl From<UnifiedPlan> for CtePlanBody {
100    fn from(plan: UnifiedPlan) -> Self {
101        match plan {
102            UnifiedPlan::Query(query) => Self::Query(query),
103            UnifiedPlan::Command(command) => Self::Command(command),
104        }
105    }
106}
107
108/// Generated traversal-order column for a recursive CTE.
109#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
110pub struct CteSearchPlan {
111    pub columns: Vec<String>,
112    pub breadth_first: bool,
113    pub sequence_column: String,
114}
115
116/// Generated cycle mark and path columns for a recursive CTE.
117#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
118pub struct CteCyclePlan {
119    pub columns: Vec<String>,
120    pub mark_column: String,
121    pub mark_value: ScalarExpr,
122    pub mark_default: ScalarExpr,
123    pub path_column: String,
124}
125
126/// Relational nodes common to ordinary SQL, retrieval SQL, and table/graph
127/// functions.
128#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
129pub enum RelationalPlan {
130    /// A single SELECT query block. Its source is a separate plan tree and its
131    /// compute phase is classified as projection, aggregation, or windowing.
132    QueryBlock(Box<QueryBlockPlan>),
133    /// SQL set operations own both input plans; combined ordering and slicing
134    /// are properties of the set node rather than either branch.
135    SetOp {
136        kind: SetOpKind,
137        all: bool,
138        left: Box<QueryPlan>,
139        right: Box<QueryPlan>,
140        order_by: Vec<OrderPlan>,
141        limit: Option<Box<ScalarExpr>>,
142        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143        with_ties: bool,
144        offset: Option<Box<ScalarExpr>>,
145        subqueries: Vec<QueryPlan>,
146    },
147    /// Standalone `VALUES`, used both as a statement and as a relational
148    /// source. Each cell remains an expression so parameters/functions bind at
149    /// execution time.
150    Values {
151        rows: Vec<Vec<ScalarExpr>>,
152        subqueries: Vec<QueryPlan>,
153    },
154}
155
156/// One SELECT block after `WITH` and set-operation structure has been pulled
157/// into explicit parent/child nodes.
158#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
159pub struct QueryBlockPlan {
160    /// The canonical owners of window inputs; calls keep resolved execution copies.
161    #[serde(default, skip_serializing_if = "Vec::is_empty")]
162    pub windows: Vec<crate::ast::WindowDefinition<crate::ir::ScalarWindowSpec>>,
163    pub projections: Vec<ProjectionPlan>,
164    /// Analyzed column reads retained when unused outputs are removed. These names authorize access but never evaluate the discarded values.
165    #[serde(default, skip_serializing_if = "std::collections::BTreeSet::is_empty")]
166    pub privilege_columns: std::collections::BTreeSet<crate::ColumnIdentity>,
167    pub from: Option<SourcePlan>,
168    pub r#where: Option<ScalarExpr>,
169    pub compute: ComputePlan,
170    pub group_by: Vec<ScalarExpr>,
171    pub grouping_sets: Vec<Vec<ScalarExpr>>,
172    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
173    pub group_distinct: bool,
174    pub having: Option<ScalarExpr>,
175    pub order_by: Vec<OrderPlan>,
176    pub limit: Option<ScalarExpr>,
177    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
178    pub with_ties: bool,
179    pub offset: Option<ScalarExpr>,
180    pub distinct: bool,
181    pub distinct_on: Vec<ScalarExpr>,
182    pub subqueries: Vec<QueryPlan>,
183    pub access: AccessPathPlan,
184    /// `FOR UPDATE` / `FOR SHARE` clauses belonging to this query block.
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub locking: Vec<crate::ast::LockingClause>,
187}
188
189/// Cross-paradigm access decision made after the relational and scalar
190/// portions of a query block have both been lowered.
191#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
192pub enum AccessPathPlan {
193    /// Ordinary row-source execution.
194    Row,
195    /// Use the shared document-support/operator algebra for the block predicate.
196    OperatorTree {
197        /// The relational ORDER BY/OFFSET/LIMIT can be pushed into the
198        /// retrieval function before row materialization.
199        score_limit_pushdown: bool,
200    },
201    /// Split a mixed predicate into posting-list candidates followed by
202    /// row-level residual evaluation.
203    Hybrid,
204}
205
206/// Physical strategy selected for a relational join.
207///
208/// `Auto` is used for an unreordered SQL join and lets physical lowering pick
209/// hash execution for a splittable equality predicate or nested-loop execution
210/// otherwise. `Hash` is an optimizer commitment produced by `DPccp` and must be
211/// executable; physical lowering reports an internal planning error if that
212/// invariant is violated.
213#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
214pub enum JoinExecutionStrategy {
215    #[default]
216    Auto,
217    Hash,
218}
219
220/// One independently resolved and bound function inside a range-function group.
221#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
222pub struct TableFunctionPlan {
223    pub name: String,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub binding: Option<crate::ast::FunctionBinding>,
226    #[serde(default)]
227    pub output_name: String,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub relations: Option<crate::ast::OperatorJoinRelations>,
230    pub args: Vec<ScalarExpr>,
231    pub column_aliases: Vec<String>,
232    pub column_types: Vec<String>,
233}
234
235/// The row-producing source below a query block.
236#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
237pub enum SourcePlan {
238    /// Execution-scoped rows; never persisted as stored syntax or a reusable catalog plan.
239    #[serde(skip)]
240    #[doc(hidden)]
241    RetainedRows(crate::ast::RetainedRowSource),
242    Table {
243        name: String,
244        /// The statement's prepared view or folded CTE. Stored syntax never retains an execution-specific projection or folded value.
245        #[serde(skip)]
246        executable_query: Option<Box<QueryPlan>>,
247        #[serde(default)]
248        qualifier: String,
249        alias: Option<String>,
250        #[serde(default, skip_serializing_if = "Vec::is_empty")]
251        column_aliases: Vec<String>,
252        #[serde(default, skip_serializing_if = "Option::is_none")]
253        bound_columns: Option<Vec<String>>,
254        #[serde(default = "default_include_descendants")]
255        include_descendants: bool,
256    },
257    Join {
258        left: Box<SourcePlan>,
259        right: Box<SourcePlan>,
260        kind: crate::ast::JoinKind,
261        on: Option<ScalarExpr>,
262        #[serde(default, skip_serializing_if = "Option::is_none")]
263        using: Option<crate::ast::JoinUsing>,
264        #[serde(default)]
265        natural: bool,
266        #[serde(default, skip_serializing_if = "Option::is_none")]
267        alias: Option<String>,
268        #[serde(default, skip_serializing_if = "Vec::is_empty")]
269        column_aliases: Vec<String>,
270        lateral: bool,
271        #[serde(default)]
272        strategy: JoinExecutionStrategy,
273    },
274    Values {
275        rows: Vec<Vec<ScalarExpr>>,
276        alias: Option<String>,
277        column_aliases: Vec<String>,
278        #[serde(default, skip_serializing_if = "Option::is_none")]
279        internal_relation: Option<crate::ast::InternalRelationId>,
280        #[serde(default, skip_serializing_if = "Vec::is_empty")]
281        internal_column_types: Vec<Option<crate::ast::ColumnType>>,
282        #[serde(default, skip_serializing_if = "Vec::is_empty")]
283        internal_column_collations: Vec<Option<u32>>,
284    },
285    Function {
286        name: String,
287        #[serde(default, skip_serializing_if = "Option::is_none")]
288        binding: Option<crate::ast::FunctionBinding>,
289        #[serde(default)]
290        output_name: String,
291        #[serde(default, skip_serializing_if = "Option::is_none")]
292        relations: Option<crate::ast::OperatorJoinRelations>,
293        args: Vec<ScalarExpr>,
294        alias: Option<String>,
295        column_aliases: Vec<String>,
296        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
297        ordinality: bool,
298        column_types: Vec<String>,
299    },
300    FunctionGroup {
301        functions: Vec<TableFunctionPlan>,
302        alias: Option<String>,
303        column_aliases: Vec<String>,
304        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
305        ordinality: bool,
306    },
307    Subquery {
308        body: Box<QueryPlan>,
309        alias: Option<String>,
310        column_aliases: Vec<String>,
311    },
312}
313
314/// The SELECT-list phase chosen during lowering.
315#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
316pub enum ComputePlan {
317    Project,
318    Aggregate,
319    Window,
320}
321
322#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
323pub struct ProjectionPlan {
324    pub expr: ScalarExpr,
325    pub alias: Option<String>,
326}
327
328#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
329pub struct OrderPlan {
330    pub expr: ScalarExpr,
331    pub descending: bool,
332    pub nulls: Option<NullsOrder>,
333}
334
335/// Executable scalar IR plus every query-valued descendant it owns.
336#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
337pub struct ExpressionPlan {
338    pub scalar: ScalarExpr,
339    pub subqueries: Vec<QueryPlan>,
340}
341
342#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
343pub struct AssignmentPlan {
344    #[serde(rename = "column")]
345    pub target: crate::ast::AssignmentTargets<ScalarExpr>,
346    pub value: ScalarExpr,
347}
348
349impl AssignmentPlan {
350    pub fn expressions(&self) -> impl Iterator<Item = &ScalarExpr> {
351        self.target
352            .expressions()
353            .chain(std::iter::once(&self.value))
354    }
355
356    pub fn expressions_mut(&mut self) -> impl Iterator<Item = &mut ScalarExpr> {
357        self.target
358            .expressions_mut()
359            .chain(std::iter::once(&mut self.value))
360    }
361}
362
363#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
364pub struct ViewCheckPlan {
365    pub view: String,
366    pub predicate: ScalarExpr,
367}
368
369#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
370pub struct ViewRuleReturningPlan {
371    pub relation: String,
372    pub target_qualifier: String,
373    pub returning: Vec<ProjectionPlan>,
374    pub aliases: crate::ast::ReturningAliases,
375    pub subqueries: Vec<QueryPlan>,
376}
377
378#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
379pub struct ViewRuleInsertPlan {
380    pub relation: String,
381    pub supplied_columns: Vec<String>,
382    pub input_columns: Vec<String>,
383}
384
385#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
386pub struct ViewRuleUpdatePlan {
387    pub relation: String,
388    pub assigned_columns: Vec<String>,
389    pub input_columns: Vec<String>,
390}
391
392#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
393pub struct InsertPlan {
394    pub table: String,
395    pub target_relation_bound: bool,
396    /// Whether non-target relation references are stored catalog identities rather than names that must be resolved in the executing session.
397    pub relations_bound: bool,
398    /// Effective role used for non-target privilege checks in an internally rewritten statement.
399    pub statement_privilege_subject: Option<RoleReference>,
400    /// Effective role used only for privilege checks on an internally rewritten target relation.
401    pub target_privilege_subject: Option<RoleReference>,
402    pub target_qualifier: String,
403    #[serde(default)]
404    pub target_alias: Option<String>,
405    pub include_descendants: bool,
406    pub columns: Vec<crate::ast::AssignmentTarget<ScalarExpr>>,
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub overriding: Option<crate::ast::OverridingKind>,
409    pub ctes: Vec<CtePlan>,
410    pub rows: Vec<Vec<ScalarExpr>>,
411    pub source: Option<Box<QueryPlan>>,
412    pub on_conflict: Option<ConflictPlan>,
413    pub returning: Vec<ProjectionPlan>,
414    pub returning_aliases: crate::ast::ReturningAliases,
415    pub subqueries: Vec<QueryPlan>,
416    pub view_checks: Vec<ViewCheckPlan>,
417    pub view_rule_relations: Vec<String>,
418    pub view_rule_insert_plans: Vec<ViewRuleInsertPlan>,
419    pub view_rule_returning: Option<ViewRuleReturningPlan>,
420}
421
422#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
423pub struct ConflictPlan {
424    pub predicate: Option<Box<ScalarExpr>>,
425    pub constraint: Option<String>,
426    pub conflict_columns: Vec<String>,
427    pub expressions: Vec<ScalarExpr>,
428    pub action: ConflictActionPlan,
429}
430
431#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
432pub enum ConflictActionPlan {
433    Nothing,
434    Update {
435        assignments: Vec<AssignmentPlan>,
436        predicate: Option<Box<ScalarExpr>>,
437    },
438}
439
440#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
441pub struct UpdatePlan {
442    pub table: String,
443    pub target_relation_bound: bool,
444    /// Whether non-target relation references are stored catalog identities rather than names that must be resolved in the executing session.
445    pub relations_bound: bool,
446    /// Effective role used for non-target privilege checks in an internally rewritten statement.
447    pub statement_privilege_subject: Option<RoleReference>,
448    /// Effective role used only for privilege checks on an internally rewritten target relation.
449    pub target_privilege_subject: Option<RoleReference>,
450    pub target_qualifier: String,
451    #[serde(default)]
452    pub target_alias: Option<String>,
453    pub include_descendants: bool,
454    pub assignments: Vec<AssignmentPlan>,
455    pub predicate: Option<ScalarExpr>,
456    pub ctes: Vec<CtePlan>,
457    pub source: Option<Box<SourcePlan>>,
458    pub returning: Vec<ProjectionPlan>,
459    pub returning_aliases: crate::ast::ReturningAliases,
460    pub subqueries: Vec<QueryPlan>,
461    pub view_checks: Vec<ViewCheckPlan>,
462    pub view_rule_relations: Vec<String>,
463    pub view_rule_update_plans: Vec<ViewRuleUpdatePlan>,
464    pub view_rule_returning: Option<ViewRuleReturningPlan>,
465}
466
467#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
468pub struct DeletePlan {
469    pub table: String,
470    pub target_relation_bound: bool,
471    /// Whether non-target relation references are stored catalog identities rather than names that must be resolved in the executing session.
472    pub relations_bound: bool,
473    /// Effective role used for non-target privilege checks in an internally rewritten statement.
474    pub statement_privilege_subject: Option<RoleReference>,
475    /// Effective role used only for privilege checks on an internally rewritten target relation.
476    pub target_privilege_subject: Option<RoleReference>,
477    pub target_qualifier: String,
478    #[serde(default)]
479    pub target_alias: Option<String>,
480    pub include_descendants: bool,
481    pub predicate: Option<ScalarExpr>,
482    pub ctes: Vec<CtePlan>,
483    pub source: Option<Box<SourcePlan>>,
484    pub returning: Vec<ProjectionPlan>,
485    pub returning_aliases: crate::ast::ReturningAliases,
486    pub subqueries: Vec<QueryPlan>,
487    pub view_rule_relations: Vec<String>,
488    pub view_rule_returning: Option<ViewRuleReturningPlan>,
489}
490
491#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
492pub struct MergePlan {
493    #[serde(default)]
494    pub ctes: Vec<CtePlan>,
495    pub target: String,
496    /// Effective role used for non-target privilege checks in an internally rewritten statement.
497    pub statement_privilege_subject: Option<RoleReference>,
498    /// Effective role used only for privilege checks on an internally rewritten target relation.
499    pub target_privilege_subject: Option<RoleReference>,
500    pub target_qualifier: String,
501    pub target_alias: Option<String>,
502    pub include_descendants: bool,
503    pub target_predicate: Option<ScalarExpr>,
504    pub source: Box<SourcePlan>,
505    pub join_condition: ScalarExpr,
506    pub when_clauses: Vec<MergeWhenPlan>,
507    pub returning: Vec<ProjectionPlan>,
508    pub returning_aliases: crate::ast::ReturningAliases,
509    pub subqueries: Vec<QueryPlan>,
510    pub view_checks: Vec<ViewCheckPlan>,
511}
512
513#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
514pub enum MergeWhenPlan {
515    UpdateMatched {
516        condition: Option<ScalarExpr>,
517        assignments: Vec<AssignmentPlan>,
518    },
519    DeleteMatched {
520        condition: Option<ScalarExpr>,
521    },
522    UpdateNotMatchedBySource {
523        condition: Option<ScalarExpr>,
524        assignments: Vec<AssignmentPlan>,
525    },
526    DeleteNotMatchedBySource {
527        condition: Option<ScalarExpr>,
528    },
529    InsertNotMatched {
530        condition: Option<ScalarExpr>,
531        columns: Vec<crate::ast::AssignmentTarget<ScalarExpr>>,
532        #[serde(default, skip_serializing_if = "Option::is_none")]
533        overriding: Option<crate::ast::OverridingKind>,
534        values: Vec<ScalarExpr>,
535    },
536    NothingMatched {
537        condition: Option<ScalarExpr>,
538    },
539    NothingNotMatched {
540        condition: Option<ScalarExpr>,
541    },
542    NothingNotMatchedBySource {
543        condition: Option<ScalarExpr>,
544    },
545}
546
547/// Non-query statement plans. Mutations own physical sources and scalar IR;
548/// query-bearing catalog commands own explicit query children. Typed DDL and
549/// procedural payloads contain catalog data, never a second SQL dispatcher.
550#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
551pub enum CommandPlan {
552    CreateTable(Box<crate::ast::CreateTable>),
553    CreateTableIfNotExists(crate::ast::DeferredCreateTable),
554    CreateIndex(crate::ast::CreateIndex),
555    RenameIndex(crate::ast::RenameIndexStmt),
556    Insert(Box<InsertPlan>),
557    Update(Box<UpdatePlan>),
558    Delete(Box<DeletePlan>),
559    Drop(crate::ast::DropStmt),
560    AlterTable(Box<crate::ast::AlterTableStmt>),
561    AlterView(crate::ast::AlterViewStmt),
562    CreateView {
563        name: String,
564        column_names: Vec<String>,
565        query: Box<QueryPlan>,
566        or_replace: bool,
567        persistence: crate::ast::RelationPersistence,
568        options: Vec<(String, String)>,
569    },
570    CreateMaterializedView {
571        name: String,
572        column_names: Vec<String>,
573        if_not_exists: bool,
574        with_no_data: bool,
575        options: Vec<(String, String)>,
576        query: Box<QueryPlan>,
577    },
578    RefreshMaterializedView {
579        name: String,
580        concurrently: bool,
581        with_no_data: bool,
582    },
583    CreateSchema {
584        name: Option<String>,
585        if_not_exists: bool,
586        #[serde(default, skip_serializing_if = "Option::is_none")]
587        authorization: Option<crate::ast::SchemaAuthorization>,
588    },
589    AlterSchemaOwner {
590        name: String,
591        new_owner: crate::ast::RoleSpecification,
592    },
593    RenameSchema {
594        name: String,
595        new_name: String,
596    },
597    Notify {
598        channel: String,
599        payload: String,
600    },
601    Listen {
602        channel: String,
603    },
604    Unlisten {
605        channel: Option<String>,
606    },
607    SetVariable {
608        name: String,
609        value: String,
610        #[serde(default)]
611        local: bool,
612        #[serde(default)]
613        is_default: bool,
614    },
615    ResetVariable {
616        name: String,
617    },
618    ResetAllVariables,
619    SetConstraints {
620        constraints: Vec<crate::ast::SetConstraintName>,
621        deferred: bool,
622    },
623    ShowVariable {
624        name: String,
625    },
626    Discard {
627        target: crate::ast::DiscardTarget,
628    },
629    Load {
630        library: String,
631    },
632    Explain {
633        analyze: bool,
634        verbose: bool,
635        format: Option<String>,
636        body: Box<UnifiedPlan>,
637    },
638    Analyze {
639        table: Option<String>,
640    },
641    Vacuum(crate::ast::VacuumStmt),
642    LockTable(crate::ast::LockTableStmt),
643    Truncate {
644        tables: Vec<crate::ast::TruncateTarget>,
645        cascade: bool,
646        restart_identity: bool,
647    },
648    Transaction(crate::ast::TransactionStmt),
649    DeclareCursor {
650        name: String,
651        binary: bool,
652        scroll: Option<bool>,
653        hold: bool,
654        query: Box<QueryPlan>,
655    },
656    FetchCursor(crate::ast::FetchCursorStmt),
657    CloseCursor {
658        name: Option<String>,
659    },
660    CreateSequence(crate::ast::CreateSequence),
661    CreateDomain(crate::ast::CreateDomain),
662    AlterDomain(crate::ast::AlterDomain),
663    CreateShellType(String),
664    CommentType(crate::ast::CommentType),
665    CreateEnum(crate::ast::CreateEnum),
666    CreateCompositeType(crate::ast::CreateCompositeType),
667    AlterEnum(crate::ast::AlterEnum),
668    AlterTypeObject(crate::ast::AlterTypeObject),
669    GrantType(crate::ast::GrantTypeStmt),
670    AlterSequence(crate::ast::AlterSequence),
671    CreateTableAs {
672        name: String,
673        if_not_exists: bool,
674        column_names: Vec<String>,
675        with_no_data: bool,
676        /// Written as `SELECT ... INTO`, which `PostgreSQL` tags `SELECT INTO`.
677        #[serde(default)]
678        select_into: bool,
679        persistence: crate::ast::RelationPersistence,
680        on_commit: crate::ast::OnCommitAction,
681        query: Box<QueryPlan>,
682    },
683    Prepare {
684        name: String,
685        #[serde(default)]
686        parameter_types: Vec<crate::ast::ColumnType>,
687        body: Box<UnifiedPlan>,
688    },
689    Execute {
690        name: String,
691        params: Vec<ExpressionPlan>,
692    },
693    Deallocate {
694        name: Option<String>,
695    },
696    CreateForeignWrapper(crate::ast::CreateForeignWrapper),
697    CreateForeignServer(crate::ast::CreateForeignServer),
698    CreateForeignTable(crate::ast::CreateForeignTable),
699    #[serde(alias = "CreateForeignTableIfNotExists")]
700    CreateForeignTableDefinition(crate::ast::DeferredCreateForeignTable),
701    AlterForeignTable(crate::ast::AlterForeignTableStmt),
702    Merge(Box<MergePlan>),
703    CreateFunction(Box<crate::ast::CreateFunction>),
704    DropFunction(crate::ast::DropFunctionStmt),
705    AlterRoutine(crate::ast::AlterRoutineStmt),
706    AlterRoutineOwner(crate::ast::AlterRoutineOwnerStmt),
707    RenameRoutine(crate::ast::RenameRoutineStmt),
708    GrantRoutine(crate::ast::GrantRoutineStmt),
709    GrantTable(crate::ast::GrantTableStmt),
710    GrantSequence(crate::ast::GrantSequenceStmt),
711    GrantDatabase(crate::ast::GrantDatabaseStmt),
712    GrantSchema(crate::ast::GrantSchemaStmt),
713    GrantRole(crate::ast::GrantRoleStmt),
714    CreateRole(crate::ast::CreateRoleStmt),
715    AlterRole(crate::ast::AlterRoleStmt),
716    RenameRole(crate::ast::RenameRoleStmt),
717    DropRole(crate::ast::DropRoleStmt),
718    CreateTrigger(crate::ast::CreateTrigger),
719    DropTrigger(crate::ast::DropTrigger),
720    CreateRule(crate::ast::CreateRule),
721    DropRule(crate::ast::DropRule),
722    DoBlock {
723        language: String,
724        body: String,
725    },
726    Call {
727        name: String,
728        args: Vec<ExpressionPlan>,
729    },
730}
731
732/// Classification hook for engine-registered aggregate functions. Built-in
733/// aggregates are always recognised; the callback extends that set without
734/// making the planner depend on the engine.
735pub trait AggregateClassifier {
736    fn is_registered_aggregate(&self, name: &str) -> bool;
737}
738
739impl<F> AggregateClassifier for F
740where
741    F: Fn(&str) -> bool,
742{
743    fn is_registered_aggregate(&self, name: &str) -> bool {
744        self(name)
745    }
746}
747
748pub(super) struct NoRegisteredAggregates;
749
750impl AggregateClassifier for NoRegisteredAggregates {
751    fn is_registered_aggregate(&self, _name: &str) -> bool {
752        false
753    }
754}