Skip to main content

uqa_execution/query/scope/
bindings.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Save selected lexical bindings and restore their exact nodes without allocating.
8
9use super::{definitions::DefinitionBindings, CteRowsMap, CteScope};
10use std::{collections::BTreeSet, sync::Arc};
11use uqa_core::memory::ProductionControl;
12use uqa_sql::{
13    binding::production::{BindingMap, BindingNameSet},
14    plan::RetainedCtePlan,
15    SQLError,
16};
17
18#[derive(Default)]
19pub struct SavedCteBindings {
20    names: BindingNameSet,
21    rows: CteRowsMap,
22    deferred: BindingMap<RetainedCtePlan>,
23    definitions: BindingMap<Arc<DefinitionBindings>>,
24    non_returning: BindingNameSet,
25    folded: BindingNameSet,
26}
27
28pub fn save_and_remove_cte_names<S: Clone>(
29    ctes: &mut CteScope<S>,
30    names: &BTreeSet<String>,
31) -> SavedCteBindings {
32    save_and_remove_cte_names_with_control(
33        ctes,
34        names.iter().map(String::as_str),
35        &ProductionControl::uncontrolled(),
36    )
37    .expect("ordinary lexical extraction")
38}
39
40pub fn save_and_remove_cte_names_with_control<'n, S: Clone>(
41    ctes: &mut CteScope<S>,
42    names: impl IntoIterator<Item = &'n str>,
43    control: &ProductionControl<'_>,
44) -> Result<SavedCteBindings, SQLError> {
45    let mut saved = SavedCteBindings::default();
46    for name in names {
47        saved.names.insert_with_control(name, control)?;
48    }
49    control.check()?;
50    for name in &saved.names {
51        saved.rows.append(ctes.rows.extract(name));
52        saved.deferred.append(ctes.deferred_ctes.extract(name));
53        saved
54            .definitions
55            .append(ctes.definition_scopes.extract(name));
56        saved
57            .non_returning
58            .append(ctes.non_returning_ctes.extract(name));
59        saved.folded.append(ctes.folded_ctes.extract(name));
60    }
61    Ok(saved)
62}
63
64/// Retain enclosing names while non-recursive definitions establish their inputs. No part of the live scope changes during admission.
65pub fn save_cte_names<S: Clone>(ctes: &CteScope<S>, names: &BTreeSet<String>) -> SavedCteBindings {
66    save_cte_names_with_control(
67        ctes,
68        names.iter().map(String::as_str),
69        &ProductionControl::uncontrolled(),
70    )
71    .expect("ordinary lexical copy")
72}
73
74pub fn save_cte_names_with_control<'n, S: Clone>(
75    ctes: &CteScope<S>,
76    names: impl IntoIterator<Item = &'n str>,
77    control: &ProductionControl<'_>,
78) -> Result<SavedCteBindings, SQLError> {
79    control.check()?;
80    let mut saved = SavedCteBindings::default();
81    for name in names {
82        if !saved.names.insert_with_control(name, control)? {
83            continue;
84        }
85        if let Some(rows) = ctes.rows.get(name) {
86            saved
87                .rows
88                .insert_with_control(name, rows.clone(), control)?;
89        }
90        if let Some(plan) = ctes.deferred_ctes.get(name) {
91            saved
92                .deferred
93                .insert_with_control(name, plan.clone(), control)?;
94        }
95        if let Some(definition) = ctes.definition_scopes.get(name) {
96            saved
97                .definitions
98                .insert_with_control(name, Arc::clone(definition), control)?;
99        }
100        if ctes.non_returning_ctes.contains(name) {
101            saved.non_returning.insert_with_control(name, control)?;
102        }
103        if ctes.folded_ctes.contains(name) {
104            saved.folded.insert_with_control(name, control)?;
105        }
106    }
107    Ok(saved)
108}
109
110pub fn restore_cte_names<S: Clone>(ctes: &mut CteScope<S>, saved: SavedCteBindings) {
111    for name in &saved.names {
112        ctes.remove_materialized(name);
113        ctes.remove_deferred(name);
114    }
115    ctes.rows.append(saved.rows);
116    ctes.deferred_ctes.append(saved.deferred);
117    ctes.definition_scopes.append(saved.definitions);
118    ctes.non_returning_ctes.append(saved.non_returning);
119    ctes.folded_ctes.append(saved.folded);
120}
121
122pub struct CteBindingScope<'a, S: Clone> {
123    scope: &'a mut CteScope<S>,
124    saved: Option<SavedCteBindings>,
125}
126
127impl<S: Clone> CteScope<S> {
128    /// Restore only the selected names on every exit, preserving progress of unrelated materialized inputs.
129    pub fn enter_cte_bindings_with_control<'a, 'n>(
130        &'a mut self,
131        names: impl IntoIterator<Item = &'n str>,
132        control: &ProductionControl<'_>,
133    ) -> Result<CteBindingScope<'a, S>, SQLError> {
134        let saved = save_cte_names_with_control(self, names, control)?;
135        Ok(CteBindingScope {
136            scope: self,
137            saved: Some(saved),
138        })
139    }
140}
141impl<S: Clone> std::ops::Deref for CteBindingScope<'_, S> {
142    type Target = CteScope<S>;
143    fn deref(&self) -> &Self::Target {
144        self.scope
145    }
146}
147impl<S: Clone> std::ops::DerefMut for CteBindingScope<'_, S> {
148    fn deref_mut(&mut self) -> &mut Self::Target {
149        self.scope
150    }
151}
152impl<S: Clone> Drop for CteBindingScope<'_, S> {
153    fn drop(&mut self) {
154        restore_cte_names(self.scope, self.saved.take().expect("live lexical guard"));
155    }
156}