Skip to main content

uqa_execution/query/scope/
definitions.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Lexical inputs of deferred definitions, sharing plans and materialized readers.
8
9use super::CteScope;
10use std::sync::Arc;
11use uqa_core::memory::{MemoryReservation, ProductionControl};
12use uqa_sql::{
13    binding::production::{BindingMap, BindingNameSet},
14    plan::{CtePlan, RetainedCtePlan},
15    SQLError,
16};
17
18mod publication;
19use publication::PendingEntry;
20
21#[derive(Default)]
22pub(super) struct DefinitionBindings {
23    rows: super::CteRowsMap,
24    deferred: BindingMap<RetainedCtePlan>,
25    definitions: BindingMap<Arc<Self>>,
26    non_returning: BindingNameSet,
27    folded: BindingNameSet,
28    recursive_widths: BindingMap<usize>,
29    names: BindingNameSet,
30    own_reference: bool,
31    _memory: Option<MemoryReservation>,
32}
33
34impl DefinitionBindings {
35    fn capture<S: Clone>(
36        scope: &CteScope<S>,
37        plan: &CtePlan,
38        control: &ProductionControl<'_>,
39    ) -> Result<Arc<Self>, SQLError> {
40        let names = uqa_sql::semantics::cte_external_references_with_control(
41            &plan.body,
42            scope
43                .rows
44                .keys()
45                .chain(scope.deferred_ctes.keys())
46                .map(String::as_str),
47            *control,
48        )?;
49        let own_reference =
50            uqa_sql::semantics::cte_references_own_name_with_control(plan, *control)?;
51        let mut retained = Self {
52            own_reference,
53            ..Self::default()
54        };
55        for name in names.iter().copied() {
56            control.check()?;
57            if own_reference && name == plan.name {
58                continue;
59            }
60            if let Some(rows) = scope.rows.get(name) {
61                retained
62                    .rows
63                    .insert_with_control(name, rows.clone(), control)?;
64            }
65            if let Some(plan) = scope.deferred_ctes.get(name) {
66                retained
67                    .deferred
68                    .insert_with_control(name, plan.clone(), control)?;
69            }
70            if let Some(definition) = scope.definition_scopes.get(name) {
71                retained
72                    .definitions
73                    .insert_with_control(name, Arc::clone(definition), control)?;
74            }
75            if scope.non_returning_ctes.contains(name) {
76                retained.non_returning.insert_with_control(name, control)?;
77            }
78            if scope.folded_ctes.contains(name) {
79                retained.folded.insert_with_control(name, control)?;
80            }
81            if let Some(width) = scope.recursive_control_widths.get(name) {
82                retained
83                    .recursive_widths
84                    .insert_with_control(name, *width, control)?;
85            }
86            retained.names.insert_with_control(name, control)?;
87        }
88        let memory = control.reserve(size_of::<Self>())?;
89        Ok(Arc::new(Self {
90            _memory: memory,
91            ..retained
92        }))
93    }
94
95    fn scope<S: Clone>(
96        &self,
97        parent: &CteScope<S>,
98        own_plan: Option<&RetainedCtePlan>,
99        control: &ProductionControl<'_>,
100    ) -> Result<CteScope<S>, SQLError> {
101        let mut scope = parent.copy_context_with_control(control)?;
102        scope.rows = self.rows.copy_with_control(control)?;
103        scope.deferred_ctes = self
104            .deferred
105            .copy_with_control(control, |plan| Ok(plan.clone()))?;
106        scope.definition_scopes = self
107            .definitions
108            .copy_with_control(control, |definition| Ok(Arc::clone(definition)))?;
109        scope.non_returning_ctes = self.non_returning.copy_with_control(control)?;
110        scope.folded_ctes = self.folded.copy_with_control(control)?;
111        scope.recursive_control_widths = self
112            .recursive_widths
113            .copy_with_control(control, |width| Ok(*width))?;
114        scope.visible_cte_names = self.names.copy_with_control(control)?;
115        if self.own_reference {
116            if let Some(plan) = own_plan {
117                scope
118                    .deferred_ctes
119                    .insert_with_control(&plan.name, plan.clone(), control)?;
120                scope
121                    .visible_cte_names
122                    .insert_with_control(&plan.name, control)?;
123            }
124        }
125        Ok(scope)
126    }
127}
128
129impl<S: Clone> CteScope<S> {
130    /// Prepare a definition in its original lexical bindings while retaining the invoking statement's catalog, row locks, scalar arena and transaction controls.
131    pub fn definition_scope(&self, reference: &str) -> Option<Self> {
132        self.definition_scope_with_control(reference, &ProductionControl::uncontrolled())
133            .expect("ordinary definition scope")
134    }
135
136    pub fn definition_scope_with_control(
137        &self,
138        reference: &str,
139        control: &ProductionControl<'_>,
140    ) -> Result<Option<Self>, SQLError> {
141        control.check()?;
142        let Some(reference) = uqa_core::RelationIdentity::borrowed_reference(reference)
143            .filter(|reference| reference.schema.is_none())
144        else {
145            return Ok(None);
146        };
147        self.definition_scopes
148            .get_name(reference.name)
149            .map(|retained| {
150                retained.scope(self, self.deferred_ctes.get_name(reference.name), control)
151            })
152            .transpose()
153    }
154
155    /// A declaration already owns its decoded identifier; dots and quotes in that name are not SQL qualification syntax.
156    #[cfg(test)]
157    pub(crate) fn definition_scope_for_name(&self, name: &str) -> Option<Self> {
158        self.definition_scope_for_name_with_control(name, &ProductionControl::uncontrolled())
159            .expect("ordinary decoded definition scope")
160    }
161
162    pub(crate) fn definition_scope_for_name_with_control(
163        &self,
164        name: &str,
165        control: &ProductionControl<'_>,
166    ) -> Result<Option<Self>, SQLError> {
167        control.check()?;
168        self.definition_scopes
169            .get(name)
170            .map(|retained| retained.scope(self, self.deferred_ctes.get(name), control))
171            .transpose()
172    }
173
174    pub(crate) fn insert_preparation_cte(&mut self, plan: RetainedCtePlan, folded: bool) {
175        self.insert_preparation_cte_with_control(plan, folded, &ProductionControl::uncontrolled())
176            .expect("ordinary CTE declaration");
177    }
178
179    /// Prepare every new name, node and selected definition before publishing any part of the declaration. Replacing a key reuses its exact original node.
180    pub(crate) fn insert_preparation_cte_with_control(
181        &mut self,
182        plan: RetainedCtePlan,
183        folded: bool,
184        control: &ProductionControl<'_>,
185    ) -> Result<(), SQLError> {
186        let definition = DefinitionBindings::capture(self, &plan, control)?;
187        let definition =
188            PendingEntry::prepare(&self.definition_scopes, &plan.name, definition, control)?;
189        let deferred =
190            PendingEntry::prepare(&self.deferred_ctes, &plan.name, plan.clone(), control)?;
191        let mut non_returning = BindingNameSet::new();
192        if !plan.body.returns_rows() && !self.non_returning_ctes.contains(&plan.name) {
193            non_returning.insert_with_control(&plan.name, control)?;
194        }
195        let mut folded_names = BindingNameSet::new();
196        if folded && !self.folded_ctes.contains(&plan.name) {
197            folded_names.insert_with_control(&plan.name, control)?;
198        }
199        control.check()?;
200        self.rows.remove(&plan.name);
201        if plan.body.returns_rows() {
202            self.non_returning_ctes.remove(&plan.name);
203        }
204        self.non_returning_ctes.append(non_returning);
205        if !folded {
206            self.folded_ctes.remove(&plan.name);
207        }
208        self.folded_ctes.append(folded_names);
209        definition.publish(&mut self.definition_scopes, &plan.name);
210        deferred.publish(&mut self.deferred_ctes, &plan.name);
211        Ok(())
212    }
213
214    pub fn insert_deferred_with_control(
215        &mut self,
216        plan: RetainedCtePlan,
217        control: &ProductionControl<'_>,
218    ) -> Result<(), SQLError> {
219        self.insert_preparation_cte_with_control(plan, true, control)
220    }
221
222    pub(crate) fn cte_is_folded(&self, name: &str) -> bool {
223        uqa_core::RelationIdentity::borrowed_reference(name).is_some_and(|reference| {
224            reference.schema.is_none() && self.folded_ctes.contains_name(reference.name)
225        })
226    }
227
228    #[cfg(test)]
229    pub(crate) fn deferred_input(&self, name: &str) -> Option<(RetainedCtePlan, Self)> {
230        self.deferred_input_with_control(name, &ProductionControl::uncontrolled())
231            .expect("ordinary deferred input")
232    }
233
234    pub(crate) fn deferred_input_with_control(
235        &self,
236        name: &str,
237        control: &ProductionControl<'_>,
238    ) -> Result<Option<(RetainedCtePlan, Self)>, SQLError> {
239        Ok(self
240            .definition_scope_with_control(name, control)?
241            .and_then(|scope| self.deferred_for_scan(name).map(|plan| (plan, scope))))
242    }
243}