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 builtin_permissions(
184        &self,
185    ) -> Option<Arc<dyn uqa_sql::catalog::security::builtin_routines::BuiltinRoutineExecution>>
186    {
187        Some(Arc::new(uqa_execution::catalog::security::builtin_routines::execution::BuiltinRoutinePermissions::capture(&self.catalog_execution())))
188    }
189    fn statistics(&self) -> StatementStatisticsContext<'_> {
190        self.statement_statistics_context()
191    }
192    fn rule_inputs(&self) -> RuleInputPlanningContext<'_> {
193        self.rule_input_planning_context()
194    }
195    fn routine_inlining(&self) -> Option<uqa_sql::routines::inlining::RoutineInliningContext<'_>> {
196        let compilation = self.routine_definition_context().compilation.analysis;
197        Some(uqa_sql::routines::inlining::RoutineInliningContext {
198            routines: compilation.routines,
199            types: compilation.types,
200            parsers: compilation.parsers,
201            catalog: compilation.catalog,
202            relations: compilation.relations,
203            authority: self,
204            volatility: self,
205            expressions: self,
206        })
207    }
208}
209
210pub(crate) fn estimate_engine_plan(
211    engine: &Engine,
212    plan: &uqa_planner::UnifiedPlan,
213) -> Result<uqa_planner::plan_cost::PlanCost, SQLError> {
214    uqa_planner::statement_planning::estimate_plan(engine.statement_statistics_context(), plan)
215}
216
217pub(crate) fn optimize_engine_query(
218    engine: &Engine,
219    query: &uqa_planner::QueryPlan,
220) -> Result<uqa_planner::QueryPlan, SQLError> {
221    uqa_planner::statement_planning::executable::optimize_query(
222        &engine.statement_planning_context(),
223        query,
224    )
225}
226
227pub(crate) fn optimize_engine_plan(
228    engine: &Engine,
229    plan: uqa_planner::UnifiedPlan,
230) -> Result<uqa_planner::UnifiedPlan, SQLError> {
231    uqa_planner::statement_planning::executable::optimize_plan(
232        &engine.statement_planning_context(),
233        plan,
234    )
235}
236
237impl uqa_sql::routines::inlining::RoutinePlanExpressions for Engine {
238    fn evaluate_constant_routine(
239        &self,
240        expression: &ScalarExpr,
241    ) -> Result<uqa_core::Value, SQLError> {
242        uqa_execution::query::catalog_expression::eval_expression_plan_with_schema(
243            self,
244            crate::capabilities::query_scope::new_for_current_routine(self),
245            uqa_sql::plan::ExpressionPlan {
246                scalar: expression.clone(),
247                subqueries: Vec::new(),
248            },
249            &uqa_sql::ResultRow::new(),
250            &uqa_sql::RowSchema::default(),
251            &[],
252        )
253    }
254}