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 preserve borrowed syntax or an admitted private query.
8
9use super::{production::ControlledBindingContext, BindingContext, SchemaScope};
10use crate::{
11    plan::{QueryBlockPlan, RelationalPlan, SourcePlan},
12    routines::RoutineResolution,
13    RowSchema, SQLError, SQLParam,
14};
15use std::borrow::Cow;
16use uqa_core::memory::ProductionControl;
17
18mod block;
19mod sources;
20pub use block::ExecutionQueryBlock;
21pub(in crate::binding) use sources::CapturedSources;
22pub use sources::{ExecutionSourceBindings, SharedExecutionSourceBindings};
23
24#[derive(Clone, Copy, Default)]
25pub struct ExecutionBindingOptions<'a> {
26    pub outer: Option<&'a RowSchema>,
27    pub defer_distinct_limit: bool,
28}
29
30pub struct BoundExecutionBlock<'a> {
31    pub block: Cow<'a, QueryBlockPlan>,
32    pub schema: RowSchema,
33    pub sources: Option<SharedExecutionSourceBindings<'a>>,
34}
35
36pub struct ControlledExecutionBlock<'a> {
37    pub block: ExecutionQueryBlock<'a>,
38    pub schema: RowSchema,
39    pub sources: Option<SharedExecutionSourceBindings<'a>>,
40}
41
42/// Bind the current execution tree and retain its already visited derived sources for immediate physical assembly in this same immutable scope.
43pub fn bind_query_block_with_sources<'a>(
44    routines: &dyn RoutineResolution,
45    block: &'a QueryBlockPlan,
46    params: &[SQLParam],
47    context: &BindingContext<'_>,
48    outer: Option<&RowSchema>,
49    defer_distinct_limit: bool,
50) -> Result<BoundExecutionBlock<'a>, SQLError> {
51    let control = ProductionControl::uncontrolled();
52    let bound = bind_execution_block(
53        routines,
54        block,
55        params,
56        context.copy_with_control(&control)?,
57        ExecutionBindingOptions {
58            outer,
59            defer_distinct_limit,
60        },
61        true,
62        &control,
63    )?;
64    Ok(BoundExecutionBlock {
65        block: bound.block.into_uncontrolled(),
66        schema: bound.schema,
67        sources: bound.sources,
68    })
69}
70
71/// Keep the input immutable while selecting table-function identities and moving DISTINCT slicing to its existing later boundary.
72pub fn bind_query_block_for_execution<'a>(
73    routines: &dyn RoutineResolution,
74    block: &'a QueryBlockPlan,
75    params: &[SQLParam],
76    context: &BindingContext<'_>,
77    outer: Option<&RowSchema>,
78    defer_distinct_limit: bool,
79) -> Result<(Cow<'a, QueryBlockPlan>, RowSchema), SQLError> {
80    let control = ProductionControl::uncontrolled();
81    let bound = bind_execution_block(
82        routines,
83        block,
84        params,
85        context.copy_with_control(&control)?,
86        ExecutionBindingOptions {
87            outer,
88            defer_distinct_limit,
89        },
90        false,
91        &control,
92    )?;
93    Ok((bound.block.into_uncontrolled(), bound.schema))
94}
95
96/// Bind a private execution block without retaining descriptors for recursive physical source transfer.
97pub fn bind_query_block_for_execution_with_control<'a>(
98    routines: &dyn RoutineResolution,
99    block: &'a QueryBlockPlan,
100    params: &[SQLParam],
101    context: ControlledBindingContext<'_>,
102    options: ExecutionBindingOptions<'_>,
103    control: &ProductionControl<'_>,
104) -> Result<(ExecutionQueryBlock<'a>, RowSchema), SQLError> {
105    let bound = bind_execution_block(routines, block, params, context, options, false, control)?;
106    Ok((bound.block, bound.schema))
107}
108
109pub fn bind_query_block_with_sources_with_control<'a>(
110    routines: &dyn RoutineResolution,
111    block: &'a QueryBlockPlan,
112    params: &[SQLParam],
113    context: ControlledBindingContext<'_>,
114    options: ExecutionBindingOptions<'_>,
115    control: &ProductionControl<'_>,
116) -> Result<ControlledExecutionBlock<'a>, SQLError> {
117    bind_execution_block(routines, block, params, context, options, true, control)
118}
119
120fn bind_execution_block<'a>(
121    routines: &dyn RoutineResolution,
122    block: &'a QueryBlockPlan,
123    params: &[SQLParam],
124    context: ControlledBindingContext<'_>,
125    options: ExecutionBindingOptions<'_>,
126    retain_sources: bool,
127    control: &ProductionControl<'_>,
128) -> Result<ControlledExecutionBlock<'a>, SQLError> {
129    control.check()?;
130    let captured_outer = options
131        .outer
132        .map(|schema| {
133            crate::semantics::view_rewrite::bind_outer_rewrite_scope_with_control(
134                block, schema, control,
135            )
136        })
137        .transpose()?;
138    let outer = captured_outer.as_deref();
139    if options.defer_distinct_limit
140        || block.from.as_ref().is_some_and(source_binds_routines)
141        || !block.deferred_outer_rewrites.is_empty() && block.from.is_some()
142    {
143        return bind_rewritten_block(
144            routines,
145            block,
146            params,
147            context,
148            ExecutionBindingOptions { outer, ..options },
149            control,
150        );
151    }
152    let (schema, sources) = if let Some(source) = &block.from {
153        let subqueries = context.scalar_subqueries;
154        let mut scope = SchemaScope::from_context_with_control(context, control)?;
155        if retain_sources {
156            let captured = CapturedSources::for_source(source, control)?;
157            scope.execution_sources = (!captured.is_empty()).then_some(captured);
158        }
159        let schema = scope.bind_source(routines, source, subqueries, params, outer)?;
160        let sources = scope
161            .execution_sources
162            .as_mut()
163            .map(|captured| captured.take(source, control))
164            .transpose()?;
165        (schema, sources)
166    } else {
167        (empty_schema(control)?, None)
168    };
169    let block = ExecutionQueryBlock::borrowed(block).resolve_outer_rewrites(&schema, control)?;
170    Ok(ControlledExecutionBlock {
171        block,
172        schema,
173        sources,
174    })
175}
176
177fn bind_rewritten_block<'a>(
178    routines: &dyn RoutineResolution,
179    block: &'a QueryBlockPlan,
180    params: &[SQLParam],
181    context: ControlledBindingContext<'_>,
182    options: ExecutionBindingOptions<'_>,
183    control: &ProductionControl<'_>,
184) -> Result<ControlledExecutionBlock<'a>, SQLError> {
185    let outer = options.outer;
186    let mut execution = block.copy_for_rewrite(control)?;
187    if options.defer_distinct_limit {
188        execution = execution.clear_block_slice(control)?;
189    }
190    execution = crate::semantics::view_rewrite::resolve_outer_sources_owned(
191        execution,
192        outer,
193        &mut |source, subqueries, scope| {
194            let context = ControlledBindingContext {
195                scalar_subqueries: subqueries,
196                ..context.copy_with_control(control)?
197            };
198            SchemaScope::from_context_with_control(context, control)?
199                .bind_source_input(routines, source, subqueries, params, scope)
200        },
201        control,
202    )?;
203    let mut schema = None;
204    execution = execution.map_source_with_parent(control, |parent, source| {
205        let RelationalPlan::QueryBlock(parent) = &parent.root else {
206            unreachable!("original query block")
207        };
208        let context = ControlledBindingContext {
209            scalar_subqueries: &parent.subqueries,
210            ..context.copy_with_control(control)?
211        };
212        let (source, bound) = SchemaScope::from_context_with_control(context, control)?
213            .bind_owned_source_for_execution(routines, source, &parent.subqueries, params, outer)?;
214        schema = Some(bound);
215        Ok(source)
216    })?;
217    let schema = match schema {
218        Some(schema) => schema,
219        None => empty_schema(control)?,
220    };
221    execution =
222        crate::semantics::view_rewrite::resolve_outer_rewrites_owned(execution, &schema, control)?;
223    Ok(ControlledExecutionBlock {
224        block: ExecutionQueryBlock::owned(execution, control)?,
225        schema,
226        sources: None,
227    })
228}
229
230fn empty_schema(control: &ProductionControl<'_>) -> Result<RowSchema, SQLError> {
231    RowSchema::new_with_control(
232        control.finish(Vec::new(), control.empty_reservation())?,
233        control,
234    )
235}
236
237fn source_binds_routines(source: &SourcePlan) -> bool {
238    match source {
239        SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. } => true,
240        SourcePlan::Join { left, right, .. } => {
241            source_binds_routines(left) || source_binds_routines(right)
242        }
243        // A nested query selects its routines when its own execution block is entered.
244        SourcePlan::Table { .. }
245        | SourcePlan::Subquery { .. }
246        | SourcePlan::Values { .. }
247        | SourcePlan::RetainedRows(_) => false,
248    }
249}
250
251#[cfg(test)]
252mod tests;