uqa-execution 0.6.2

Volcano physical operators with row-batch pipelines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! CTE lifetime, visibility, and scalar-subquery arena scopes.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::{atomic::Ordering, Arc};
use uqa_sql::catalog::roles::RoleReference;

use uqa_sql::plan::{CtePlan, QueryPlan};
use uqa_sql::SQLError;

use super::{CteScope, LockIdentityOptions};
use uqa_sql::catalog::resolution::RelationLookupMode;

impl<S: Clone> CteScope<S> {
    pub fn command_cte_snapshot(&self) -> Option<std::sync::Arc<S>> {
        self.command_cte_snapshot.clone()
    }

    pub fn set_command_cte_snapshot(&mut self, snapshot: Option<std::sync::Arc<S>>) {
        self.command_cte_snapshot = snapshot;
    }

    /// Make this scope part of the statement whose commands `commands` holds.
    pub fn set_statement_commands(&mut self, commands: std::sync::Arc<super::StatementCommands>) {
        self.statement_commands = Some(commands);
    }

    /// The commands of the statement this scope belongs to.
    pub fn statement_commands(&self) -> Option<&std::sync::Arc<super::StatementCommands>> {
        self.statement_commands.as_ref()
    }

    /// 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.
    pub fn statement_wrote(
        &self,
        row: &crate::mutation::candidate::PhysicalDocumentIdentity,
    ) -> bool {
        self.statement_commands
            .as_ref()
            .is_some_and(|commands| commands.wrote(row))
    }

    /// Whether a statement that the statement this scope belongs to started wrote `row`, which `PostgreSQL` finds modified under a later command id.
    pub fn statement_triggered_write(
        &self,
        row: &crate::mutation::candidate::PhysicalDocumentIdentity,
    ) -> bool {
        self.statement_commands
            .as_ref()
            .is_some_and(|commands| commands.triggered_write(row))
    }

    pub fn inherit_cte_bindings(&mut self, parent: &Self) {
        self.rows.clone_from(&parent.rows);
        self.deferred_ctes.clone_from(&parent.deferred_ctes);
        self.definition_scopes.clone_from(&parent.definition_scopes);
        self.folded_ctes.clone_from(&parent.folded_ctes);
        self.non_returning_ctes
            .clone_from(&parent.non_returning_ctes);
        self.visible_cte_names.clone_from(&parent.visible_cte_names);
        self.recursive_control_widths
            .clone_from(&parent.recursive_control_widths);
        self.command_cte_snapshot
            .clone_from(&parent.command_cte_snapshot);
        self.statement_commands
            .clone_from(&parent.statement_commands);
        if self.privilege_subject.is_none() {
            self.privilege_subject.clone_from(&parent.privilege_subject);
        }
    }

    /// Override only relation privilege checks while preserving SQL-visible `current_user` and the caller's namespace.
    pub fn enter_privilege_subject(
        &mut self,
        subject: RoleReference,
    ) -> PrivilegeSubjectScope<'_, S> {
        let previous = self.privilege_subject.replace(subject);
        PrivilegeSubjectScope {
            ctes: self,
            previous,
        }
    }

    /// Select the namespace semantics owned by one query plan and restore the parent plan's mode on every exit path.
    pub fn enter_relation_lookup_mode(
        &mut self,
        relations_bound: bool,
    ) -> Result<RelationLookupScope<'_, S>, SQLError> {
        let resolution = self.catalog_resolution.as_mut().ok_or_else(|| {
            SQLError::Internal(
                "query execution scope has no statement name-resolution snapshot".into(),
            )
        })?;
        let lookup_mode = if relations_bound {
            RelationLookupMode::Bound
        } else {
            RelationLookupMode::Dynamic
        };
        let previous = resolution.set_lookup_mode(lookup_mode);
        Ok(RelationLookupScope {
            ctes: self,
            previous,
        })
    }

    /// Enter the namespace and relation authority retained by one query, including rewritten inputs nested under a different statement owner.
    pub fn enter_query_plan_scope(
        &mut self,
        plan: &QueryPlan,
    ) -> Result<QueryPlanScope<'_, S>, SQLError> {
        let mut lookup = self.enter_relation_lookup_mode(plan.relations_bound)?;
        let previous_subject = match &plan.relation_privilege_subject {
            Some(subject) => {
                QueryPrivilege::Restore(lookup.privilege_subject.replace(subject.clone()))
            }
            None => QueryPrivilege::Unchanged,
        };
        Ok(QueryPlanScope {
            lookup,
            previous_subject,
        })
    }

    pub fn insert_shared(&mut self, name: String, rows: crate::SharedSpill) {
        self.insert_rows(name, crate::query::cte::rows::CteRows::Complete(rows));
    }

    pub fn insert_rows(&mut self, name: String, rows: crate::query::cte::rows::CteRows) {
        self.deferred_ctes.remove(&name);
        self.definition_scopes.remove(&name);
        self.folded_ctes.remove(&name);
        self.non_returning_ctes.remove(&name);
        self.rows.insert(name, rows);
    }

    pub fn insert_deferred(&mut self, plan: uqa_sql::plan::RetainedCtePlan) {
        self.insert_preparation_cte(plan, true);
    }

    pub fn remove_deferred(&mut self, name: &str) -> Option<uqa_sql::plan::RetainedCtePlan> {
        self.non_returning_ctes.remove(name);
        self.definition_scopes.remove(name);
        self.folded_ctes.remove(name);
        self.deferred_ctes.remove(name)
    }

    /// Return a folded definition without consuming its lexical binding. A single syntactic reference can be built again by a recursive working-table iteration or a correlated consumer. Materialized producers replace the definition explicitly when installed.
    pub fn deferred_for_scan(&self, name: &str) -> Option<CtePlan> {
        let name = uqa_sql::semantics::cte_reference_name(name)?;
        self.deferred_ctes.get(&name).map(|plan| (**plan).clone())
    }

    pub fn materialized_for_scan(
        &self,
        reference: &str,
    ) -> Option<crate::query::cte::rows::CteRows> {
        self.rows
            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
            .cloned()
    }

    pub fn deferred_reference(&self, reference: &str) -> Option<&CtePlan> {
        self.deferred_ctes
            .get(&uqa_sql::semantics::cte_reference_name(reference)?)
            .map(AsRef::as_ref)
    }

    pub fn deferred_ctes(&self) -> &BTreeMap<String, uqa_sql::plan::RetainedCtePlan> {
        &self.deferred_ctes
    }

    pub fn recursive_control_width(&self, name: &str) -> Option<usize> {
        self.recursive_control_widths.get(name).copied()
    }

    pub fn set_recursive_control_width(&mut self, name: String, width: usize) -> Option<usize> {
        self.recursive_control_widths.insert(name, width)
    }

    pub fn restore_recursive_control_width(&mut self, name: &str, previous: Option<usize>) {
        match previous {
            Some(width) => {
                self.recursive_control_widths
                    .insert(name.to_string(), width);
            }
            None => {
                self.recursive_control_widths.remove(name);
            }
        }
    }

    pub fn remove_materialized(&mut self, name: &str) -> Option<crate::query::cte::rows::CteRows> {
        self.non_returning_ctes.remove(name);
        self.rows.remove(name)
    }

    /// Enter a query block's scalar arena and the outer substitutions owned by its FROM expressions.
    pub fn enter_query_block(
        &mut self,
        block: &uqa_sql::plan::QueryBlockPlan,
    ) -> ScalarSubqueryScope<'_, S> {
        let mut scope = self.enter_scalar_subqueries(&block.subqueries);
        scope.source_outer_rewrites = (!block.deferred_outer_rewrites.is_empty())
            .then(|| block.deferred_outer_rewrites.as_slice().into());
        scope
    }

    /// Bind the scalar-subquery arena owned by one query block. The guard restores the parent arena and correlated row binding on success, error, or panic so nested and lateral query execution cannot resolve a child slot in its parent.
    pub fn enter_scalar_subqueries(
        &mut self,
        subqueries: &[QueryPlan],
    ) -> ScalarSubqueryScope<'_, S> {
        let previous = std::mem::replace(&mut self.scalar_subqueries, subqueries.into());
        let next_arena = self
            .next_scalar_subquery_arena
            .fetch_add(1, Ordering::Relaxed);
        let previous_arena = std::mem::replace(&mut self.scalar_subquery_arena, next_arena);
        let previous_lock_identities = self.lock_identities;
        let previous_outer_row = self.outer_row_binding();
        let previous_source_rewrites = self.source_outer_rewrites.clone();
        ScalarSubqueryScope {
            ctes: self,
            previous: Some(previous),
            previous_arena,
            previous_lock_identities,
            previous_outer_row,
            previous_source_rewrites,
        }
    }

    pub fn enter_visible_ctes<'a>(
        &'a mut self,
        names: impl IntoIterator<Item = &'a str>,
    ) -> VisibleCteScope<'a, S> {
        let previous = std::mem::take(&mut self.visible_cte_names);
        self.visible_cte_names.clone_from(&previous);
        self.visible_cte_names
            .extend(names.into_iter().map(str::to_owned));
        VisibleCteScope {
            ctes: self,
            previous: Some(previous),
        }
    }

    /// 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.
    pub fn is_visible_cte(&self, name: &str) -> bool {
        uqa_sql::semantics::cte_reference_name(name)
            .is_some_and(|name| self.contains_cte_name(&name))
    }

    /// Test an already decoded, unqualified identifier without applying SQL name parsing a second time.
    pub fn contains_cte_name(&self, name: &str) -> bool {
        self.visible_cte_names.contains(name)
            || self.rows.contains_key(name)
            || self.deferred_ctes.contains_key(name)
    }

    pub fn returning_statement_snapshot_scope(&self) -> Self {
        let mut scope = self.clone();
        scope.read_command_overlay = false;
        scope
    }

    pub fn reads_command_overlay(&self) -> bool {
        self.read_command_overlay
    }

    pub fn enable_command_progress_streaming(&mut self) {
        self.stream_command_progress = true;
    }

    pub fn streams_command_progress(&self) -> bool {
        self.stream_command_progress
    }

    pub fn enable_backwards_scanning(&mut self) {
        self.scan_backwards = true;
    }

    pub fn scans_backwards(&self) -> bool {
        self.scan_backwards
    }
}

pub struct PrivilegeSubjectScope<'a, S: Clone> {
    ctes: &'a mut CteScope<S>,
    previous: Option<RoleReference>,
}

impl<S: Clone> std::ops::Deref for PrivilegeSubjectScope<'_, S> {
    type Target = CteScope<S>;

    fn deref(&self) -> &Self::Target {
        self.ctes
    }
}

impl<S: Clone> std::ops::DerefMut for PrivilegeSubjectScope<'_, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.ctes
    }
}

impl<S: Clone> Drop for PrivilegeSubjectScope<'_, S> {
    fn drop(&mut self) {
        self.ctes.privilege_subject = self.previous.take();
    }
}

pub struct RelationLookupScope<'a, S: Clone> {
    ctes: &'a mut CteScope<S>,
    previous: RelationLookupMode,
}

impl<S: Clone> std::ops::Deref for RelationLookupScope<'_, S> {
    type Target = CteScope<S>;

    fn deref(&self) -> &Self::Target {
        self.ctes
    }
}

impl<S: Clone> std::ops::DerefMut for RelationLookupScope<'_, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.ctes
    }
}

impl<S: Clone> Drop for RelationLookupScope<'_, S> {
    fn drop(&mut self) {
        let resolution = self
            .ctes
            .catalog_resolution
            .as_mut()
            .expect("relation lookup scope lost its statement resolution");
        resolution.set_lookup_mode(self.previous);
    }
}

pub struct QueryPlanScope<'a, S: Clone> {
    lookup: RelationLookupScope<'a, S>,
    previous_subject: QueryPrivilege,
}

enum QueryPrivilege {
    Unchanged,
    Restore(Option<RoleReference>),
}

impl<S: Clone> std::ops::Deref for QueryPlanScope<'_, S> {
    type Target = CteScope<S>;
    fn deref(&self) -> &Self::Target {
        &self.lookup
    }
}

impl<S: Clone> std::ops::DerefMut for QueryPlanScope<'_, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.lookup
    }
}

impl<S: Clone> Drop for QueryPlanScope<'_, S> {
    fn drop(&mut self) {
        if let QueryPrivilege::Restore(previous) = &mut self.previous_subject {
            self.lookup.privilege_subject = previous.take();
        }
    }
}

pub struct ScalarSubqueryScope<'a, S: Clone> {
    ctes: &'a mut CteScope<S>,
    previous: Option<Arc<[QueryPlan]>>,
    previous_arena: u64,
    previous_lock_identities: LockIdentityOptions,
    previous_outer_row: Option<Arc<crate::OwnedPhysicalRow>>,
    previous_source_rewrites: Option<Arc<[uqa_sql::semantics::view_rewrite::DeferredOuterRewrite]>>,
}

impl<S: Clone> std::ops::Deref for ScalarSubqueryScope<'_, S> {
    type Target = CteScope<S>;

    fn deref(&self) -> &Self::Target {
        self.ctes
    }
}

impl<S: Clone> std::ops::DerefMut for ScalarSubqueryScope<'_, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.ctes
    }
}

impl<S: Clone> Drop for ScalarSubqueryScope<'_, S> {
    fn drop(&mut self) {
        if let Some(previous) = self.previous.take() {
            self.ctes.scalar_subqueries = previous;
            self.ctes.scalar_subquery_arena = self.previous_arena;
            self.ctes.lock_identities = self.previous_lock_identities;
            self.ctes
                .restore_outer_row_binding(self.previous_outer_row.take());
            self.ctes.source_outer_rewrites = std::mem::take(&mut self.previous_source_rewrites);
        }
    }
}

pub struct VisibleCteScope<'a, S: Clone> {
    ctes: &'a mut CteScope<S>,
    previous: Option<BTreeSet<String>>,
}

impl<S: Clone> std::ops::Deref for VisibleCteScope<'_, S> {
    type Target = CteScope<S>;

    fn deref(&self) -> &Self::Target {
        self.ctes
    }
}

impl<S: Clone> std::ops::DerefMut for VisibleCteScope<'_, S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.ctes
    }
}

impl<S: Clone> Drop for VisibleCteScope<'_, S> {
    fn drop(&mut self) {
        if let Some(previous) = self.previous.take() {
            self.ctes.visible_cte_names = previous;
        }
    }
}