Skip to main content

uqa_execution/query/
scope.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Statement-scoped CTE buffers, subquery arenas, and tuple recheck state.
8
9use crate::catalog::CatalogReadView;
10use crate::row_locks::recheck::{
11    recheck_storage_names_match, RecheckDoc, RecheckSourceRow, RowLockRecheckPins,
12};
13use std::collections::{BTreeMap, BTreeSet};
14use std::sync::{atomic::AtomicU64, Arc};
15use uqa_sql::catalog::resolution::{RelationLookupMode, RelationNameResolution};
16use uqa_sql::catalog::roles::RoleReference;
17use uqa_sql::plan::{CtePlan, QueryPlan};
18use uqa_sql::SQLError;
19
20mod cte;
21#[cfg(test)]
22mod retained_plans;
23mod row_locks;
24mod statement_commands;
25pub mod subqueries;
26use row_locks::RowLockScopeState;
27pub use row_locks::{LockIdentityOptions, ResolvedRowLock};
28pub use statement_commands::StatementCommands;
29use subqueries::ScalarSubqueryCacheEntry;
30
31#[derive(Clone)]
32pub struct CteScope<S: Clone = ()> {
33    pub rows: BTreeMap<String, crate::SharedSpill>,
34    deferred_ctes: BTreeMap<String, Arc<CtePlan>>,
35    pub non_returning_ctes: BTreeSet<String>,
36    pub scalar_subqueries: Arc<[QueryPlan]>,
37    pub lock_identities: LockIdentityOptions,
38    row_lock: Option<Box<RowLockScopeState>>,
39    visible_cte_names: BTreeSet<String>,
40    recursive_control_widths: BTreeMap<String, usize>,
41    scalar_subquery_arena: u64,
42    read_command_overlay: bool,
43    stream_command_progress: bool,
44    scan_backwards: bool,
45    next_scalar_subquery_arena: Arc<AtomicU64>,
46    scalar_subquery_cache:
47        Arc<parking_lot::Mutex<BTreeMap<(u64, usize), ScalarSubqueryCacheEntry>>>,
48    catalog: Option<CatalogReadView>,
49    catalog_revision: Option<(u64, u64)>,
50    catalog_resolution: Option<RelationNameResolution>,
51    privilege_subject: Option<RoleReference>,
52    command_cte_snapshot: Option<Arc<S>>,
53    /// The commands of the statement this scope belongs to, shared by every scope of the statement.
54    statement_commands: Option<Arc<StatementCommands>>,
55}
56
57impl<S: Clone> Default for CteScope<S> {
58    fn default() -> Self {
59        Self {
60            rows: BTreeMap::new(),
61            deferred_ctes: BTreeMap::new(),
62            non_returning_ctes: BTreeSet::new(),
63            scalar_subqueries: Arc::default(),
64            lock_identities: LockIdentityOptions::default(),
65            row_lock: None,
66            visible_cte_names: BTreeSet::new(),
67            recursive_control_widths: BTreeMap::new(),
68            scalar_subquery_arena: 0,
69            read_command_overlay: true,
70            stream_command_progress: false,
71            scan_backwards: false,
72            next_scalar_subquery_arena: Arc::new(AtomicU64::new(1)),
73            scalar_subquery_cache: Arc::new(parking_lot::Mutex::new(BTreeMap::new())),
74            catalog: None,
75            catalog_revision: None,
76            catalog_resolution: None,
77            privilege_subject: None,
78            command_cte_snapshot: None,
79            statement_commands: None,
80        }
81    }
82}
83
84impl<S: Clone> CteScope<S> {
85    /// Bind immutable statement metadata while keeping the snapshot payload owned by the caller.
86    pub fn with_catalog(
87        catalog: CatalogReadView,
88        resolution: RelationNameResolution,
89        privilege_subject: Option<RoleReference>,
90    ) -> Self {
91        Self {
92            catalog: Some(catalog),
93            catalog_resolution: Some(resolution),
94            privilege_subject,
95            ..Self::default()
96        }
97    }
98
99    pub fn set_reads_command_overlay(&mut self, enabled: bool) {
100        self.read_command_overlay = enabled;
101    }
102
103    pub fn set_relation_lookup_mode(&mut self, mode: RelationLookupMode) -> Result<(), SQLError> {
104        self.catalog_resolution
105            .as_mut()
106            .ok_or_else(|| {
107                SQLError::Internal(
108                    "query execution scope has no statement name-resolution snapshot".into(),
109                )
110            })?
111            .set_lookup_mode(mode);
112        Ok(())
113    }
114
115    pub fn cached_subquery(&self, slot: usize) -> Option<ScalarSubqueryCacheEntry> {
116        self.scalar_subquery_cache
117            .lock()
118            .get(&(self.scalar_subquery_arena, slot))
119            .cloned()
120    }
121
122    pub fn cache_subquery(&self, slot: usize, entry: ScalarSubqueryCacheEntry) {
123        self.scalar_subquery_cache
124            .lock()
125            .insert((self.scalar_subquery_arena, slot), entry);
126    }
127
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    pub fn catalog_read_view(&self) -> Result<CatalogReadView, SQLError> {
133        self.catalog.clone().ok_or_else(|| {
134            SQLError::Internal("query execution scope has no statement catalog snapshot".into())
135        })
136    }
137
138    /// Record the caller's source identity and invalidation revision when it captures the catalog, independently of the immutable binding view.
139    pub fn set_catalog_revision(&mut self, source: u64, revision: u64) {
140        self.catalog_revision = Some((source, revision));
141    }
142
143    pub fn catalog_revision(&self) -> Option<(u64, u64)> {
144        self.catalog_revision
145    }
146
147    pub fn relation_name_resolution(&self) -> Result<RelationNameResolution, SQLError> {
148        self.catalog_resolution.clone().ok_or_else(|| {
149            SQLError::Internal(
150                "query execution scope has no statement name-resolution snapshot".into(),
151            )
152        })
153    }
154
155    pub fn privilege_subject(&self) -> Result<&RoleReference, SQLError> {
156        if let Some(subject) = self.privilege_subject.as_ref() {
157            return Ok(subject);
158        }
159        self.catalog_resolution
160            .as_ref()
161            .map(RelationNameResolution::current_user)
162            .ok_or_else(|| {
163                SQLError::Internal(
164                    "query execution scope has no statement authorization subject".into(),
165                )
166            })
167    }
168}
169
170pub use uqa_sql::semantics::expr_contains_subquery;
171
172#[cfg(test)]
173mod tests {
174    use super::{expr_contains_subquery, CteScope};
175    use crate::ScalarExpr;
176    use crate::ScalarFrameBound;
177    use uqa_sql::ast::{FrameExclusion, FrameMode};
178
179    #[test]
180    fn empty_row_lock_scopes_leave_non_locking_state_unallocated() {
181        let mut ctes = CteScope::<()>::new();
182        {
183            let _scope = ctes.enter_source_row_locks(Vec::new());
184        }
185        assert!(ctes.row_lock.is_none());
186        {
187            let _scope = ctes.enter_recheck_storage_pins("plain_source");
188        }
189        assert!(ctes.row_lock.is_none());
190    }
191
192    #[test]
193    fn scalar_ir_detects_subqueries_in_window_frame_bounds() {
194        let expression = ScalarExpr::WindowCall {
195            name: "sum".into(),
196            args: vec![ScalarExpr::Column("amount".into())],
197            spec: crate::ScalarWindowSpec {
198                definition: None,
199                partition_by: Vec::new(),
200                order_by: Vec::new(),
201                frame: Some(crate::ScalarWindowFrame {
202                    mode: FrameMode::Rows,
203                    start: ScalarFrameBound::Preceding(Box::new(ScalarExpr::ScalarSubquery(0))),
204                    end: ScalarFrameBound::CurrentRow,
205                    between: true,
206                    exclusion: FrameExclusion::NoOthers,
207                }),
208            },
209            filter: None,
210            modifiers: uqa_sql::ast::WindowCallModifiers::default(),
211        };
212        assert!(expr_contains_subquery(&expression));
213    }
214    #[test]
215    fn scalar_subquery_scope_restores_the_parent_arena_after_unwind() {
216        use uqa_sql::plan::UnifiedPlan;
217
218        let statement = uqa_sql::compile("SELECT 1")
219            .unwrap()
220            .into_iter()
221            .next()
222            .unwrap();
223        let UnifiedPlan::Query(query) = UnifiedPlan::lower(statement) else {
224            panic!("SELECT must lower to a query plan");
225        };
226        let query = *query;
227        let mut scope = CteScope::<()>::new();
228        scope.scalar_subqueries = vec![query.clone()].into();
229
230        let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
231            let _guard = scope.enter_scalar_subqueries(&[query.clone(), query]);
232            panic!("exercise scalar-subquery scope cleanup");
233        }));
234
235        assert!(unwind.is_err());
236        assert_eq!(scope.scalar_subqueries.len(), 1);
237    }
238}
239
240pub mod bindings;