Skip to main content

uqa_execution/query/statement/
retained_owner.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Keep a physical pipeline and its borrowed session inputs in one safe owner, on the caller's thread.
8
9use crate::{Batch, ExecResult, PhysicalOperator, RowSchema};
10use std::num::NonZeroUsize;
11use uqa_sql::SQLError;
12
13/// The host retains the session, statement snapshot, parameters and lexical scope. Execution builds and drives the existing physical pipeline while that owner remains alive.
14pub trait RetainedQueryInput: Send + Sync {
15    fn build(&self) -> Result<Option<Box<dyn PhysicalOperator + '_>>, SQLError>;
16}
17
18type BoundQuery<'a> = Option<Box<dyn PhysicalOperator + 'a>>;
19self_cell::self_cell!(
20    struct QueryCell {
21        owner: Box<dyn RetainedQueryInput>,
22        #[not_covariant]
23        dependent: BoundQuery,
24    }
25);
26
27pub struct RetainedQueryOperator {
28    query: QueryCell,
29    schema: RowSchema,
30    closed: bool,
31    ordering: Vec<crate::PhysicalOrder>,
32}
33
34impl RetainedQueryOperator {
35    pub fn try_new(input: Box<dyn RetainedQueryInput>) -> Result<Option<Self>, SQLError> {
36        let query = QueryCell::try_new(input, |input| input.build())?;
37        let schema =
38            query.with_dependent(|_, input| input.as_ref().map(|input| input.row_schema().clone()));
39        let ordering = query.with_dependent(|_, input| {
40            input
41                .as_ref()
42                .map_or_else(Vec::new, |input| input.output_ordering().to_vec())
43        });
44        Ok(schema.map(|schema| Self {
45            query,
46            schema,
47            closed: false,
48            ordering,
49        }))
50    }
51}
52
53impl PhysicalOperator for RetainedQueryOperator {
54    fn row_schema(&self) -> &RowSchema {
55        &self.schema
56    }
57    fn estimated_cardinality(&self) -> Option<u64> {
58        self.query.with_dependent(|_, input| {
59            input
60                .as_ref()
61                .and_then(|input| input.estimated_cardinality())
62        })
63    }
64    fn output_ordering(&self) -> &[crate::PhysicalOrder] {
65        &self.ordering
66    }
67    fn backward_scan_support(&self) -> crate::BackwardScanSupport {
68        self.query.with_dependent(|_, input| {
69            input
70                .as_ref()
71                .expect("retained query present")
72                .backward_scan_support()
73        })
74    }
75    fn consume_into_aggregate(
76        &mut self,
77        executor: &mut dyn crate::relational::AggregateExecutor,
78    ) -> ExecResult<bool> {
79        self.query.with_dependent_mut(|_, input| {
80            input
81                .as_mut()
82                .expect("retained query present")
83                .consume_into_aggregate(executor)
84        })
85    }
86    fn next_direction(
87        &mut self,
88        direction: crate::PhysicalScanDirection,
89    ) -> ExecResult<Option<Batch>> {
90        self.query.with_dependent_mut(|_, input| {
91            input
92                .as_mut()
93                .expect("retained query present")
94                .next_direction(direction)
95        })
96    }
97    fn rewind(&mut self) -> ExecResult<()> {
98        self.query
99            .with_dependent_mut(|_, input| input.as_mut().expect("retained query present").rewind())
100    }
101    fn open(&mut self) -> ExecResult<()> {
102        self.closed = false;
103        self.query
104            .with_dependent_mut(|_, input| input.as_mut().expect("retained query present").open())
105    }
106    fn next(&mut self) -> ExecResult<Option<Batch>> {
107        self.query
108            .with_dependent_mut(|_, input| input.as_mut().expect("retained query present").next())
109    }
110    fn next_with_demand(&mut self, rows: NonZeroUsize) -> ExecResult<Option<Batch>> {
111        self.query.with_dependent_mut(|_, input| {
112            input
113                .as_mut()
114                .expect("retained query present")
115                .next_with_demand(rows)
116        })
117    }
118    fn close(&mut self) -> ExecResult<()> {
119        if std::mem::replace(&mut self.closed, true) {
120            return Ok(());
121        }
122        self.query
123            .with_dependent_mut(|_, input| input.as_mut().expect("retained query present").close())
124    }
125}
126impl Drop for RetainedQueryOperator {
127    fn drop(&mut self) {
128        let _ = self.close();
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use std::sync::{
136        atomic::{AtomicUsize, Ordering},
137        Arc,
138    };
139
140    struct Input(Arc<AtomicUsize>);
141    struct Source(Arc<AtomicUsize>);
142
143    impl crate::SQLRowSource<crate::PhysicalRow> for Source {
144        fn next_row(&mut self) -> Result<Option<crate::PhysicalRow>, SQLError> {
145            panic!("closing must not fetch a row")
146        }
147        fn close(&mut self) -> Result<(), SQLError> {
148            assert_eq!(self.0.fetch_add(1, Ordering::SeqCst), 0);
149            Err(SQLError::Routine {
150                sqlstate: "58030".into(),
151                message: "retained scan close failed".into(),
152            })
153        }
154    }
155
156    impl RetainedQueryInput for Input {
157        fn build(&self) -> Result<Option<Box<dyn PhysicalOperator + '_>>, SQLError> {
158            Ok(Some(Box::new(crate::PhysicalRowIteratorScan::from_stream(
159                RowSchema::new(vec!["n".into()]),
160                crate::SQLRowStream::from_source(Source(self.0.clone())),
161            ))))
162        }
163    }
164
165    #[test]
166    fn retained_pipeline_close_reports_resources_created_before_open() {
167        for open in [false, true] {
168            let closed = Arc::new(AtomicUsize::new(0));
169            let mut pipeline = RetainedQueryOperator::try_new(Box::new(Input(closed.clone())))
170                .unwrap()
171                .unwrap();
172            if open {
173                pipeline.open().unwrap();
174            }
175            let error = crate::physical::physical_exec_error(pipeline.close().unwrap_err());
176            assert_eq!(error.sqlstate(), Some("58030"));
177            pipeline.close().unwrap();
178            drop(pipeline);
179            assert_eq!(closed.load(Ordering::SeqCst), 1);
180        }
181    }
182}