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;
10
11use super::{bind_source_plan_schema, bind_source_plan_schema_for_execution, BindingContext};
12use crate::{
13    plan::{QueryBlockPlan, SourcePlan},
14    routines::RoutineResolution,
15    RowSchema, SQLError, SQLParam,
16};
17
18/// Keep the input immutable while selecting table-function identities and, when requested, moving the DISTINCT slice to its existing later boundary.
19pub fn bind_query_block_for_execution<'a>(
20    routines: &dyn RoutineResolution,
21    block: &'a QueryBlockPlan,
22    params: &[SQLParam],
23    context: &BindingContext<'_>,
24    outer: Option<&RowSchema>,
25    defer_distinct_limit: bool,
26) -> Result<(Cow<'a, QueryBlockPlan>, RowSchema), SQLError> {
27    if defer_distinct_limit || block.from.as_ref().is_some_and(source_binds_routines) {
28        let mut execution = crate::semantics::select_execution_stmt(block, defer_distinct_limit);
29        let source = execution.from.as_mut().map_or_else(
30            || Ok(RowSchema::default()),
31            |source| {
32                bind_source_plan_schema_for_execution(routines, source, params, context, outer)
33            },
34        )?;
35        return Ok((Cow::Owned(execution), source));
36    }
37    let source = block.from.as_ref().map_or_else(
38        || Ok(RowSchema::default()),
39        |source| bind_source_plan_schema(routines, source, params, context, outer),
40    )?;
41    Ok((Cow::Borrowed(block), source))
42}
43
44fn source_binds_routines(source: &SourcePlan) -> bool {
45    match source {
46        SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. } => true,
47        SourcePlan::Join { left, right, .. } => {
48            source_binds_routines(left) || source_binds_routines(right)
49        }
50        // A nested query selects its routines when its own execution block is entered.
51        SourcePlan::Table { .. }
52        | SourcePlan::Subquery { .. }
53        | SourcePlan::Values { .. }
54        | SourcePlan::RetainedRows(_) => false,
55    }
56}
57
58#[cfg(test)]
59mod tests;