Skip to main content

uqa_execution/query/sources/
retained_source.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Execution ownership of SQL-invisible, repeatable row sources.
8
9use std::cell::RefCell;
10use std::collections::btree_map::Entry;
11use std::collections::BTreeMap;
12use std::marker::PhantomData;
13use std::rc::Rc;
14use std::sync::Arc;
15
16use uqa_sql::ast::{InternalRelationId, RetainedRowSource};
17use uqa_sql::SQLError;
18
19use crate::{SharedSpill, SharedSpillScan};
20
21#[derive(Clone)]
22struct RetainedRows {
23    rows: SharedSpill,
24}
25
26#[cfg(test)]
27mod tests;
28
29thread_local! {
30    static ACTIVE_ROWS: RefCell<Arc<BTreeMap<InternalRelationId, RetainedRows>>> = RefCell::default();
31}
32
33/// Immutable owners captured for a statement's workers. Capturing and entering a context share the spill owners without copying rows or their metadata maps.
34#[derive(Clone, Default)]
35pub struct RetainedRowContext(Arc<BTreeMap<InternalRelationId, RetainedRows>>);
36
37impl RetainedRowContext {
38    #[must_use]
39    pub fn current() -> Self {
40        ACTIVE_ROWS.with(|active| Self(active.borrow().clone()))
41    }
42
43    pub(crate) fn enter(&self) -> RetainedRowThreadScope {
44        RetainedRowThreadScope {
45            previous: ACTIVE_ROWS.with(|active| active.replace(self.0.clone())),
46            _thread: PhantomData,
47        }
48    }
49}
50
51pub(crate) struct RetainedRowThreadScope {
52    previous: Arc<BTreeMap<InternalRelationId, RetainedRows>>,
53    _thread: PhantomData<Rc<()>>,
54}
55
56impl Drop for RetainedRowThreadScope {
57    fn drop(&mut self) {
58        ACTIVE_ROWS.with(|active| {
59            std::mem::swap(&mut *active.borrow_mut(), &mut self.previous);
60        });
61    }
62}
63
64/// Own one source until its synchronous action finishes. Nested actions have independent opaque identities; an error or unwind removes exactly this source. The guard cannot move to another thread, while an opened scan owns its independent spill reader.
65pub struct RetainedRowScope {
66    descriptor: RetainedRowSource,
67    _thread: PhantomData<Rc<()>>,
68}
69
70impl RetainedRowScope {
71    pub fn enter(relation: InternalRelationId, rows: SharedSpill) -> Result<Self, SQLError> {
72        let descriptor = RetainedRowSource::new(relation, rows.row_schema().clone(), rows.rows())?;
73        ACTIVE_ROWS.with(|active| {
74            match Arc::make_mut(&mut active.borrow_mut()).entry(relation) {
75                Entry::Occupied(_) => Err(SQLError::Internal(
76                    "retained row source is already active".into(),
77                )),
78                Entry::Vacant(entry) => {
79                    entry.insert(RetainedRows { rows });
80                    Ok(())
81                }
82            }
83        })?;
84        Ok(Self {
85            descriptor,
86            _thread: PhantomData,
87        })
88    }
89
90    pub fn descriptor(&self) -> &RetainedRowSource {
91        &self.descriptor
92    }
93}
94
95impl Drop for RetainedRowScope {
96    fn drop(&mut self) {
97        ACTIVE_ROWS.with(|active| {
98            let removed =
99                Arc::make_mut(&mut active.borrow_mut()).remove(&self.descriptor.relation());
100            debug_assert!(removed.is_some(), "retained row source ownership was lost");
101        });
102    }
103}
104
105fn retained_rows(source: &RetainedRowSource) -> Result<RetainedRows, SQLError> {
106    ACTIVE_ROWS.with(|active| {
107        let active = active.borrow();
108        let rows = active.get(&source.relation()).ok_or_else(|| {
109            SQLError::Internal("retained row source is outside its execution scope".into())
110        })?;
111        if rows.rows.rows() != source.rows() || rows.rows.row_schema() != source.schema() {
112            return Err(SQLError::Internal(
113                "retained row source does not match its declared rows and schema".into(),
114            ));
115        }
116        Ok(rows.clone())
117    })
118}
119
120#[cfg(test)]
121pub(crate) fn build_retained_source(
122    source: &RetainedRowSource,
123) -> Result<SharedSpillScan, SQLError> {
124    Ok(SharedSpillScan::new(retained_rows(source)?.rows))
125}
126
127pub(super) fn build_retained_source_operator(
128    source: &RetainedRowSource,
129) -> Result<SharedSpillScan, SQLError> {
130    Ok(SharedSpillScan::new(retained_rows(source)?.rows))
131}