Skip to main content

uqa_sql/binding/
execution.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Execution-local source bindings without copying unchanged query syntax.
8
9use std::borrow::Cow;
10use std::sync::Arc;
11
12use super::{bind_source_plan_schema_for_execution, BindingContext};
13use crate::{
14    plan::{QueryBlockPlan, SourcePlan},
15    routines::RoutineResolution,
16    RowSchema, SQLError, SQLParam,
17};
18
19mod sources;
20pub(in crate::binding) use sources::CapturedSources;
21pub use sources::ExecutionSourceBindings;
22
23pub struct BoundExecutionBlock<'a> {
24    pub block: Cow<'a, QueryBlockPlan>,
25    pub schema: RowSchema,
26    pub sources: Option<Arc<ExecutionSourceBindings<'a>>>,
27}
28
29/// Bind the current execution tree and retain its already visited derived sources for immediate physical assembly in this same immutable scope. Source/function rewrites retain their ordinary binding path.
30pub fn bind_query_block_with_sources<'a>(
31    routines: &dyn RoutineResolution,
32    block: &'a QueryBlockPlan,
33    params: &[SQLParam],
34    context: &BindingContext<'_>,
35    outer: Option<&RowSchema>,
36    defer_distinct_limit: bool,
37) -> Result<BoundExecutionBlock<'a>, SQLError> {
38    bind_execution_block(
39        routines,
40        block,
41        params,
42        context,
43        outer,
44        defer_distinct_limit,
45        true,
46    )
47}
48
49/// Keep the input immutable while selecting table-function identities and, when requested, moving the DISTINCT slice to its existing later boundary.
50pub fn bind_query_block_for_execution<'a>(
51    routines: &dyn RoutineResolution,
52    block: &'a QueryBlockPlan,
53    params: &[SQLParam],
54    context: &BindingContext<'_>,
55    outer: Option<&RowSchema>,
56    defer_distinct_limit: bool,
57) -> Result<(Cow<'a, QueryBlockPlan>, RowSchema), SQLError> {
58    let bound = bind_execution_block(
59        routines,
60        block,
61        params,
62        context,
63        outer,
64        defer_distinct_limit,
65        false,
66    )?;
67    Ok((bound.block, bound.schema))
68}
69
70fn bind_execution_block<'a>(
71    routines: &dyn RoutineResolution,
72    block: &'a QueryBlockPlan,
73    params: &[SQLParam],
74    context: &BindingContext<'_>,
75    outer: Option<&RowSchema>,
76    defer_distinct_limit: bool,
77    retain_sources: bool,
78) -> Result<BoundExecutionBlock<'a>, SQLError> {
79    let captured_outer =
80        outer.map(|schema| crate::semantics::view_rewrite::bind_outer_rewrite_scope(block, schema));
81    let outer = captured_outer.as_deref();
82    if defer_distinct_limit
83        || block.from.as_ref().is_some_and(source_binds_routines)
84        || !block.deferred_outer_rewrites.is_empty() && block.from.is_some()
85    {
86        let mut execution = crate::semantics::select_execution_stmt(block, defer_distinct_limit);
87        if let Cow::Owned(rewritten) = crate::semantics::view_rewrite::resolve_outer_sources(
88            &execution,
89            outer,
90            &mut |source, subqueries, scope| {
91                super::sources::bind_source_input_schema(
92                    routines,
93                    source,
94                    params,
95                    &BindingContext {
96                        scalar_subqueries: subqueries,
97                        ..context.clone()
98                    },
99                    scope,
100                )
101            },
102        )? {
103            execution = rewritten;
104        }
105        let source_context = BindingContext {
106            scalar_subqueries: &execution.subqueries,
107            ..context.clone()
108        };
109        let source = execution.from.as_mut().map_or_else(
110            || Ok(RowSchema::default()),
111            |source| {
112                bind_source_plan_schema_for_execution(
113                    routines,
114                    source,
115                    params,
116                    &source_context,
117                    outer,
118                )
119            },
120        )?;
121        if let Cow::Owned(rewritten) =
122            crate::semantics::view_rewrite::resolve_outer_rewrites(&execution, &source)
123        {
124            execution = rewritten;
125        }
126        return Ok(BoundExecutionBlock {
127            block: Cow::Owned(execution),
128            schema: source,
129            sources: None,
130        });
131    }
132    let (schema, sources) = if let Some(source) = &block.from {
133        let mut scope = super::SchemaScope::from_context(context)?;
134        scope.execution_sources = retain_sources
135            .then(|| CapturedSources::for_source(source))
136            .filter(|captured| !captured.is_empty());
137        let schema =
138            scope.bind_source(routines, source, context.scalar_subqueries, params, outer)?;
139        let sources = scope
140            .execution_sources
141            .as_mut()
142            .map(|captured| captured.take(source));
143        (schema, sources)
144    } else {
145        (RowSchema::default(), None)
146    };
147    Ok(BoundExecutionBlock {
148        block: crate::semantics::view_rewrite::resolve_outer_rewrites(block, &schema),
149        schema,
150        sources,
151    })
152}
153
154fn source_binds_routines(source: &SourcePlan) -> bool {
155    match source {
156        SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. } => true,
157        SourcePlan::Join { left, right, .. } => {
158            source_binds_routines(left) || source_binds_routines(right)
159        }
160        // A nested query selects its routines when its own execution block is entered.
161        SourcePlan::Table { .. }
162        | SourcePlan::Subquery { .. }
163        | SourcePlan::Values { .. }
164        | SourcePlan::RetainedRows(_) => false,
165    }
166}
167
168#[cfg(test)]
169mod tests;