Skip to main content

uqa_execution/query/statement/
directional.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Persistent directional query traversal over a session-owned worker task.
8use crate::query::consumer::{QueryConsumerControl, QueryRowConsumer};
9use crate::query::diagnostics::{InvocationRequest, QueryDiagnostics, RequestScope};
10use crate::{
11    BackwardScanSupport, Batch, ExecError, ExecResult, PhysicalOperator, PhysicalRow,
12    PhysicalScanDirection, RowSchema,
13};
14use std::{cell::Cell, rc::Rc};
15use uqa_core::Value;
16use uqa_sql::SQLError;
17
18enum DirectionalPlanRequest {
19    Step(PhysicalScanDirection, Option<InvocationRequest>),
20    Rewind(Option<InvocationRequest>),
21    Close,
22}
23
24enum DirectionalPlanResponse {
25    Row(PhysicalRow),
26    Eof,
27    Rewound,
28    Error(SQLError),
29}
30
31struct DirectionalPlanWorker {
32    requests: std::sync::mpsc::Sender<DirectionalPlanRequest>,
33    responses: std::sync::mpsc::Receiver<DirectionalPlanResponse>,
34    join: Option<std::thread::JoinHandle<()>>,
35}
36
37impl Drop for DirectionalPlanWorker {
38    fn drop(&mut self) {
39        let _ = self.requests.send(DirectionalPlanRequest::Close);
40        if let Some(join) = self.join.take() {
41            let _ = join.join();
42        }
43    }
44}
45
46struct DirectionalPlanRowConsumer {
47    diagnostics: RequestScope,
48    requests: std::sync::mpsc::Receiver<DirectionalPlanRequest>,
49    responses: std::sync::mpsc::Sender<DirectionalPlanResponse>,
50    direction: Cell<PhysicalScanDirection>,
51    closed: Cell<bool>,
52    schema: RowSchema,
53}
54
55impl DirectionalPlanRowConsumer {
56    fn wait_for_request(&self) -> Result<QueryConsumerControl, SQLError> {
57        match self.requests.recv() {
58            Ok(DirectionalPlanRequest::Step(direction, diagnostics)) => {
59                self.diagnostics.replace(diagnostics);
60                self.direction.set(direction);
61                Ok(QueryConsumerControl::Continue)
62            }
63            Ok(DirectionalPlanRequest::Rewind(diagnostics)) => {
64                self.diagnostics.replace(diagnostics);
65                Ok(QueryConsumerControl::Rewind)
66            }
67            Ok(DirectionalPlanRequest::Close) | Err(_) => {
68                self.closed.set(true);
69                Ok(QueryConsumerControl::Stop)
70            }
71        }
72    }
73
74    fn respond_and_wait(
75        &self,
76        response: DirectionalPlanResponse,
77    ) -> Result<QueryConsumerControl, SQLError> {
78        if self.responses.send(response).is_err() {
79            self.closed.set(true);
80            return Ok(QueryConsumerControl::Stop);
81        }
82        self.wait_for_request()
83    }
84}
85
86impl QueryRowConsumer for DirectionalPlanRowConsumer {
87    fn begin(&self, columns: &[String], _schema: &RowSchema) -> Result<(), SQLError> {
88        if columns.len() != self.schema.len() {
89            return Err(SQLError::TypeMismatch(format!(
90                "directional set-operation branch width {} does not match declared width {}",
91                columns.len(),
92                self.schema.len()
93            )));
94        }
95        Ok(())
96    }
97
98    fn consume(&self, row: crate::OwnedPhysicalRow) -> Result<QueryConsumerControl, SQLError> {
99        let view = row.view();
100        let values = (0..self.schema.len())
101            .map(|position| view.value_at(position).cloned().unwrap_or(Value::Null))
102            .collect();
103        self.respond_and_wait(DirectionalPlanResponse::Row(PhysicalRow::from_values(
104            values,
105        )))
106    }
107
108    fn uses_directional_scan(&self) -> bool {
109        true
110    }
111
112    fn scan_direction(&self) -> PhysicalScanDirection {
113        self.direction.get()
114    }
115
116    fn direction_exhausted(&self) -> Result<QueryConsumerControl, SQLError> {
117        self.respond_and_wait(DirectionalPlanResponse::Eof)
118    }
119
120    fn rewound(&self) -> Result<QueryConsumerControl, SQLError> {
121        self.respond_and_wait(DirectionalPlanResponse::Rewound)
122    }
123}
124
125/// Run one query in the session state prepared by the caller. The session owns its statement gate and snapshot lifetime.
126pub trait DirectionalQueryTask: Send {
127    fn execute(self: Box<Self>, consumer: Rc<dyn QueryRowConsumer>) -> Result<(), SQLError>;
128}
129
130pub struct DirectionalQueryPlanOperator {
131    diagnostics: Option<QueryDiagnostics>,
132    schema: RowSchema,
133    support: BackwardScanSupport,
134    input: Option<Box<dyn DirectionalQueryTask>>,
135    worker: Option<DirectionalPlanWorker>,
136}
137
138impl DirectionalQueryPlanOperator {
139    pub fn new(
140        input: Box<dyn DirectionalQueryTask>,
141        support: BackwardScanSupport,
142        schema: RowSchema,
143    ) -> Self {
144        Self {
145            diagnostics: None,
146            schema,
147            support,
148            input: Some(input),
149            worker: None,
150        }
151    }
152
153    #[must_use]
154    pub fn with_diagnostics(mut self, diagnostics: QueryDiagnostics) -> Self {
155        self.diagnostics = Some(diagnostics);
156        self
157    }
158
159    fn start_worker(&mut self, direction: PhysicalScanDirection) -> ExecResult<()> {
160        let input = self
161            .input
162            .take()
163            .ok_or_else(|| ExecError::Other("directional query branch is closed".into()))?;
164        let (request_tx, request_rx) = std::sync::mpsc::channel();
165        let (response_tx, response_rx) = std::sync::mpsc::channel();
166        let schema = self.schema.clone();
167        let diagnostics = self.diagnostics.as_ref().map(QueryDiagnostics::request);
168        let thread_context = crate::statement::thread_context::StatementThreadContext::current();
169        let join = std::thread::spawn({
170            move || {
171                let _statement_thread = thread_context.enter();
172                let consumer = Rc::new(DirectionalPlanRowConsumer {
173                    diagnostics: QueryDiagnostics::request_scope(diagnostics),
174                    requests: request_rx,
175                    responses: response_tx.clone(),
176                    direction: Cell::new(direction),
177                    closed: Cell::new(false),
178                    schema,
179                });
180                let result = input.execute(consumer.clone());
181                if let Err(error) = result {
182                    if !consumer.closed.get() {
183                        let _ = response_tx.send(DirectionalPlanResponse::Error(error));
184                    }
185                } else if !consumer.closed.get() {
186                    let _ = response_tx.send(DirectionalPlanResponse::Error(SQLError::Internal(
187                        "directional query branch stopped without a close request".into(),
188                    )));
189                }
190            }
191        });
192        self.worker = Some(DirectionalPlanWorker {
193            requests: request_tx,
194            responses: response_rx,
195            join: Some(join),
196        });
197        Ok(())
198    }
199
200    fn worker(&self) -> ExecResult<&DirectionalPlanWorker> {
201        self.worker
202            .as_ref()
203            .ok_or_else(|| ExecError::Other("directional query branch is closed".into()))
204    }
205
206    fn request(&self, request: DirectionalPlanRequest) -> ExecResult<DirectionalPlanResponse> {
207        let worker = self.worker()?;
208        worker.requests.send(request).map_err(|_| {
209            ExecError::Other("directional query branch stopped before a request".into())
210        })?;
211        worker.responses.recv().map_err(|_| {
212            ExecError::Other("directional query branch stopped without a response".into())
213        })
214    }
215
216    fn step(&mut self, direction: PhysicalScanDirection) -> ExecResult<DirectionalPlanResponse> {
217        if self.worker.is_none() {
218            self.start_worker(direction)?;
219            return self.worker()?.responses.recv().map_err(|_| {
220                ExecError::Other("directional query branch stopped without a response".into())
221            });
222        }
223        self.request(DirectionalPlanRequest::Step(
224            direction,
225            self.diagnostics.as_ref().map(QueryDiagnostics::request),
226        ))
227    }
228}
229
230impl PhysicalOperator for DirectionalQueryPlanOperator {
231    fn row_schema(&self) -> &RowSchema {
232        &self.schema
233    }
234
235    fn backward_scan_support(&self) -> BackwardScanSupport {
236        self.support
237    }
238
239    fn open(&mut self) -> ExecResult<()> {
240        if self.input.is_some() || self.worker.is_some() {
241            Ok(())
242        } else {
243            Err(ExecError::Other(
244                "directional query branch is closed".into(),
245            ))
246        }
247    }
248
249    fn next(&mut self) -> ExecResult<Option<Batch>> {
250        self.next_direction(PhysicalScanDirection::Forward)
251    }
252
253    fn next_direction(&mut self, direction: PhysicalScanDirection) -> ExecResult<Option<Batch>> {
254        match self.step(direction)? {
255            DirectionalPlanResponse::Row(row) => Ok(Some(Batch::from_physical_rows(
256                self.schema.clone(),
257                vec![row],
258            ))),
259            DirectionalPlanResponse::Eof => Ok(None),
260            DirectionalPlanResponse::Error(error) => Err(ExecError::SQL(error)),
261            DirectionalPlanResponse::Rewound => Err(ExecError::Other(
262                "directional query branch returned an invalid row response".into(),
263            )),
264        }
265    }
266
267    fn rewind(&mut self) -> ExecResult<()> {
268        if self.input.is_some() {
269            return Ok(());
270        }
271        match self.request(DirectionalPlanRequest::Rewind(
272            self.diagnostics.as_ref().map(QueryDiagnostics::request),
273        ))? {
274            DirectionalPlanResponse::Rewound => Ok(()),
275            DirectionalPlanResponse::Error(error) => Err(ExecError::SQL(error)),
276            DirectionalPlanResponse::Row(_) | DirectionalPlanResponse::Eof => {
277                Err(ExecError::Other(
278                    "directional query branch returned an invalid rewind response".into(),
279                ))
280            }
281        }
282    }
283
284    fn close(&mut self) -> ExecResult<()> {
285        self.worker = None;
286        self.input = None;
287        Ok(())
288    }
289}