Skip to main content

uqa_sql/routines/
inlining.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Caller-plan expansion of selected SQL routines. Source text is analyzed for
8//! each planning attempt; declining expansion never changes the session body cache.
9
10mod operators;
11mod owned;
12mod owned_arguments;
13mod owned_substitution;
14mod preparation;
15mod properties;
16mod selection;
17pub use selection::InlineOwnedRoutineExpression;
18mod table;
19pub use table::{InlineOwnedRoutineQuery, InlineRoutineQuery};
20#[cfg(test)]
21mod tests;
22
23use super::{
24    compilation::{RoutineCompilationCatalog, RoutineParserCatalog},
25    declaration::RoutineTypeCatalog,
26    security::RoutineExecutionAuthority,
27    RoutineResolution,
28};
29use crate::{
30    ast::{CreateFunction, FunctionBinding},
31    plan::UnifiedPlan,
32    semantics::volatility::VolatilityCatalog,
33    SQLError, ScalarExpr,
34};
35
36/// Metadata and analysis capabilities borrowed for one optimizer invocation.
37pub trait RoutinePlanExpressions {
38    /// Execute only an immutable call whose inputs the planner proved constant.
39    /// The existing runtime boundary retains authorization and session body caches.
40    fn evaluate_constant_routine(
41        &self,
42        expression: &ScalarExpr,
43    ) -> Result<uqa_core::Value, SQLError>;
44
45    /// Evaluate a constant call and admit its distinct planning destination before copying the result. Native evaluators also admit their temporary scalar and scope inputs; interpreter rows and results retain their existing execution ownership.
46    fn evaluate_constant_routine_with_control(
47        &self,
48        expression: &ScalarExpr,
49        control: &uqa_core::memory::ProductionControl<'_>,
50    ) -> Result<uqa_core::memory::Produced<uqa_core::Value>, SQLError> {
51        control.check()?;
52        let value = self.evaluate_constant_routine(expression)?;
53        if control.budget().is_none() {
54            Ok(control.finish(value, None)?)
55        } else {
56            Ok(control.copy_value(&value)?)
57        }
58    }
59}
60
61#[derive(Clone, Copy)]
62pub struct RoutineInliningContext<'a> {
63    pub routines: &'a dyn RoutineResolution,
64    pub types: &'a dyn RoutineTypeCatalog,
65    pub parsers: &'a dyn RoutineParserCatalog,
66    pub catalog: &'a dyn RoutineCompilationCatalog,
67    pub relations: &'a dyn crate::binding::stored_relations::StoredRelationCatalog,
68    pub authority: &'a dyn RoutineExecutionAuthority,
69    pub volatility: &'a dyn VolatilityCatalog,
70    pub expressions: &'a dyn RoutinePlanExpressions,
71}
72
73impl std::fmt::Debug for RoutineInliningContext<'_> {
74    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        formatter
76            .debug_struct("RoutineInliningContext")
77            .finish_non_exhaustive()
78    }
79}
80
81/// A typed replacement, together with the routine identity whose recursive
82/// expansion the planner must suppress while simplifying the replacement.
83pub struct InlineRoutineExpression {
84    pub identity: [u8; 16],
85    pub expression: ScalarExpr,
86    pub error_context: Option<String>,
87}
88
89impl RoutineInliningContext<'_> {
90    /// Classify an analyzed/planned expression in its own row scope, including casts and selected operators.
91    pub fn expression_volatility(
92        &self,
93        expression: &ScalarExpr,
94        schema: &crate::RowSchema,
95    ) -> Result<crate::ast::FunctionVolatility, SQLError> {
96        properties::volatility(self, expression, schema)
97    }
98
99    pub fn expression_volatility_with_control(
100        &self,
101        expression: &ScalarExpr,
102        schema: &crate::RowSchema,
103        control: &uqa_core::memory::ProductionControl<'_>,
104    ) -> Result<crate::ast::FunctionVolatility, SQLError> {
105        properties::volatility_with_control(self, expression, schema, control)
106    }
107
108    /// Try the selected routine only; a same-named overload cannot replace it.
109    /// Argument simplification and lazy branches belong to the caller's planner.
110    pub fn prepare(
111        &self,
112        binding: &FunctionBinding,
113        arguments: &[ScalarExpr],
114        active: &[[u8; 16]],
115    ) -> Result<Option<InlineRoutineExpression>, SQLError> {
116        let control = uqa_core::memory::ProductionControl::uncontrolled();
117        let replacement = self.prepare_owned(binding, arguments, active, &control)?;
118        replacement
119            .map(|replacement| {
120                Ok(InlineRoutineExpression {
121                    identity: replacement.identity,
122                    expression: replacement
123                        .expression
124                        .finish(&control)?
125                        .into_uncontrolled()
126                        .expect("ordinary inline expression"),
127                    error_context: replacement.error_context.map(|frame| {
128                        frame
129                            .into_uncontrolled()
130                            .expect("ordinary inline diagnostic frame")
131                    }),
132                })
133            })
134            .transpose()
135    }
136
137    /// Expand defaults, named arguments and implicit casts before the planner
138    /// simplifies children. Returning an exact invocation prevents a second
139    /// overload selection and keeps discarded or repeated arguments typed.
140    pub fn materialize_call(
141        &self,
142        binding: &FunctionBinding,
143        arguments: &[ScalarExpr],
144    ) -> Result<Option<(FunctionBinding, Vec<ScalarExpr>)>, SQLError> {
145        let control = uqa_core::memory::ProductionControl::uncontrolled();
146        let Some((selected, arguments)) =
147            self.materialized_owned_arguments(binding, arguments, &control)?
148        else {
149            return Ok(None);
150        };
151        let selected = selected
152            .into_uncontrolled()
153            .expect("ordinary selected binding");
154        let arguments = arguments
155            .finish(&control)?
156            .into_uncontrolled()
157            .expect("ordinary call arguments");
158        let ScalarExpr::Or(arguments) = arguments else {
159            unreachable!("routine argument container");
160        };
161        Ok(Some((selected, arguments)))
162    }
163
164    fn selected_function(
165        &self,
166        binding: &FunctionBinding,
167    ) -> Option<std::sync::Arc<super::SQLUserFunction>> {
168        super::selected_bound_function(self.routines, binding)
169    }
170
171    /// Ordinary messages repeat optimizer-time routine work. Prepared plans
172    /// intentionally keep their own custom/generic planning lifetime instead.
173    pub fn requires_replanning(&self, plan: &UnifiedPlan) -> bool {
174        let mut required = false;
175        plan.visit_scalar_expressions(&mut |root| {
176            root.visit(&mut |expression| {
177                let ScalarExpr::Func {
178                    binding: Some(binding),
179                    ..
180                } = expression
181                else {
182                    return;
183                };
184                if binding.builtin {
185                    return;
186                }
187                required |= self
188                    .routines
189                    .lookup_bound_sql_functions_by_binding(binding)
190                    .is_some_and(|functions| {
191                        functions.iter().any(|function| {
192                            function.def.object_id == binding.object_id
193                                && super::routine_signature_types(&function.def)
194                                    == binding.argument_types
195                                && (eligible_definition(&function.def)
196                                    || function.def.volatility
197                                        == crate::ast::FunctionVolatility::Immutable)
198                        })
199                    });
200            });
201        });
202        plan.visit_sources(&mut |source| {
203            if let crate::plan::SourcePlan::Function {
204                binding: Some(binding),
205                ..
206            } = source
207            {
208                required |= self.selected_function(binding).is_some_and(|function| {
209                    eligible_definition(&function.def)
210                        || table::eligible_definition(&function.def)
211                        || function.def.volatility == crate::ast::FunctionVolatility::Immutable
212                });
213            }
214        });
215        required
216    }
217
218    pub fn requires_replanning_with_control(
219        &self,
220        plan: crate::plan::PlanRef<'_>,
221        control: &uqa_core::memory::ProductionControl<'_>,
222    ) -> Result<bool, SQLError> {
223        let mut required = false;
224        let mut status: Result<(), SQLError> = Ok(());
225        plan.visit_scalar_expressions(&mut |root| {
226            if status.is_err() {
227                return;
228            }
229            status = root.try_visit(&mut |expression| {
230                control.check()?;
231                if let ScalarExpr::Func {
232                    binding: Some(binding),
233                    ..
234                } = expression
235                {
236                    if !binding.builtin {
237                        if let Some(function) = super::selected_bound_function_with_control(
238                            self.routines,
239                            binding,
240                            control,
241                        )? {
242                            required |= eligible_definition(&function.def)
243                                || function.def.volatility
244                                    == crate::ast::FunctionVolatility::Immutable;
245                        }
246                    }
247                }
248                Ok::<_, SQLError>(true)
249            });
250        });
251        status?;
252        let mut status: Result<(), SQLError> = Ok(());
253        plan.visit_sources(&mut |source| {
254            if status.is_err() {
255                return;
256            }
257            status = (|| {
258                control.check()?;
259                if let crate::plan::SourcePlan::Function {
260                    binding: Some(binding),
261                    ..
262                } = source
263                {
264                    if let Some(function) = super::selected_bound_function_with_control(
265                        self.routines,
266                        binding,
267                        control,
268                    )? {
269                        required |= eligible_definition(&function.def)
270                            || table::eligible_definition(&function.def)
271                            || function.def.volatility == crate::ast::FunctionVolatility::Immutable;
272                    }
273                }
274                Ok(())
275            })();
276        });
277        status?;
278        Ok(required)
279    }
280}
281
282fn eligible_definition(definition: &CreateFunction) -> bool {
283    selection::eligible_definition_with_control(
284        definition,
285        &uqa_core::memory::ProductionControl::uncontrolled(),
286    )
287    .expect("ordinary routine eligibility")
288}
289
290fn is_constant(expression: &ScalarExpr) -> bool {
291    matches!(
292        expression,
293        ScalarExpr::Literal(_) | ScalarExpr::TypedLiteral { .. } | ScalarExpr::RetainedLiteral(_)
294    )
295}
296
297fn is_null_constant(expression: &ScalarExpr) -> bool {
298    matches!(
299        expression,
300        ScalarExpr::Literal(uqa_core::Value::Null)
301            | ScalarExpr::TypedLiteral {
302                value: uqa_core::Value::Null,
303                ..
304            }
305    )
306}