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