1use 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 volatility: self,
100 }
101 }
102}
103impl StatisticsTableState for crate::TableState {}
104
105impl PlannerStatisticsCatalog for Engine {
106 fn storage_table(&self, table: &str) -> Result<Option<Arc<dyn StatisticsTableState>>, String> {
107 self.try_table(table)
108 .map(|state| state.map(|state| state as Arc<dyn StatisticsTableState>))
109 .map_err(|error| error.to_string())
110 }
111 fn hierarchy_scan_tables(&self, table: &str) -> Result<Vec<String>, SQLError> {
112 self.query_hierarchy_scan_tables(table, true)
113 }
114 fn table_row_count(&self, table: &str) -> Result<u64, SQLError> {
115 self.table_row_estimate(table)
116 }
117 fn column_statistics(&self, table: &str) -> Result<BTreeMap<String, ColumnStats>, String> {
118 self.try_query_column_stats(table)
119 .map_err(|error| error.to_string())
120 }
121 fn resolved_table_name(&self, table: &str) -> Result<Option<String>, SQLError> {
122 self.resolve_table_name(table)
123 .map_err(|error| SQLError::Internal(error.to_string()))
124 }
125 fn catalog_indexes(&self) -> Result<Vec<CatalogIndexRow>, SQLError> {
126 self.catalog_indexes_in_execution()
127 .map_err(|error| SQLError::Internal(error.to_string()))
128 }
129}
130impl RetrievalSourceCosting for Engine {
131 fn operator_join_access(
132 &self,
133 name: &str,
134 relations: Option<&OperatorJoinRelations>,
135 args: &[ScalarExpr],
136 ) -> Result<LocalAccessEstimate, SQLError> {
137 crate::operator_tree_bridge::estimate_operator_join_table_function(
138 self,
139 name,
140 relations,
141 args,
142 &[],
143 )
144 }
145 fn local_access(
146 &self,
147 table: &str,
148 predicate: &ScalarExpr,
149 ) -> Result<Option<LocalAccessEstimate>, SQLError> {
150 crate::operator_tree_bridge::estimate_local_access(self, table, predicate, &[])
151 }
152}
153impl RuleInputColumns for Engine {
154 fn source_column_names(
155 &self,
156 table: &str,
157 relations_bound: bool,
158 ) -> Result<Option<Vec<String>>, SQLError> {
159 uqa_execution::catalog::projection::query_source_column_names(
160 &self.catalog_execution(),
161 table,
162 relations_bound,
163 )
164 }
165}
166
167impl Engine {
168 pub(crate) fn statement_planning_context(
169 &self,
170 ) -> uqa_planner::statement_planning::executable::StatementPlanningContext<'_> {
171 uqa_planner::statement_planning::executable::StatementPlanningContext {
172 analysis: uqa_sql::binding::statements::StatementAnalysisContext {
173 scopes: self,
174 routines: self,
175 aliases: self,
176 },
177 aggregates: self,
178 optimization: self,
179 constant_evaluator: uqa_execution::scalar::eval_constant_scalar,
180 }
181 }
182}
183impl uqa_planner::statement_planning::executable::StatementOptimizationContexts for Engine {
184 fn constant_storage(
185 &self,
186 ) -> Result<Option<Arc<dyn uqa_sql::ir::ConstantValueStorage>>, SQLError> {
187 let bytes =
188 uqa_execution::query::runtime::QueryMemorySettings::work_mem_bytes(&*self.session)?;
189 Ok(Some(Arc::new(
190 uqa_execution::scalar::RetainedConstants::new(bytes),
191 )))
192 }
193 fn builtin_permissions(
194 &self,
195 ) -> Option<Arc<dyn uqa_sql::catalog::security::builtin_routines::BuiltinRoutineExecution>>
196 {
197 Some(Arc::new(uqa_execution::catalog::security::builtin_routines::execution::BuiltinRoutinePermissions::capture(&self.catalog_execution())))
198 }
199 fn statistics(&self) -> StatementStatisticsContext<'_> {
200 self.statement_statistics_context()
201 }
202 fn rule_inputs(&self) -> RuleInputPlanningContext<'_> {
203 self.rule_input_planning_context()
204 }
205 fn routine_inlining(&self) -> Option<uqa_sql::routines::inlining::RoutineInliningContext<'_>> {
206 let compilation = self.routine_definition_context().compilation.analysis;
207 Some(uqa_sql::routines::inlining::RoutineInliningContext {
208 routines: compilation.routines,
209 types: compilation.types,
210 parsers: compilation.parsers,
211 catalog: compilation.catalog,
212 relations: compilation.relations,
213 authority: self,
214 volatility: self,
215 expressions: self,
216 })
217 }
218}
219
220pub(crate) fn estimate_engine_plan(
221 engine: &Engine,
222 plan: &uqa_planner::UnifiedPlan,
223) -> Result<uqa_planner::plan_cost::PlanCost, SQLError> {
224 uqa_planner::statement_planning::estimate_plan(engine.statement_statistics_context(), plan)
225}
226
227pub(crate) fn optimize_engine_query(
228 engine: &Engine,
229 query: &uqa_planner::QueryPlan,
230) -> Result<uqa_planner::QueryPlan, SQLError> {
231 uqa_planner::statement_planning::executable::optimize_query(
232 &engine.statement_planning_context(),
233 query,
234 )
235}
236
237pub(crate) fn optimize_engine_plan(
238 engine: &Engine,
239 plan: uqa_planner::UnifiedPlan,
240) -> Result<uqa_planner::UnifiedPlan, SQLError> {
241 uqa_planner::statement_planning::executable::optimize_plan(
242 &engine.statement_planning_context(),
243 plan,
244 )
245}
246
247impl uqa_sql::routines::inlining::RoutinePlanExpressions for Engine {
248 fn evaluate_constant_routine(
249 &self,
250 expression: &ScalarExpr,
251 ) -> Result<uqa_core::Value, SQLError> {
252 uqa_execution::query::catalog_expression::eval_expression_plan_with_schema(
253 self,
254 crate::capabilities::query_scope::new_for_current_routine(self),
255 uqa_sql::plan::ExpressionPlan {
256 scalar: expression.clone(),
257 subqueries: Vec::new(),
258 },
259 &uqa_sql::ResultRow::new(),
260 &uqa_sql::RowSchema::default(),
261 &[],
262 )
263 }
264}