Skip to main content

uqa_execution/query/binding/
capture.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Retain the catalog adapter and capture immutable lexical inputs before SQL preparation.
8
9use crate::query::CteScope;
10use uqa_core::memory::ProductionControl;
11use uqa_sql::{binding::production::ControlledBindingSnapshot, SQLError};
12
13pub fn binding_snapshot_with_control<S: Clone>(
14    scope: &CteScope<S>,
15    control: &ProductionControl<'_>,
16) -> Result<ControlledBindingSnapshot, SQLError> {
17    control.check()?;
18    let catalog = control
19        .finish(scope.catalog_read_view()?, control.empty_reservation())?
20        .into_shared(control)?;
21    let mut schemas = uqa_core::memory::ProductionVec::new(*control);
22    for (name, rows) in &scope.rows {
23        control.check()?;
24        let schema = scope.recursive_control_width(name).map_or_else(
25            || Ok(rows.row_schema().clone()),
26            |width| {
27                uqa_sql::RowSchema::with_recursive_input_with_control(
28                    rows.row_schema(),
29                    width,
30                    control,
31                )
32            },
33        )?;
34        schemas
35            .push_produced(control.finish((name.as_str(), schema), control.empty_reservation())?)?;
36    }
37    ControlledBindingSnapshot::from_inputs_with_control(
38        catalog,
39        scope.relation_name_resolution_with_control(control)?,
40        schemas.iter().map(|(name, schema)| (*name, schema.clone())),
41        scope
42            .deferred_ctes()
43            .iter()
44            .map(|(name, plan)| (name.as_str(), plan)),
45        scope.non_returning_ctes.iter().map(String::as_str),
46        scope.scalar_subqueries.clone(),
47        control,
48    )
49}
50
51pub fn binding_context_with_control<'a, S: Clone>(
52    scope: &'a CteScope<S>,
53    control: &ProductionControl<'_>,
54) -> Result<uqa_sql::binding::production::ControlledBindingContext<'a>, SQLError> {
55    let snapshot = binding_snapshot_with_control(scope, control)?;
56    Ok(uqa_sql::binding::production::ControlledBindingContext {
57        catalog: snapshot.catalog,
58        resolution: snapshot.resolution,
59        ctes: snapshot.ctes,
60        deferred_ctes: snapshot.deferred_ctes,
61        non_returning_ctes: snapshot.non_returning_ctes,
62        scalar_subqueries: &scope.scalar_subqueries,
63    })
64}