uqa-execution 0.6.3

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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

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

use std::sync::{atomic::Ordering, Arc};
use uqa_sql::binding::production::{BindingMap, BindingNameSet};
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.inherit_cte_bindings_with_control(
            parent,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary inherited CTE bindings");
    }

    /// Admit every private lexical destination before replacing any part of the child scope. Statement and immutable definition owners remain shared with the parent.
    pub fn inherit_cte_bindings_with_control(
        &mut self,
        parent: &Self,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<(), SQLError> {
        control.check()?;
        let rows = parent.rows.copy_with_control(control)?;
        let deferred = parent
            .deferred_ctes
            .copy_with_control(control, |plan| Ok(plan.clone()))?;
        let definitions = parent
            .definition_scopes
            .copy_with_control(control, |definition| Ok(Arc::clone(definition)))?;
        let folded = parent.folded_ctes.copy_with_control(control)?;
        let non_returning = parent.non_returning_ctes.copy_with_control(control)?;
        let visible = parent.visible_cte_names.copy_with_control(control)?;
        let widths = parent
            .recursive_control_widths
            .copy_with_control(control, |width| Ok(*width))?;
        control.check()?;
        self.rows = rows;
        self.deferred_ctes = deferred;
        self.definition_scopes = definitions;
        self.folded_ctes = folded;
        self.non_returning_ctes = non_returning;
        self.visible_cte_names = visible;
        self.recursive_control_widths = 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);
        }
        Ok(())
    }

    /// 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.into());
        PrivilegeSubjectScope {
            ctes: self,
            previous,
        }
    }

    /// Transfer an admitted authority reference with its original lease before publishing the override. Child scopes share that owner after this guard restores its parent.
    pub fn enter_privilege_subject_with_control(
        &mut self,
        subject: uqa_core::memory::Produced<RoleReference>,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<PrivilegeSubjectScope<'_, S>, SQLError> {
        let subject = super::production::subject::ScopeSubject::from_produced(subject, control)?;
        let previous = self.privilege_subject.replace(subject);
        Ok(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> {
        self.enter_query_plan_scope_with_control(
            plan,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
    }

    pub fn enter_query_plan_scope_with_control(
        &mut self,
        plan: &QueryPlan,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> 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) => {
                let subject = super::production::subject::ScopeSubject::capture(subject, control)?;
                QueryPrivilege::Restore(lookup.privilege_subject.replace(subject))
            }
            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<uqa_sql::plan::RetainedCtePlan> {
        let reference = uqa_core::RelationIdentity::borrowed_reference(name)?;
        (reference.schema.is_none())
            .then(|| self.deferred_ctes.get_name(reference.name).cloned())
            .flatten()
    }

    pub fn materialized_for_scan(
        &self,
        reference: &str,
    ) -> Option<crate::query::cte::rows::CteRows> {
        let reference = uqa_core::RelationIdentity::borrowed_reference(reference)?;
        (reference.schema.is_none())
            .then(|| self.rows.get_name(reference.name).cloned())
            .flatten()
    }

    pub fn deferred_reference(&self, reference: &str) -> Option<&CtePlan> {
        let reference = uqa_core::RelationIdentity::borrowed_reference(reference)?;
        (reference.schema.is_none())
            .then(|| {
                self.deferred_ctes
                    .get_name(reference.name)
                    .map(AsRef::as_ref)
            })
            .flatten()
    }

    pub fn deferred_ctes(&self) -> &BindingMap<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> {
        self.enter_query_block_with_control(
            block,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary query-block scope")
    }

    /// Construct both private destinations before installing either, so admission failure leaves the complete parent namespace intact.
    pub fn enter_query_block_with_control(
        &mut self,
        block: &uqa_sql::plan::QueryBlockPlan,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<ScalarSubqueryScope<'_, S>, SQLError> {
        let arena = uqa_sql::plan::RetainedQueryArena::capture(&block.subqueries, control)?;
        let rewrites = if block.deferred_outer_rewrites.is_empty() {
            None
        } else {
            let mut rewrites = uqa_core::memory::ProductionVec::new(*control);
            rewrites.reserve(block.deferred_outer_rewrites.len())?;
            for rewrite in &block.deferred_outer_rewrites {
                rewrites.push_produced(rewrite.clone_with_control(control)?)?;
            }
            Some(rewrites.finish()?.into_shared(control)?)
        };
        control.check()?;
        let mut scope = self.enter_retained_scalar_subqueries(arena);
        scope.source_outer_rewrites = rewrites;
        Ok(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> {
        self.enter_scalar_subqueries_with_control(
            subqueries,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary scalar-query scope")
    }

    pub fn enter_scalar_subqueries_with_control(
        &mut self,
        subqueries: &[QueryPlan],
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<ScalarSubqueryScope<'_, S>, SQLError> {
        let arena = uqa_sql::plan::RetainedQueryArena::capture(subqueries, control)?;
        Ok(self.enter_retained_scalar_subqueries(arena))
    }

    pub(crate) fn enter_retained_scalar_subqueries(
        &mut self,
        arena: uqa_sql::plan::RetainedQueryArena,
    ) -> ScalarSubqueryScope<'_, S> {
        let previous = std::mem::replace(&mut self.scalar_subqueries, arena);
        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, 'n>(
        &'a mut self,
        names: impl IntoIterator<Item = &'n str>,
    ) -> VisibleCteScope<'a, S> {
        self.enter_visible_ctes_with_control(
            names,
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary visible CTE scope")
    }

    /// Build the complete name set before publication. The guard restores its exact previous owner without allocation on error or unwind.
    pub fn enter_visible_ctes_with_control<'a, 'n>(
        &'a mut self,
        names: impl IntoIterator<Item = &'n str>,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<VisibleCteScope<'a, S>, SQLError> {
        let mut visible = self.visible_cte_names.copy_with_control(control)?;
        for name in names {
            visible.insert_with_control(name, control)?;
        }
        control.check()?;
        let previous = std::mem::replace(&mut self.visible_cte_names, visible);
        Ok(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_core::RelationIdentity::borrowed_reference(name).is_some_and(|reference| {
            reference.schema.is_none()
                && (self.visible_cte_names.contains_name(reference.name)
                    || self.rows.get_name(reference.name).is_some()
                    || self.deferred_ctes.get_name(reference.name).is_some())
        })
    }

    /// 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 {
        self.returning_statement_snapshot_scope_with_control(
            &uqa_core::memory::ProductionControl::uncontrolled(),
        )
        .expect("ordinary returning scope")
    }

    pub fn returning_statement_snapshot_scope_with_control(
        &self,
        control: &uqa_core::memory::ProductionControl<'_>,
    ) -> Result<Self, SQLError> {
        let mut scope = self.copy_with_control(control)?;
        scope.read_command_overlay = false;
        Ok(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<super::production::subject::ScopeSubject>,
}

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<super::production::subject::ScopeSubject>),
}

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<uqa_sql::plan::RetainedQueryArena>,
    previous_arena: u64,
    previous_lock_identities: LockIdentityOptions,
    previous_outer_row: Option<Arc<crate::OwnedPhysicalRow>>,
    previous_source_rewrites: Option<super::SourceOuterRewrites>,
}

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<BindingNameSet>,
}

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;
        }
    }
}