Skip to main content

uqa_execution/query/scope/
cte.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! CTE lifetime, visibility, and scalar-subquery arena scopes.
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::sync::{atomic::Ordering, Arc};
11use uqa_sql::catalog::roles::RoleReference;
12
13use uqa_sql::plan::{CtePlan, QueryPlan};
14use uqa_sql::SQLError;
15
16use super::{CteScope, LockIdentityOptions};
17use uqa_sql::catalog::resolution::RelationLookupMode;
18
19impl<S: Clone> CteScope<S> {
20    pub fn command_cte_snapshot(&self) -> Option<std::sync::Arc<S>> {
21        self.command_cte_snapshot.clone()
22    }
23
24    pub fn set_command_cte_snapshot(&mut self, snapshot: Option<std::sync::Arc<S>>) {
25        self.command_cte_snapshot = snapshot;
26    }
27
28    /// Make this scope part of the statement whose commands `commands` holds.
29    pub fn set_statement_commands(&mut self, commands: std::sync::Arc<super::StatementCommands>) {
30        self.statement_commands = Some(commands);
31    }
32
33    /// The commands of the statement this scope belongs to.
34    pub fn statement_commands(&self) -> Option<&std::sync::Arc<super::StatementCommands>> {
35        self.statement_commands.as_ref()
36    }
37
38    /// Whether a command of the statement this scope belongs to wrote `row`. A later command finds the row's earlier version in its snapshot, which `PostgreSQL` reports as `TM_SelfModified` because the statement's command id already modified it.
39    pub fn statement_wrote(
40        &self,
41        row: &crate::mutation::candidate::PhysicalDocumentIdentity,
42    ) -> bool {
43        self.statement_commands
44            .as_ref()
45            .is_some_and(|commands| commands.wrote(row))
46    }
47
48    /// Whether a statement that the statement this scope belongs to started wrote `row`, which `PostgreSQL` finds modified under a later command id.
49    pub fn statement_triggered_write(
50        &self,
51        row: &crate::mutation::candidate::PhysicalDocumentIdentity,
52    ) -> bool {
53        self.statement_commands
54            .as_ref()
55            .is_some_and(|commands| commands.triggered_write(row))
56    }
57
58    pub fn inherit_cte_bindings(&mut self, parent: &Self) {
59        self.rows.clone_from(&parent.rows);
60        self.deferred_ctes.clone_from(&parent.deferred_ctes);
61        self.non_returning_ctes
62            .clone_from(&parent.non_returning_ctes);
63        self.visible_cte_names.clone_from(&parent.visible_cte_names);
64        self.recursive_control_widths
65            .clone_from(&parent.recursive_control_widths);
66        self.command_cte_snapshot
67            .clone_from(&parent.command_cte_snapshot);
68        self.statement_commands
69            .clone_from(&parent.statement_commands);
70        if self.privilege_subject.is_none() {
71            self.privilege_subject.clone_from(&parent.privilege_subject);
72        }
73    }
74
75    /// Override only relation privilege checks while preserving SQL-visible `current_user` and the caller's namespace.
76    pub fn enter_privilege_subject(
77        &mut self,
78        subject: RoleReference,
79    ) -> PrivilegeSubjectScope<'_, S> {
80        let previous = self.privilege_subject.replace(subject);
81        PrivilegeSubjectScope {
82            ctes: self,
83            previous,
84        }
85    }
86
87    /// Select the namespace semantics owned by one query plan and restore the parent plan's mode on every exit path.
88    pub fn enter_relation_lookup_mode(
89        &mut self,
90        relations_bound: bool,
91    ) -> Result<RelationLookupScope<'_, S>, SQLError> {
92        let resolution = self.catalog_resolution.as_mut().ok_or_else(|| {
93            SQLError::Internal(
94                "query execution scope has no statement name-resolution snapshot".into(),
95            )
96        })?;
97        let lookup_mode = if relations_bound {
98            RelationLookupMode::Bound
99        } else {
100            RelationLookupMode::Dynamic
101        };
102        let previous = resolution.set_lookup_mode(lookup_mode);
103        Ok(RelationLookupScope {
104            ctes: self,
105            previous,
106        })
107    }
108
109    pub fn insert_shared(&mut self, name: String, rows: crate::SharedSpill) {
110        self.deferred_ctes.remove(&name);
111        self.non_returning_ctes.remove(&name);
112        self.rows.insert(name, rows);
113    }
114
115    pub fn insert_deferred(&mut self, plan: CtePlan) {
116        self.rows.remove(&plan.name);
117        if plan.body.returns_rows() {
118            self.non_returning_ctes.remove(&plan.name);
119        } else {
120            self.non_returning_ctes.insert(plan.name.clone());
121        }
122        self.deferred_ctes.insert(plan.name.clone(), Arc::new(plan));
123    }
124
125    pub fn remove_deferred(&mut self, name: &str) -> Option<CtePlan> {
126        self.non_returning_ctes.remove(name);
127        self.deferred_ctes.remove(name).map(Arc::unwrap_or_clone)
128    }
129
130    /// Return one deferred CTE for a scan. `NOT MATERIALIZED` definitions remain available so every syntactic reference is independently folded, while the default single-reference fast path is consumed exactly once.
131    pub fn deferred_for_scan(&mut self, name: &str) -> Option<CtePlan> {
132        let name = uqa_sql::semantics::cte_reference_name(name)?;
133        let persistent = self.deferred_ctes.get(&name).is_some_and(|plan| {
134            plan.materialization == uqa_sql::ast::CteMaterialization::NotMaterialized
135        });
136        let plan = if persistent {
137            self.deferred_ctes.get(&name).cloned()
138        } else {
139            self.deferred_ctes.remove(&name)
140        };
141        plan.map(Arc::unwrap_or_clone)
142    }
143
144    pub fn materialized_for_scan(&self, reference: &str) -> Option<crate::SharedSpill> {
145        self.rows
146            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
147            .cloned()
148    }
149
150    pub fn deferred_reference(&self, reference: &str) -> Option<&CtePlan> {
151        self.deferred_ctes
152            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
153            .map(Arc::as_ref)
154    }
155
156    pub fn deferred_ctes(&self) -> &BTreeMap<String, Arc<CtePlan>> {
157        &self.deferred_ctes
158    }
159
160    pub fn recursive_control_width(&self, name: &str) -> Option<usize> {
161        self.recursive_control_widths.get(name).copied()
162    }
163
164    pub fn set_recursive_control_width(&mut self, name: String, width: usize) -> Option<usize> {
165        self.recursive_control_widths.insert(name, width)
166    }
167
168    pub fn restore_recursive_control_width(&mut self, name: &str, previous: Option<usize>) {
169        match previous {
170            Some(width) => {
171                self.recursive_control_widths
172                    .insert(name.to_string(), width);
173            }
174            None => {
175                self.recursive_control_widths.remove(name);
176            }
177        }
178    }
179
180    pub fn remove_materialized(&mut self, name: &str) -> Option<crate::SharedSpill> {
181        self.non_returning_ctes.remove(name);
182        self.rows.remove(name)
183    }
184
185    /// Bind the scalar-subquery arena owned by one query block. The guard restores the parent arena on success, error, or panic so nested and lateral query execution cannot resolve a child slot in its parent.
186    pub fn enter_scalar_subqueries(
187        &mut self,
188        subqueries: &[QueryPlan],
189    ) -> ScalarSubqueryScope<'_, S> {
190        let previous = std::mem::replace(&mut self.scalar_subqueries, subqueries.into());
191        let next_arena = self
192            .next_scalar_subquery_arena
193            .fetch_add(1, Ordering::Relaxed);
194        let previous_arena = std::mem::replace(&mut self.scalar_subquery_arena, next_arena);
195        let previous_lock_identities = self.lock_identities;
196        ScalarSubqueryScope {
197            ctes: self,
198            previous: Some(previous),
199            previous_arena,
200            previous_lock_identities,
201        }
202    }
203
204    pub fn enter_visible_ctes<'a>(
205        &'a mut self,
206        names: impl IntoIterator<Item = &'a str>,
207    ) -> VisibleCteScope<'a, S> {
208        let previous = std::mem::take(&mut self.visible_cte_names);
209        self.visible_cte_names.clone_from(&previous);
210        self.visible_cte_names
211            .extend(names.into_iter().map(str::to_owned));
212        VisibleCteScope {
213            ctes: self,
214            previous: Some(previous),
215        }
216    }
217
218    /// Whether `name` resolves to a CTE in this scope: a name declared by an enclosing query's WITH list, or one whose rows or deferred plan are bound in the scope, which is how a DML statement's own WITH list reaches the query it drives.
219    pub fn is_visible_cte(&self, name: &str) -> bool {
220        uqa_sql::semantics::cte_reference_name(name).is_some_and(|name| {
221            self.visible_cte_names.contains(&name)
222                || self.rows.contains_key(&name)
223                || self.deferred_ctes.contains_key(&name)
224        })
225    }
226
227    pub fn returning_statement_snapshot_scope(&self) -> Self {
228        let mut scope = self.clone();
229        scope.read_command_overlay = false;
230        scope
231    }
232
233    pub fn reads_command_overlay(&self) -> bool {
234        self.read_command_overlay
235    }
236
237    pub fn enable_command_progress_streaming(&mut self) {
238        self.stream_command_progress = true;
239    }
240
241    pub fn streams_command_progress(&self) -> bool {
242        self.stream_command_progress
243    }
244
245    pub fn enable_backwards_scanning(&mut self) {
246        self.scan_backwards = true;
247    }
248
249    pub fn scans_backwards(&self) -> bool {
250        self.scan_backwards
251    }
252}
253
254pub struct PrivilegeSubjectScope<'a, S: Clone> {
255    ctes: &'a mut CteScope<S>,
256    previous: Option<RoleReference>,
257}
258
259impl<S: Clone> std::ops::Deref for PrivilegeSubjectScope<'_, S> {
260    type Target = CteScope<S>;
261
262    fn deref(&self) -> &Self::Target {
263        self.ctes
264    }
265}
266
267impl<S: Clone> std::ops::DerefMut for PrivilegeSubjectScope<'_, S> {
268    fn deref_mut(&mut self) -> &mut Self::Target {
269        self.ctes
270    }
271}
272
273impl<S: Clone> Drop for PrivilegeSubjectScope<'_, S> {
274    fn drop(&mut self) {
275        self.ctes.privilege_subject = self.previous.take();
276    }
277}
278
279pub struct RelationLookupScope<'a, S: Clone> {
280    ctes: &'a mut CteScope<S>,
281    previous: RelationLookupMode,
282}
283
284impl<S: Clone> std::ops::Deref for RelationLookupScope<'_, S> {
285    type Target = CteScope<S>;
286
287    fn deref(&self) -> &Self::Target {
288        self.ctes
289    }
290}
291
292impl<S: Clone> std::ops::DerefMut for RelationLookupScope<'_, S> {
293    fn deref_mut(&mut self) -> &mut Self::Target {
294        self.ctes
295    }
296}
297
298impl<S: Clone> Drop for RelationLookupScope<'_, S> {
299    fn drop(&mut self) {
300        let resolution = self
301            .ctes
302            .catalog_resolution
303            .as_mut()
304            .expect("relation lookup scope lost its statement resolution");
305        resolution.set_lookup_mode(self.previous);
306    }
307}
308
309pub struct ScalarSubqueryScope<'a, S: Clone> {
310    ctes: &'a mut CteScope<S>,
311    previous: Option<Arc<[QueryPlan]>>,
312    previous_arena: u64,
313    previous_lock_identities: LockIdentityOptions,
314}
315
316impl<S: Clone> std::ops::Deref for ScalarSubqueryScope<'_, S> {
317    type Target = CteScope<S>;
318
319    fn deref(&self) -> &Self::Target {
320        self.ctes
321    }
322}
323
324impl<S: Clone> std::ops::DerefMut for ScalarSubqueryScope<'_, S> {
325    fn deref_mut(&mut self) -> &mut Self::Target {
326        self.ctes
327    }
328}
329
330impl<S: Clone> Drop for ScalarSubqueryScope<'_, S> {
331    fn drop(&mut self) {
332        if let Some(previous) = self.previous.take() {
333            self.ctes.scalar_subqueries = previous;
334            self.ctes.scalar_subquery_arena = self.previous_arena;
335            self.ctes.lock_identities = self.previous_lock_identities;
336        }
337    }
338}
339
340pub struct VisibleCteScope<'a, S: Clone> {
341    ctes: &'a mut CteScope<S>,
342    previous: Option<BTreeSet<String>>,
343}
344
345impl<S: Clone> std::ops::Deref for VisibleCteScope<'_, S> {
346    type Target = CteScope<S>;
347
348    fn deref(&self) -> &Self::Target {
349        self.ctes
350    }
351}
352
353impl<S: Clone> std::ops::DerefMut for VisibleCteScope<'_, S> {
354    fn deref_mut(&mut self) -> &mut Self::Target {
355        self.ctes
356    }
357}
358
359impl<S: Clone> Drop for VisibleCteScope<'_, S> {
360    fn drop(&mut self) {
361        if let Some(previous) = self.previous.take() {
362            self.ctes.visible_cte_names = previous;
363        }
364    }
365}