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;
14use std::sync::{atomic::AtomicU64, Arc};
15use uqa_core::memory::{Produced, ProductionControl};
16use uqa_sql::binding::production::{BindingMap, BindingNameSet};
17use uqa_sql::catalog::resolution::{RelationLookupMode, RelationNameResolution};
18use uqa_sql::catalog::roles::RoleReference;
19use uqa_sql::SQLError;
20
21pub(crate) mod binding;
22mod cte;
23mod definitions;
24mod producers;
25mod production;
26mod recursive;
27pub use production::{CteRowsIter, CteRowsMap};
28#[cfg(test)]
29mod query_arenas;
30#[cfg(test)]
31mod retained_plans;
32mod row_locks;
33mod statement_commands;
34pub mod subqueries;
35use row_locks::RowLockScopeState;
36pub use row_locks::{LockIdentityOptions, ResolvedRowLock, SelectedRowLock};
37pub use statement_commands::StatementCommands;
38use subqueries::ScalarSubqueryCacheEntry;
39
40type SourceOuterRewrites =
41    Arc<uqa_core::memory::Produced<Vec<uqa_sql::semantics::view_rewrite::DeferredOuterRewrite>>>;
42
43type ScalarSubqueryCache = parking_lot::Mutex<BTreeMap<(u64, usize), ScalarSubqueryCacheEntry>>;
44
45#[derive(Clone)]
46pub struct CteScope<S: Clone = ()> {
47    producers: producers::CteProducers,
48    pub rows: CteRowsMap,
49    deferred_ctes: BindingMap<uqa_sql::plan::RetainedCtePlan>,
50    definition_scopes: BindingMap<Arc<definitions::DefinitionBindings>>,
51    folded_ctes: BindingNameSet,
52    pub non_returning_ctes: BindingNameSet,
53    pub scalar_subqueries: uqa_sql::plan::RetainedQueryArena,
54    pub(crate) source_outer_rewrites: Option<SourceOuterRewrites>,
55    pub lock_identities: LockIdentityOptions,
56    row_lock: Option<RowLockScopeState>,
57    visible_cte_names: BindingNameSet,
58    recursive_control_widths: BindingMap<usize>,
59    scalar_subquery_arena: u64,
60    read_command_overlay: bool,
61    stream_command_progress: bool,
62    scan_backwards: bool,
63    next_scalar_subquery_arena: Arc<Produced<AtomicU64>>,
64    scalar_subquery_cache: Arc<Produced<ScalarSubqueryCache>>,
65    catalog: Option<CatalogReadView>,
66    catalog_revision: Option<(u64, u64)>,
67    catalog_resolution: Option<production::resolution::ScopeResolution>,
68    privilege_subject: Option<production::subject::ScopeSubject>,
69    command_cte_snapshot: Option<Arc<S>>,
70    /// The commands of the statement this scope belongs to, shared by every scope of the statement.
71    statement_commands: Option<Arc<StatementCommands>>,
72}
73
74impl<S: Clone> Default for CteScope<S> {
75    fn default() -> Self {
76        Self::empty_with_control(&ProductionControl::uncontrolled())
77            .expect("uncontrolled query scope construction")
78    }
79}
80
81impl<S: Clone> CteScope<S> {
82    /// Bind immutable statement metadata while keeping the snapshot payload owned by the caller.
83    pub fn with_catalog(
84        catalog: CatalogReadView,
85        resolution: RelationNameResolution,
86        privilege_subject: Option<RoleReference>,
87    ) -> Self {
88        Self {
89            catalog: Some(catalog),
90            catalog_resolution: Some(resolution.into()),
91            privilege_subject: privilege_subject.map(Into::into),
92            ..Self::default()
93        }
94    }
95
96    pub fn set_reads_command_overlay(&mut self, enabled: bool) {
97        self.read_command_overlay = enabled;
98    }
99
100    pub fn set_relation_lookup_mode(&mut self, mode: RelationLookupMode) -> Result<(), SQLError> {
101        self.catalog_resolution
102            .as_mut()
103            .ok_or_else(|| {
104                SQLError::Internal(
105                    "query execution scope has no statement name-resolution snapshot".into(),
106                )
107            })?
108            .set_lookup_mode(mode);
109        Ok(())
110    }
111
112    pub fn cached_subquery(&self, slot: usize) -> Option<ScalarSubqueryCacheEntry> {
113        self.scalar_subquery_cache
114            .lock()
115            .get(&(self.scalar_subquery_arena, slot))
116            .cloned()
117    }
118
119    pub fn cache_subquery(&self, slot: usize, entry: ScalarSubqueryCacheEntry) {
120        self.scalar_subquery_cache
121            .lock()
122            .insert((self.scalar_subquery_arena, slot), entry);
123    }
124
125    pub fn new() -> Self {
126        Self::default()
127    }
128
129    pub fn catalog_read_view(&self) -> Result<CatalogReadView, SQLError> {
130        self.catalog.clone().ok_or_else(|| {
131            SQLError::Internal("query execution scope has no statement catalog snapshot".into())
132        })
133    }
134
135    /// Record the caller's source identity and invalidation revision when it captures the catalog, independently of the immutable binding view.
136    pub fn set_catalog_revision(&mut self, source: u64, revision: u64) {
137        self.catalog_revision = Some((source, revision));
138    }
139
140    pub fn catalog_revision(&self) -> Option<(u64, u64)> {
141        self.catalog_revision
142    }
143
144    pub fn relation_name_resolution(&self) -> Result<RelationNameResolution, SQLError> {
145        Ok(self.name_resolution()?.snapshot())
146    }
147
148    fn name_resolution(&self) -> Result<&production::resolution::ScopeResolution, SQLError> {
149        self.catalog_resolution.as_ref().ok_or_else(|| {
150            SQLError::Internal(
151                "query execution scope has no statement name-resolution snapshot".into(),
152            )
153        })
154    }
155
156    pub(crate) fn relation_lookup_mode(
157        &self,
158    ) -> Option<uqa_sql::catalog::resolution::RelationLookupMode> {
159        self.catalog_resolution
160            .as_ref()
161            .map(production::resolution::ScopeResolution::lookup_mode)
162    }
163
164    pub fn privilege_subject(&self) -> Result<&RoleReference, SQLError> {
165        if let Some(subject) = self.privilege_subject.as_ref() {
166            return Ok(subject);
167        }
168        self.invoking_role()
169    }
170
171    /// The statement's invoking identity is independent of relation-owner overrides in enclosing views.
172    pub fn invoking_role(&self) -> Result<&RoleReference, SQLError> {
173        self.catalog_resolution
174            .as_ref()
175            .map(|resolution| resolution.current_user())
176            .ok_or_else(|| {
177                SQLError::Internal(
178                    "query execution scope has no statement authorization subject".into(),
179                )
180            })
181    }
182}
183
184pub use uqa_sql::semantics::expr_contains_subquery;
185
186#[cfg(test)]
187mod tests {
188    use super::{expr_contains_subquery, CteScope};
189    use crate::ScalarExpr;
190    use crate::ScalarFrameBound;
191    use uqa_sql::ast::{FrameExclusion, FrameMode};
192
193    #[test]
194    fn query_scope_restores_relation_authority_and_namespace_after_unwind() {
195        use uqa_sql::catalog::resolution::{RelationLookupMode, RelationNameResolution};
196        let uqa_sql::plan::UnifiedPlan::Query(mut query) =
197            uqa_sql::plan::UnifiedPlan::lower(uqa_sql::compile("SELECT 1").unwrap().remove(0))
198        else {
199            panic!("query")
200        };
201        query.relation_privilege_subject = Some("caller".into());
202        let mut scope = CteScope::<()>::new();
203        scope.privilege_subject = Some("action_owner".into());
204        scope.catalog_resolution = Some(
205            RelationNameResolution {
206                search_path: vec!["public".into()],
207                temporary_schema: "pg_temp_1".into(),
208                temporary_namespace_allocated: false,
209                current_user: "caller".into(),
210                lookup_mode: RelationLookupMode::Bound,
211            }
212            .into(),
213        );
214        let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
215            let current = scope.enter_query_plan_scope(&query).unwrap();
216            assert_eq!(current.privilege_subject().unwrap(), &"caller".into());
217            let resolution = current.relation_name_resolution().unwrap();
218            assert_eq!(resolution.lookup_mode, RelationLookupMode::Dynamic);
219            assert_eq!(resolution.current_user, "caller".into());
220            panic!("query failed while retaining caller authority");
221        }));
222        assert!(unwind.is_err());
223        assert_eq!(scope.privilege_subject().unwrap(), &"action_owner".into());
224        assert_eq!(
225            scope.relation_name_resolution().unwrap().lookup_mode,
226            RelationLookupMode::Bound
227        );
228    }
229
230    #[test]
231    fn empty_row_lock_scopes_leave_non_locking_state_unallocated() {
232        let mut ctes = CteScope::<()>::new();
233        {
234            let _scope = ctes.enter_source_row_locks(Vec::new());
235        }
236        assert!(ctes.row_lock.is_none());
237        {
238            let _scope = ctes.enter_recheck_storage_pins("plain_source");
239        }
240        assert!(ctes.row_lock.is_none());
241    }
242
243    #[test]
244    fn scalar_ir_detects_subqueries_in_window_frame_bounds() {
245        let expression = ScalarExpr::WindowCall {
246            name: "sum".into(),
247            args: vec![ScalarExpr::Column("amount".into())],
248            spec: crate::ScalarWindowSpec {
249                definition: None,
250                partition_by: Vec::new(),
251                order_by: Vec::new(),
252                frame: Some(crate::ScalarWindowFrame {
253                    mode: FrameMode::Rows,
254                    start: ScalarFrameBound::Preceding(Box::new(ScalarExpr::ScalarSubquery(0))),
255                    end: ScalarFrameBound::CurrentRow,
256                    between: true,
257                    exclusion: FrameExclusion::NoOthers,
258                }),
259            },
260            filter: None,
261            modifiers: uqa_sql::ast::WindowCallModifiers::default(),
262        };
263        assert!(expr_contains_subquery(&expression));
264    }
265    #[test]
266    fn scalar_subquery_scope_restores_the_parent_arena_after_unwind() {
267        use uqa_sql::plan::UnifiedPlan;
268
269        let statement = uqa_sql::compile("SELECT 1")
270            .unwrap()
271            .into_iter()
272            .next()
273            .unwrap();
274        let UnifiedPlan::Query(query) = UnifiedPlan::lower(statement) else {
275            panic!("SELECT must lower to a query plan");
276        };
277        let query = *query;
278        let mut scope = CteScope::<()>::new();
279        scope.scalar_subqueries = vec![query.clone()].into();
280
281        let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
282            let _guard = scope.enter_scalar_subqueries(&[query.clone(), query]);
283            panic!("exercise scalar-subquery scope cleanup");
284        }));
285
286        assert!(unwind.is_err());
287        assert_eq!(scope.scalar_subqueries.len(), 1);
288    }
289}
290
291pub mod bindings;