Skip to main content

uqa_execution/query/
binding.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Adapt active engine statement inputs to SQL-owned static binding.
8
9use super::CteScope;
10use crate::{RowSchema, ScalarExpr};
11use uqa_sql::plan::{
12    CommandPlan, ExpressionPlan, ProjectionPlan, QueryBlockPlan, QueryPlan, SourcePlan, UnifiedPlan,
13};
14use uqa_sql::routines::RoutineResolution;
15use uqa_sql::{ColumnType, SQLError, SQLParam};
16mod capture;
17mod context;
18pub use capture::{binding_context_with_control, binding_snapshot_with_control};
19pub(crate) mod sources;
20pub use context::binding_context;
21mod subqueries;
22pub use subqueries::resolve_scalar_subquery_type;
23
24pub(crate) fn source_depends_on_current_row<S: Clone>(
25    routines: &dyn RoutineResolution,
26    source: &SourcePlan,
27    input: &RowSchema,
28    ctes: &CteScope<S>,
29) -> Result<bool, SQLError> {
30    let catalog = ctes.catalog_read_view()?;
31    let resolution = ctes.relation_name_resolution()?;
32    uqa_sql::binding::correlation::source_depends_on_current_row(
33        uqa_sql::binding::correlation::CorrelationContext {
34            routines,
35            catalog: &catalog,
36            resolution: &resolution,
37            scoped_relations: Some(ctes),
38        },
39        source,
40        &ctes.scalar_subqueries,
41        input,
42    )
43}
44
45pub fn analyze_prepared_command_schema<S: Clone>(
46    routines: &dyn RoutineResolution,
47    command: &CommandPlan,
48    params: &[SQLParam],
49    ctes: &CteScope<S>,
50) -> Result<Option<RowSchema>, SQLError> {
51    uqa_sql::binding::analyze_prepared_command_schema(
52        routines,
53        command,
54        params,
55        &binding_context(ctes)?,
56    )
57}
58
59pub fn analyze_recursive_control_step<S: Clone>(
60    routines: &dyn RoutineResolution,
61    cte: &uqa_sql::plan::CtePlan,
62    step: &QueryPlan,
63    base_schema: RowSchema,
64    params: &[SQLParam],
65    ctes: &CteScope<S>,
66) -> Result<(), SQLError> {
67    uqa_sql::binding::analyze_recursive_control_step(
68        routines,
69        cte,
70        step,
71        base_schema,
72        params,
73        &binding_context(ctes)?,
74    )
75}
76
77pub fn infer_prepared_parameter_types<S: Clone>(
78    routines: &dyn RoutineResolution,
79    plan: &UnifiedPlan,
80    declared: &[Option<ColumnType>],
81    ctes: &CteScope<S>,
82) -> Result<Vec<Option<ColumnType>>, SQLError> {
83    uqa_sql::binding::infer_prepared_parameter_types(
84        routines,
85        plan,
86        declared,
87        &binding_context(ctes)?,
88    )
89}
90
91pub fn bind_projection_output_schema<S: Clone>(
92    routines: &dyn RoutineResolution,
93    projections: &[ProjectionPlan],
94    schemas: uqa_sql::binding::ProjectionSchemas<'_>,
95    subqueries: &[QueryPlan],
96    params: &[SQLParam],
97    ctes: &CteScope<S>,
98    control: &uqa_core::memory::ProductionControl<'_>,
99) -> Result<RowSchema, SQLError> {
100    uqa_sql::binding::bind_projection_output_schema_with_control(
101        routines,
102        projections,
103        schemas,
104        subqueries,
105        params,
106        binding_context_with_control(ctes, control)?,
107        control,
108    )
109}
110
111pub fn analyze_projection_output_schema<S: Clone>(
112    routines: &dyn RoutineResolution,
113    projections: &[ProjectionPlan],
114    schemas: uqa_sql::binding::ProjectionSchemas<'_>,
115    subqueries: &[QueryPlan],
116    params: &[SQLParam],
117    ctes: &CteScope<S>,
118    control: &uqa_core::memory::ProductionControl<'_>,
119) -> Result<RowSchema, SQLError> {
120    uqa_sql::binding::analyze_projection_output_schema_with_control(
121        routines,
122        projections,
123        schemas,
124        subqueries,
125        params,
126        binding_context_with_control(ctes, control)?,
127        control,
128    )
129}
130
131pub fn validate_query_block_expression_types<S: Clone>(
132    routines: &dyn RoutineResolution,
133    statement: &QueryBlockPlan,
134    schema: &RowSchema,
135    params: &[SQLParam],
136    ctes: &CteScope<S>,
137    control: &uqa_core::memory::ProductionControl<'_>,
138) -> Result<(), SQLError> {
139    uqa_sql::binding::validate_query_block_expression_types_with_control(
140        routines,
141        statement,
142        schema,
143        params,
144        binding_context_with_control(ctes, control)?,
145        control,
146    )
147}
148
149pub fn validate_query_block_references<S: Clone>(
150    routines: &dyn RoutineResolution,
151    statement: &QueryBlockPlan,
152    schema: &RowSchema,
153    params: &[SQLParam],
154    ctes: &CteScope<S>,
155    outer: Option<&RowSchema>,
156    control: &uqa_core::memory::ProductionControl<'_>,
157) -> Result<(), SQLError> {
158    uqa_sql::binding::validate_query_block_references_with_control(
159        routines,
160        statement,
161        schema,
162        params,
163        binding_context_with_control(ctes, control)?,
164        outer,
165        control,
166    )
167}
168
169pub fn bind_query_plan_routines_for_storage<S: Clone>(
170    engine: &dyn RoutineResolution,
171    plan: &mut QueryPlan,
172    params: &[SQLParam],
173    ctes: &CteScope<S>,
174    outer: Option<&RowSchema>,
175) -> Result<RowSchema, SQLError> {
176    uqa_sql::binding::bind_query_plan_routines_for_storage(
177        engine,
178        plan,
179        params,
180        &binding_context(ctes)?,
181        outer,
182    )
183}
184
185/// Record each call's input collation in a stored query whose routines are bound.
186pub fn assign_query_plan_input_collations<S: Clone>(
187    engine: &dyn RoutineResolution,
188    plan: &mut QueryPlan,
189    ctes: &CteScope<S>,
190) -> Result<(), SQLError> {
191    uqa_sql::binding::assign_stored_query_input_collations(engine, plan, &binding_context(ctes)?)
192}
193
194pub fn bind_expression_plan_routines_for_storage<S: Clone>(
195    engine: &dyn RoutineResolution,
196    plan: &mut ExpressionPlan,
197    params: &[SQLParam],
198    ctes: &CteScope<S>,
199    schema: &RowSchema,
200) -> Result<Option<ColumnType>, SQLError> {
201    uqa_sql::binding::bind_expression_plan_routines_for_storage(
202        engine,
203        plan,
204        params,
205        &binding_context(ctes)?,
206        schema,
207    )
208}
209
210pub fn bind_query_plan_schema<S: Clone>(
211    routines: &dyn RoutineResolution,
212    plan: &QueryPlan,
213    params: &[SQLParam],
214    ctes: &CteScope<S>,
215    outer: Option<&RowSchema>,
216) -> Result<RowSchema, SQLError> {
217    uqa_sql::binding::bind_query_plan_schema(routines, plan, params, &binding_context(ctes)?, outer)
218}
219
220pub fn bind_expression_plan_type<S: Clone>(
221    routines: &dyn RoutineResolution,
222    plan: &ExpressionPlan,
223    params: &[SQLParam],
224    ctes: &CteScope<S>,
225) -> Result<Option<ColumnType>, SQLError> {
226    uqa_sql::binding::bind_expression_plan_type(routines, plan, params, &binding_context(ctes)?)
227}
228
229pub fn analyze_expression_plan_type<S: Clone>(
230    routines: &dyn RoutineResolution,
231    plan: &ExpressionPlan,
232    params: &[SQLParam],
233    ctes: &CteScope<S>,
234) -> Result<Option<ColumnType>, SQLError> {
235    uqa_sql::binding::analyze_expression_plan_type(routines, plan, params, &binding_context(ctes)?)
236}
237
238pub fn analyze_query_plan_schema<S: Clone>(
239    routines: &dyn RoutineResolution,
240    plan: &QueryPlan,
241    params: &[SQLParam],
242    ctes: &CteScope<S>,
243    outer: Option<&RowSchema>,
244) -> Result<RowSchema, SQLError> {
245    uqa_sql::binding::analyze_query_plan_schema(
246        routines,
247        plan,
248        params,
249        &binding_context(ctes)?,
250        outer,
251    )
252}
253
254pub fn values_types_in_scope<S: Clone>(
255    routines: &dyn RoutineResolution,
256    rows: &[Vec<ScalarExpr>],
257    subqueries: &[QueryPlan],
258    schema: Option<&RowSchema>,
259    params: &[SQLParam],
260    ctes: &CteScope<S>,
261) -> Result<Vec<Option<ColumnType>>, SQLError> {
262    values_schema_in_scope(routines, rows, subqueries, schema, params, ctes)
263        .map(|schema| schema.column_types().to_vec())
264}
265
266pub fn values_schema_in_scope<S: Clone>(
267    routines: &dyn RoutineResolution,
268    rows: &[Vec<ScalarExpr>],
269    subqueries: &[QueryPlan],
270    schema: Option<&RowSchema>,
271    params: &[SQLParam],
272    ctes: &CteScope<S>,
273) -> Result<RowSchema, SQLError> {
274    uqa_sql::binding::values_schema_in_scope(
275        routines,
276        rows,
277        subqueries,
278        schema,
279        params,
280        &binding_context(ctes)?,
281    )
282}
283
284pub fn bind_source_plan_schema<S: Clone>(
285    routines: &dyn RoutineResolution,
286    source: &SourcePlan,
287    params: &[SQLParam],
288    ctes: &CteScope<S>,
289    outer: Option<&RowSchema>,
290    control: &uqa_core::memory::ProductionControl<'_>,
291) -> Result<RowSchema, SQLError> {
292    uqa_sql::binding::production::bind_source_plan_schema_with_control(
293        routines,
294        source,
295        params,
296        binding_context_with_control(ctes, control)?,
297        outer,
298        control,
299    )
300}
301
302pub fn analyze_source_plan_schema<S: Clone>(
303    routines: &dyn RoutineResolution,
304    source: &SourcePlan,
305    params: &[SQLParam],
306    ctes: &CteScope<S>,
307    outer: Option<&RowSchema>,
308) -> Result<RowSchema, SQLError> {
309    uqa_sql::binding::analyze_source_plan_schema(
310        routines,
311        source,
312        params,
313        &binding_context(ctes)?,
314        outer,
315    )
316}
317
318pub fn bind_source_plan_for_execution<S: Clone>(
319    routines: &dyn RoutineResolution,
320    source: uqa_sql::plan::MutableSourcePlan,
321    params: &[SQLParam],
322    ctes: &CteScope<S>,
323    outer: Option<&RowSchema>,
324    control: &uqa_core::memory::ProductionControl<'_>,
325) -> Result<(uqa_sql::plan::MutableSourcePlan, RowSchema), SQLError> {
326    uqa_sql::binding::bind_source_plan_for_execution_owned(
327        routines,
328        source,
329        params,
330        binding_context_with_control(ctes, control)?,
331        outer,
332        control,
333    )
334}
335
336pub fn bind_query_block_for_execution<'a, S: Clone>(
337    routines: &dyn RoutineResolution,
338    block: &'a QueryBlockPlan,
339    params: &[SQLParam],
340    ctes: &CteScope<S>,
341    options: uqa_sql::binding::ExecutionBindingOptions<'_>,
342    control: &uqa_core::memory::ProductionControl<'_>,
343) -> Result<(uqa_sql::binding::ExecutionQueryBlock<'a>, RowSchema), SQLError> {
344    uqa_sql::binding::bind_query_block_for_execution_with_control(
345        routines,
346        block,
347        params,
348        binding_context_with_control(ctes, control)?,
349        options,
350        control,
351    )
352}
353
354pub use uqa_sql::binding::{
355    extend_cte_generated_schema, overlay_outer_schema, with_query_table_pseudo_columns,
356};
357
358impl<S: Clone> uqa_sql::semantics::returning::ReturningScope for CteScope<S> {
359    fn binding_snapshot(&self) -> Result<uqa_sql::binding::snapshot::BindingSnapshot, SQLError> {
360        binding_context(self).map(uqa_sql::binding::snapshot::BindingSnapshot::from)
361    }
362}
363
364pub fn analyze_command_parameters<S: Clone>(
365    routines: &dyn RoutineResolution,
366    command: &CommandPlan,
367    params: &[SQLParam],
368    ctes: &CteScope<S>,
369) -> Result<(), SQLError> {
370    uqa_sql::binding::statements::analyze_command_parameters(routines, command, params, ctes)
371}
372
373impl<S: Clone> uqa_sql::binding::statements::StatementBindingScope for CteScope<S> {
374    fn binding_context_with_control(
375        &self,
376        control: &uqa_core::memory::ProductionControl<'_>,
377    ) -> Result<uqa_sql::binding::production::ControlledBindingContext<'_>, SQLError> {
378        binding_context_with_control(self, control)
379    }
380
381    fn binding_context(&self) -> Result<uqa_sql::binding::BindingContext<'_>, SQLError> {
382        binding_context(self)
383    }
384}
385
386/// Add SQL-owned structural identities while retaining the outer row's existing physical fragments.
387pub(crate) fn bind_outer_rewrite_row<'a>(
388    block: &QueryBlockPlan,
389    outer: &'a crate::OwnedPhysicalRow,
390) -> std::borrow::Cow<'a, crate::OwnedPhysicalRow> {
391    match uqa_sql::semantics::view_rewrite::bind_outer_rewrite_scope(block, &outer.schema) {
392        std::borrow::Cow::Borrowed(_) => std::borrow::Cow::Borrowed(outer),
393        std::borrow::Cow::Owned(schema) => std::borrow::Cow::Owned(crate::OwnedPhysicalRow {
394            schema,
395            row: outer.row.clone(),
396        }),
397    }
398}
399
400/// Source syntax and the scalar arena selected with its actual preceding row descriptor.
401pub(crate) struct OuterSourceBinding {
402    pub(crate) source: Box<SourcePlan>,
403    pub(crate) subqueries: Vec<QueryPlan>,
404}
405
406pub(crate) fn bind_outer_source_rewrites<S: Clone>(
407    routines: &dyn uqa_sql::routines::RoutineResolution,
408    source: &SourcePlan,
409    params: &[SQLParam],
410    ctes: &CteScope<S>,
411    scope: uqa_sql::binding::SourceScope<'_>,
412) -> Result<Option<OuterSourceBinding>, SQLError> {
413    let Some(rewrites) = &ctes.source_outer_rewrites else {
414        return Ok(None);
415    };
416    let context = binding_context(ctes)?;
417    let mut subqueries = ctes.scalar_subqueries.to_vec();
418    let source = uqa_sql::semantics::view_rewrite::resolve_outer_source_rewrites(
419        source,
420        rewrites,
421        &mut subqueries,
422        scope,
423        &mut |source, subqueries, scope| {
424            uqa_sql::binding::bind_source_input_schema(
425                routines,
426                source,
427                params,
428                &uqa_sql::binding::BindingContext {
429                    scalar_subqueries: subqueries,
430                    ..context.clone()
431                },
432                scope,
433            )
434        },
435    )?
436    .into_owned();
437    Ok(Some(OuterSourceBinding {
438        source: Box::new(source),
439        subqueries,
440    }))
441}