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