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    fn execute_query(
22        &self,
23        query: &QueryPlan,
24        params: &[SQLParam],
25        ctes: &mut CteScope<S>,
26    ) -> Result<QueryOutput, SQLError>;
27    fn execute_lateral_query(
28        &self,
29        query: &QueryPlan,
30        outer: &OwnedPhysicalRow,
31        params: &[SQLParam],
32        ctes: &CteScope<S>,
33    ) -> Result<QueryOutput, SQLError>;
34    fn execute_command(
35        &self,
36        command: &CommandPlan,
37        params: &[SQLParam],
38        ctes: &CteScope<S>,
39    ) -> Result<crate::mutation::output::MutationOutput, SQLError>;
40    /// Fire the AFTER events that the commands of a statement queued, once the statement has finished.
41    fn fire_after_triggers(
42        &self,
43        queue: &crate::mutation::triggers::queue::AfterTriggerQueue,
44    ) -> Result<(), SQLError>;
45}
46
47pub trait QueryOutputRewriter: Sync {
48    /// Remove scalar output expressions the containing query does not need, preserving the stored row descriptor and side effects.
49    fn prune_query_outputs(
50        &self,
51        query: &mut QueryPlan,
52        aliases: &[String],
53        projection: &uqa_sql::plan::source_projection::SourceProjection,
54        schema: &crate::RowSchema,
55    );
56
57    /// Optimize a catalog-retained query before assembling either its streaming or materialized execution path.
58    fn optimize_retained_query(&self, query: &QueryPlan) -> Result<QueryPlan, SQLError>;
59
60    /// Return a plan that applies the complete output predicate, or `None` when the caller must retain it.
61    fn push_output_filter(
62        &self,
63        query: &QueryPlan,
64        qualifier: &str,
65        filter: &ScalarExpr,
66        output_columns: Option<&[String]>,
67    ) -> Result<Option<QueryPlan>, SQLError>;
68}
69
70#[derive(Clone)]
71pub struct CteExecutionContext<'a, S: Clone> {
72    pub queries: &'a dyn CteBodyExecutor<S>,
73    pub rewrites: &'a dyn QueryOutputRewriter,
74    pub routines: &'a dyn RoutineResolution,
75    pub functions: &'a (dyn EngineHook + Sync),
76    pub runtime: QueryRuntimeView<'a>,
77}
78impl<S: Clone> Copy for CteExecutionContext<'_, S> {}