Skip to main content

uqa_execution/query/cte/
context.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Child-query execution, output rewrites, and expression services for CTEs.
8
9use crate::{
10    query::{output::QueryOutput, runtime::QueryRuntimeView, CteScope},
11    OwnedPhysicalRow,
12};
13use uqa_sql::{
14    expr::EngineHook,
15    plan::{CommandPlan, QueryPlan},
16    routines::RoutineResolution,
17    SQLError, SQLParam, ScalarExpr,
18};
19
20pub trait CteBodyExecutor<S: Clone>: Sync {
21    /// Retain the active query allowance and its original cancellation owner for CTE analysis and scheduling.
22    fn read_control(&self) -> Result<uqa_storage::read_control::StorageReadControl, SQLError>;
23    /// Retain one read-only physical producer and its selected session inputs. A semantic materialization that cannot expose a pull operator returns None.
24    fn retained_query(
25        &self,
26        query: &QueryPlan,
27        params: &[SQLParam],
28        ctes: &CteScope<S>,
29    ) -> Result<Option<Box<dyn crate::PhysicalOperator>>, SQLError>;
30    fn execute_query(
31        &self,
32        query: &QueryPlan,
33        params: &[SQLParam],
34        ctes: &mut CteScope<S>,
35    ) -> Result<QueryOutput, SQLError>;
36    fn execute_lateral_query(
37        &self,
38        query: &QueryPlan,
39        outer: &OwnedPhysicalRow,
40        params: &[SQLParam],
41        ctes: &CteScope<S>,
42    ) -> Result<QueryOutput, SQLError>;
43    fn execute_command(
44        &self,
45        command: &CommandPlan,
46        params: &[SQLParam],
47        ctes: &CteScope<S>,
48    ) -> Result<crate::mutation::output::MutationOutput, SQLError>;
49    /// Fire the AFTER events that the commands of a statement queued, once the statement has finished.
50    fn fire_after_triggers(
51        &self,
52        queue: &crate::mutation::triggers::queue::AfterTriggerQueue,
53    ) -> Result<(), SQLError>;
54}
55
56pub trait QueryOutputRewriter: Sync {
57    /// Consume the private catalog-query destination before assembling its streaming or materialized execution path. The caller has already restored layouts and applied its output demand.
58    fn optimize_retained_query(
59        &self,
60        query: uqa_sql::plan::MutableQueryPlan,
61        control: &uqa_core::memory::ProductionControl<'_>,
62    ) -> Result<uqa_sql::plan::OwnedQueryPlan, SQLError>;
63
64    fn prune_owned_query_outputs(
65        &self,
66        query: uqa_sql::plan::MutableQueryPlan,
67        aliases: &[String],
68        projection: &uqa_sql::plan::source_projection::SourceProjection,
69        schema: &crate::RowSchema,
70        visible_ctes: &dyn Fn(&str) -> bool,
71        control: &uqa_core::memory::ProductionControl<'_>,
72    ) -> Result<uqa_sql::plan::MutableQueryPlan, SQLError>;
73
74    /// Return a plan that applies the complete output predicate, or `None` when the caller must retain it.
75    fn push_output_filter(
76        &self,
77        query: &QueryPlan,
78        qualifier: &str,
79        filter: &ScalarExpr,
80        output_columns: Option<&[String]>,
81    ) -> Result<Option<uqa_sql::plan::OwnedQueryPlan>, SQLError>;
82
83    /// Place a predicate inside an ordinary derived source. Recursive specialization keeps its separate effect boundary through `push_output_filter`.
84    fn push_derived_output_filter(
85        &self,
86        query: &QueryPlan,
87        qualifier: &str,
88        filter: &ScalarExpr,
89        output_columns: Option<&[String]>,
90    ) -> Result<Option<uqa_sql::plan::OwnedQueryPlan>, SQLError> {
91        self.push_output_filter(query, qualifier, filter, output_columns)
92    }
93}
94
95#[derive(Clone)]
96pub struct CteExecutionContext<'a, S: Clone> {
97    pub queries: &'a dyn CteBodyExecutor<S>,
98    pub rewrites: &'a dyn QueryOutputRewriter,
99    pub routines: &'a dyn RoutineResolution,
100    pub functions: &'a (dyn EngineHook + Sync),
101    pub runtime: QueryRuntimeView<'a>,
102}
103impl<S: Clone> Copy for CteExecutionContext<'_, S> {}
104
105impl<S: Clone> CteExecutionContext<'_, S> {
106    /// Retain the original query allowance and both cancellation owners for private execution inputs.
107    pub fn production_resources(
108        &self,
109    ) -> Result<uqa_core::memory::OwnedProductionControl, SQLError> {
110        let retained = self.queries.read_control()?;
111        Ok(uqa_core::memory::ProductionControl::new(
112            retained.memory(),
113            retained.cancellation(),
114            self.runtime.cancellation,
115        )
116        .capture())
117    }
118}