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