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