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;
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(), 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)
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        if persistent {
137            self.deferred_ctes.get(&name).cloned()
138        } else {
139            self.deferred_ctes.remove(&name)
140        }
141    }
142
143    pub fn materialized_for_scan(&self, reference: &str) -> Option<crate::SharedSpill> {
144        self.rows
145            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
146            .cloned()
147    }
148
149    pub fn deferred_reference(&self, reference: &str) -> Option<&CtePlan> {
150        self.deferred_ctes
151            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
152    }
153
154    pub fn deferred_ctes(&self) -> &BTreeMap<String, CtePlan> {
155        &self.deferred_ctes
156    }
157
158    pub fn recursive_control_width(&self, name: &str) -> Option<usize> {
159        self.recursive_control_widths.get(name).copied()
160    }
161
162    pub fn set_recursive_control_width(&mut self, name: String, width: usize) -> Option<usize> {
163        self.recursive_control_widths.insert(name, width)
164    }
165
166    pub fn restore_recursive_control_width(&mut self, name: &str, previous: Option<usize>) {
167        match previous {
168            Some(width) => {
169                self.recursive_control_widths
170                    .insert(name.to_string(), width);
171            }
172            None => {
173                self.recursive_control_widths.remove(name);
174            }
175        }
176    }
177
178    pub fn remove_materialized(&mut self, name: &str) -> Option<crate::SharedSpill> {
179        self.non_returning_ctes.remove(name);
180        self.rows.remove(name)
181    }
182
183    /// 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.
184    pub fn enter_scalar_subqueries(
185        &mut self,
186        subqueries: &[QueryPlan],
187    ) -> ScalarSubqueryScope<'_, S> {
188        let previous = std::mem::replace(&mut self.scalar_subqueries, subqueries.to_vec());
189        let next_arena = self
190            .next_scalar_subquery_arena
191            .fetch_add(1, Ordering::Relaxed);
192        let previous_arena = std::mem::replace(&mut self.scalar_subquery_arena, next_arena);
193        let previous_lock_identities = self.lock_identities;
194        ScalarSubqueryScope {
195            ctes: self,
196            previous: Some(previous),
197            previous_arena,
198            previous_lock_identities,
199        }
200    }
201
202    pub fn enter_visible_ctes<'a>(
203        &'a mut self,
204        names: impl IntoIterator<Item = &'a str>,
205    ) -> VisibleCteScope<'a, S> {
206        let previous = std::mem::take(&mut self.visible_cte_names);
207        self.visible_cte_names.clone_from(&previous);
208        self.visible_cte_names
209            .extend(names.into_iter().map(str::to_owned));
210        VisibleCteScope {
211            ctes: self,
212            previous: Some(previous),
213        }
214    }
215
216    /// 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.
217    pub fn is_visible_cte(&self, name: &str) -> bool {
218        uqa_sql::semantics::cte_reference_name(name).is_some_and(|name| {
219            self.visible_cte_names.contains(&name)
220                || self.rows.contains_key(&name)
221                || self.deferred_ctes.contains_key(&name)
222        })
223    }
224
225    pub fn returning_statement_snapshot_scope(&self) -> Self {
226        let mut scope = self.clone();
227        scope.read_command_overlay = false;
228        scope
229    }
230
231    pub fn reads_command_overlay(&self) -> bool {
232        self.read_command_overlay
233    }
234
235    pub fn enable_command_progress_streaming(&mut self) {
236        self.stream_command_progress = true;
237    }
238
239    pub fn streams_command_progress(&self) -> bool {
240        self.stream_command_progress
241    }
242
243    pub fn enable_backwards_scanning(&mut self) {
244        self.scan_backwards = true;
245    }
246
247    pub fn scans_backwards(&self) -> bool {
248        self.scan_backwards
249    }
250}
251
252pub struct PrivilegeSubjectScope<'a, S: Clone> {
253    ctes: &'a mut CteScope<S>,
254    previous: Option<RoleReference>,
255}
256
257impl<S: Clone> std::ops::Deref for PrivilegeSubjectScope<'_, S> {
258    type Target = CteScope<S>;
259
260    fn deref(&self) -> &Self::Target {
261        self.ctes
262    }
263}
264
265impl<S: Clone> std::ops::DerefMut for PrivilegeSubjectScope<'_, S> {
266    fn deref_mut(&mut self) -> &mut Self::Target {
267        self.ctes
268    }
269}
270
271impl<S: Clone> Drop for PrivilegeSubjectScope<'_, S> {
272    fn drop(&mut self) {
273        self.ctes.privilege_subject = self.previous.take();
274    }
275}
276
277pub struct RelationLookupScope<'a, S: Clone> {
278    ctes: &'a mut CteScope<S>,
279    previous: RelationLookupMode,
280}
281
282impl<S: Clone> std::ops::Deref for RelationLookupScope<'_, S> {
283    type Target = CteScope<S>;
284
285    fn deref(&self) -> &Self::Target {
286        self.ctes
287    }
288}
289
290impl<S: Clone> std::ops::DerefMut for RelationLookupScope<'_, S> {
291    fn deref_mut(&mut self) -> &mut Self::Target {
292        self.ctes
293    }
294}
295
296impl<S: Clone> Drop for RelationLookupScope<'_, S> {
297    fn drop(&mut self) {
298        let resolution = self
299            .ctes
300            .catalog_resolution
301            .as_mut()
302            .expect("relation lookup scope lost its statement resolution");
303        resolution.set_lookup_mode(self.previous);
304    }
305}
306
307pub struct ScalarSubqueryScope<'a, S: Clone> {
308    ctes: &'a mut CteScope<S>,
309    previous: Option<Vec<QueryPlan>>,
310    previous_arena: u64,
311    previous_lock_identities: LockIdentityOptions,
312}
313
314impl<S: Clone> std::ops::Deref for ScalarSubqueryScope<'_, S> {
315    type Target = CteScope<S>;
316
317    fn deref(&self) -> &Self::Target {
318        self.ctes
319    }
320}
321
322impl<S: Clone> std::ops::DerefMut for ScalarSubqueryScope<'_, S> {
323    fn deref_mut(&mut self) -> &mut Self::Target {
324        self.ctes
325    }
326}
327
328impl<S: Clone> Drop for ScalarSubqueryScope<'_, S> {
329    fn drop(&mut self) {
330        if let Some(previous) = self.previous.take() {
331            self.ctes.scalar_subqueries = previous;
332            self.ctes.scalar_subquery_arena = self.previous_arena;
333            self.ctes.lock_identities = self.previous_lock_identities;
334        }
335    }
336}
337
338pub struct VisibleCteScope<'a, S: Clone> {
339    ctes: &'a mut CteScope<S>,
340    previous: Option<BTreeSet<String>>,
341}
342
343impl<S: Clone> std::ops::Deref for VisibleCteScope<'_, S> {
344    type Target = CteScope<S>;
345
346    fn deref(&self) -> &Self::Target {
347        self.ctes
348    }
349}
350
351impl<S: Clone> std::ops::DerefMut for VisibleCteScope<'_, S> {
352    fn deref_mut(&mut self) -> &mut Self::Target {
353        self.ctes
354    }
355}
356
357impl<S: Clone> Drop for VisibleCteScope<'_, S> {
358    fn drop(&mut self) {
359        if let Some(previous) = self.previous.take() {
360            self.ctes.visible_cte_names = previous;
361        }
362    }
363}