Skip to main content

uqa_execution/query/scope/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Native scope capture admits its new immutable namespace, shared execution state and lexical row names before construction.
8
9use super::{BindingMap, BindingNameSet, CteScope, LockIdentityOptions};
10mod copying;
11use crate::{catalog::CatalogReadView, query::cte::rows::CteRows};
12use std::{
13    collections::BTreeMap,
14    sync::{atomic::AtomicU64, Arc},
15};
16use uqa_core::memory::{Produced, ProductionControl};
17use uqa_sql::{catalog::resolution::RelationNameResolution, SQLError};
18
19mod ctes;
20pub(super) mod resolution;
21mod rows;
22pub(super) mod subject;
23pub use rows::{CteRowsIter, CteRowsMap};
24
25pub(in crate::query::scope) fn shared<T>(
26    value: T,
27    control: &ProductionControl<'_>,
28) -> Result<Arc<Produced<T>>, SQLError> {
29    Ok(control
30        .finish(value, control.empty_reservation())?
31        .into_shared(control)?)
32}
33
34impl<S: Clone> CteScope<S> {
35    pub(super) fn empty_with_control(control: &ProductionControl<'_>) -> Result<Self, SQLError> {
36        control.check()?;
37        Ok(Self {
38            producers: super::producers::CteProducers::with_control(control)?,
39            rows: CteRowsMap::new(),
40            deferred_ctes: BindingMap::new(),
41            definition_scopes: BindingMap::new(),
42            folded_ctes: BindingNameSet::new(),
43            non_returning_ctes: BindingNameSet::new(),
44            scalar_subqueries: uqa_sql::plan::RetainedQueryArena::default(),
45            source_outer_rewrites: None,
46            lock_identities: LockIdentityOptions::default(),
47            row_lock: None,
48            visible_cte_names: BindingNameSet::new(),
49            recursive_control_widths: BindingMap::new(),
50            scalar_subquery_arena: 0,
51            read_command_overlay: true,
52            stream_command_progress: false,
53            scan_backwards: false,
54            next_scalar_subquery_arena: shared(AtomicU64::new(1), control)?,
55            scalar_subquery_cache: shared(parking_lot::Mutex::new(BTreeMap::new()), control)?,
56            catalog: None,
57            catalog_revision: None,
58            catalog_resolution: None,
59            privilege_subject: None,
60            command_cte_snapshot: None,
61            statement_commands: None,
62        })
63    }
64
65    /// Capture the current routine's immutable statement inputs. The catalog already owns its generation; new namespace and execution-state payloads keep their own shared leases.
66    pub fn with_catalog_with_control(
67        catalog: CatalogReadView,
68        resolution: Produced<RelationNameResolution>,
69        control: &ProductionControl<'_>,
70    ) -> Result<Self, SQLError> {
71        control.check()?;
72        let resolution = resolution::ScopeResolution::capture(resolution, control)?;
73        let mut scope = Self::empty_with_control(control)?;
74        scope.catalog = Some(catalog);
75        scope.catalog_resolution = Some(resolution);
76        Ok(scope)
77    }
78
79    /// Replace relation authority only after its complete private reference has been admitted. SQL-visible `current_user` and namespace stay in their original owner.
80    pub fn set_privilege_subject_with_control(
81        &mut self,
82        subject: Option<&uqa_sql::catalog::roles::RoleReference>,
83        control: &ProductionControl<'_>,
84    ) -> Result<(), SQLError> {
85        control.check()?;
86        let subject = subject
87            .map(|subject| subject::ScopeSubject::capture(subject, control))
88            .transpose()?;
89        self.privilege_subject = subject;
90        Ok(())
91    }
92
93    pub fn relation_name_resolution_with_control(
94        &self,
95        control: &ProductionControl<'_>,
96    ) -> Result<Produced<RelationNameResolution>, SQLError> {
97        control.check()?;
98        self.name_resolution()?.copy_with_control(control)
99    }
100
101    /// Retain a preexisting transition materialization, admitting only its new lexical name and map node. Replacing the same name reuses its existing identity allocation.
102    pub fn insert_shared_with_control(
103        &mut self,
104        name: &str,
105        rows: crate::SharedSpill,
106        control: &ProductionControl<'_>,
107    ) -> Result<(), SQLError> {
108        self.insert_materialized_with_control(name, rows, true, control)
109    }
110
111    /// Publish materialized rows and their command visibility together after all new name storage is admitted.
112    pub fn insert_materialized_with_control(
113        &mut self,
114        name: &str,
115        rows: crate::SharedSpill,
116        returns_rows: bool,
117        control: &ProductionControl<'_>,
118    ) -> Result<(), SQLError> {
119        let mut non_returning = BindingNameSet::new();
120        if !returns_rows && !self.non_returning_ctes.contains(name) {
121            non_returning.insert_with_control(name, control)?;
122        }
123        self.rows
124            .insert_with_control(name, CteRows::Complete(rows), control)?;
125        self.deferred_ctes.remove(name);
126        self.definition_scopes.remove(name);
127        self.folded_ctes.remove(name);
128        if returns_rows {
129            self.non_returning_ctes.remove(name);
130        }
131        self.non_returning_ctes.append(non_returning);
132        Ok(())
133    }
134}
135
136#[cfg(test)]
137mod tests;
138
139#[cfg(test)]
140mod lexical_tests;