Skip to main content

uqa_engine/capabilities/
statement_planning.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Supply current catalog metadata and the configured retrieval planner to statement planning.
8use crate::Engine;
9use std::collections::BTreeMap;
10use std::sync::Arc;
11use uqa_core::catalog_index::CatalogIndexRow;
12use uqa_planner::{
13    statement_planning::{
14        rule_inputs::{RuleInputColumns, RuleInputPlanningContext},
15        PlannerStatisticsCatalog, RetrievalSourceCosting, StatementStatisticsContext,
16        StatisticsTableState,
17    },
18    ColumnStats, LocalAccessEstimate,
19};
20use uqa_sql::{ast::OperatorJoinRelations, SQLError, ScalarExpr};
21
22impl uqa_sql::plan::ExecutablePlanOptimizer for Engine {
23    fn plan_with_cached_analysis(
24        &self,
25        plan: uqa_sql::plan::UnifiedPlan,
26        params: &[uqa_sql::SQLParam],
27        cached: Option<Arc<uqa_sql::binding::statements::AnalyzedStatement>>,
28    ) -> Result<
29        (
30            uqa_sql::plan::UnifiedPlan,
31            Option<Arc<uqa_sql::binding::statements::AnalyzedStatement>>,
32        ),
33        SQLError,
34    > {
35        uqa_sql::plan::ExecutablePlanOptimizer::plan_with_cached_analysis(
36            &self.statement_planning_context(),
37            plan,
38            params,
39            cached,
40        )
41    }
42
43    fn plan_for_statement_cache(
44        &self,
45        plan: uqa_sql::plan::UnifiedPlan,
46        params: &[uqa_sql::SQLParam],
47    ) -> Result<(uqa_sql::plan::UnifiedPlan, bool), SQLError> {
48        uqa_sql::plan::ExecutablePlanOptimizer::plan_for_statement_cache(
49            &self.statement_planning_context(),
50            plan,
51            params,
52        )
53    }
54
55    fn plan_for_execution(
56        &self,
57        plan: uqa_sql::plan::UnifiedPlan,
58        params: &[uqa_sql::SQLParam],
59    ) -> Result<uqa_sql::plan::UnifiedPlan, SQLError> {
60        uqa_sql::plan::ExecutablePlanOptimizer::plan_for_execution(
61            &self.statement_planning_context(),
62            plan,
63            params,
64        )
65    }
66
67    fn plan_with_result(
68        &self,
69        plan: uqa_sql::plan::UnifiedPlan,
70        params: &[uqa_sql::SQLParam],
71    ) -> Result<
72        (
73            uqa_sql::plan::UnifiedPlan,
74            uqa_sql::binding::statements::AnalyzedResult,
75        ),
76        SQLError,
77    > {
78        uqa_sql::plan::ExecutablePlanOptimizer::plan_with_result(
79            &self.statement_planning_context(),
80            plan,
81            params,
82        )
83    }
84}
85
86impl Engine {
87    pub(crate) fn statement_statistics_context(&self) -> StatementStatisticsContext<'_> {
88        StatementStatisticsContext {
89            catalog: self,
90            volatility: self,
91            retrieval: self,
92        }
93    }
94    pub(crate) fn rule_input_planning_context(&self) -> RuleInputPlanningContext<'_> {
95        RuleInputPlanningContext {
96            rules: self,
97            views: self.view_rewrite_context(),
98            columns: self,
99        }
100    }
101}
102impl StatisticsTableState for crate::TableState {}
103
104impl PlannerStatisticsCatalog for Engine {
105    fn storage_table(&self, table: &str) -> Result<Option<Arc<dyn StatisticsTableState>>, String> {
106        self.try_table(table)
107            .map(|state| state.map(|state| state as Arc<dyn StatisticsTableState>))
108            .map_err(|error| error.to_string())
109    }
110    fn hierarchy_scan_tables(&self, table: &str) -> Result<Vec<String>, SQLError> {
111        self.query_hierarchy_scan_tables(table, true)
112    }
113    fn table_row_count(&self, table: &str) -> Result<u64, SQLError> {
114        self.table_row_estimate(table)
115    }
116    fn column_statistics(&self, table: &str) -> Result<BTreeMap<String, ColumnStats>, String> {
117        self.try_query_column_stats(table)
118            .map_err(|error| error.to_string())
119    }
120    fn resolved_table_name(&self, table: &str) -> Result<Option<String>, SQLError> {
121        self.resolve_table_name(table)
122            .map_err(|error| SQLError::Internal(error.to_string()))
123    }
124    fn catalog_indexes(&self) -> Result<Vec<CatalogIndexRow>, SQLError> {
125        self.catalog_indexes_in_execution()
126            .map_err(|error| SQLError::Internal(error.to_string()))
127    }
128}
129impl RetrievalSourceCosting for Engine {
130    fn operator_join_access(
131        &self,
132        name: &str,
133        relations: Option<&OperatorJoinRelations>,
134        args: &[ScalarExpr],
135    ) -> Result<LocalAccessEstimate, SQLError> {
136        crate::operator_tree_bridge::estimate_operator_join_table_function(
137            self,
138            name,
139            relations,
140            args,
141            &[],
142        )
143    }
144    fn local_access(
145        &self,
146        table: &str,
147        predicate: &ScalarExpr,
148    ) -> Result<Option<LocalAccessEstimate>, SQLError> {
149        crate::operator_tree_bridge::estimate_local_access(self, table, predicate, &[])
150    }
151}
152impl RuleInputColumns for Engine {
153    fn source_column_names(
154        &self,
155        table: &str,
156        relations_bound: bool,
157    ) -> Result<Option<Vec<String>>, SQLError> {
158        uqa_execution::catalog::projection::query_source_column_names(
159            &self.catalog_execution(),
160            table,
161            relations_bound,
162        )
163    }
164}
165
166impl Engine {
167    pub(crate) fn statement_planning_context(
168        &self,
169    ) -> uqa_planner::statement_planning::executable::StatementPlanningContext<'_> {
170        uqa_planner::statement_planning::executable::StatementPlanningContext {
171            analysis: uqa_sql::binding::statements::StatementAnalysisContext {
172                scopes: self,
173                routines: self,
174                aliases: self,
175            },
176            aggregates: self,
177            optimization: self,
178            constant_evaluator: uqa_execution::scalar::eval_constant_scalar,
179        }
180    }
181}
182impl uqa_planner::statement_planning::executable::StatementOptimizationContexts for Engine {
183    fn constant_storage(
184        &self,
185    ) -> Result<Option<Arc<dyn uqa_sql::ir::ConstantValueStorage>>, SQLError> {
186        let bytes =
187            uqa_execution::query::runtime::QueryMemorySettings::work_mem_bytes(&*self.session)?;
188        Ok(Some(Arc::new(
189            uqa_execution::scalar::RetainedConstants::new(bytes),
190        )))
191    }
192    fn builtin_permissions(
193        &self,
194    ) -> Option<Arc<dyn uqa_sql::catalog::security::builtin_routines::BuiltinRoutineExecution>>
195    {
196        Some(Arc::new(uqa_execution::catalog::security::builtin_routines::execution::BuiltinRoutinePermissions::capture(&self.catalog_execution())))
197    }
198    fn statistics(&self) -> StatementStatisticsContext<'_> {
199        self.statement_statistics_context()
200    }
201    fn rule_inputs(&self) -> RuleInputPlanningContext<'_> {
202        self.rule_input_planning_context()
203    }
204    fn routine_inlining(&self) -> Option<uqa_sql::routines::inlining::RoutineInliningContext<'_>> {
205        let compilation = self.routine_definition_context().compilation.analysis;
206        Some(uqa_sql::routines::inlining::RoutineInliningContext {
207            routines: compilation.routines,
208            types: compilation.types,
209            parsers: compilation.parsers,
210            catalog: compilation.catalog,
211            relations: compilation.relations,
212            authority: self,
213            volatility: self,
214            expressions: self,
215        })
216    }
217}
218
219pub(crate) fn estimate_engine_plan(
220    engine: &Engine,
221    plan: &uqa_planner::UnifiedPlan,
222) -> Result<uqa_planner::plan_cost::PlanCost, SQLError> {
223    uqa_planner::statement_planning::estimate_plan(engine.statement_statistics_context(), plan)
224}
225
226pub(crate) fn optimize_engine_query(
227    engine: &Engine,
228    query: &uqa_planner::QueryPlan,
229) -> Result<uqa_planner::QueryPlan, SQLError> {
230    uqa_planner::statement_planning::executable::optimize_query(
231        &engine.statement_planning_context(),
232        query,
233    )
234}
235
236pub(crate) fn optimize_engine_plan(
237    engine: &Engine,
238    plan: uqa_planner::UnifiedPlan,
239) -> Result<uqa_planner::UnifiedPlan, SQLError> {
240    uqa_planner::statement_planning::executable::optimize_plan(
241        &engine.statement_planning_context(),
242        plan,
243    )
244}
245
246impl uqa_sql::routines::inlining::RoutinePlanExpressions for Engine {
247    fn evaluate_constant_routine(
248        &self,
249        expression: &ScalarExpr,
250    ) -> Result<uqa_core::Value, SQLError> {
251        uqa_execution::query::catalog_expression::eval_expression_plan_with_schema(
252            self,
253            crate::capabilities::query_scope::new_for_current_routine(self),
254            uqa_sql::plan::ExpressionPlan {
255                scalar: expression.clone(),
256                subqueries: Vec::new(),
257            },
258            &uqa_sql::ResultRow::new(),
259            &uqa_sql::RowSchema::default(),
260            &[],
261        )
262    }
263}