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 join = std::thread::spawn({
169            move || {
170                let consumer = Rc::new(DirectionalPlanRowConsumer {
171                    diagnostics: QueryDiagnostics::request_scope(diagnostics),
172                    requests: request_rx,
173                    responses: response_tx.clone(),
174                    direction: Cell::new(direction),
175                    closed: Cell::new(false),
176                    schema,
177                });
178                let result = input.execute(consumer.clone());
179                if let Err(error) = result {
180                    if !consumer.closed.get() {
181                        let _ = response_tx.send(DirectionalPlanResponse::Error(error));
182                    }
183                } else if !consumer.closed.get() {
184                    let _ = response_tx.send(DirectionalPlanResponse::Error(SQLError::Internal(
185                        "directional query branch stopped without a close request".into(),
186                    )));
187                }
188            }
189        });
190        self.worker = Some(DirectionalPlanWorker {
191            requests: request_tx,
192            responses: response_rx,
193            join: Some(join),
194        });
195        Ok(())
196    }
197
198    fn worker(&self) -> ExecResult<&DirectionalPlanWorker> {
199        self.worker
200            .as_ref()
201            .ok_or_else(|| ExecError::Other("directional query branch is closed".into()))
202    }
203
204    fn request(&self, request: DirectionalPlanRequest) -> ExecResult<DirectionalPlanResponse> {
205        let worker = self.worker()?;
206        worker.requests.send(request).map_err(|_| {
207            ExecError::Other("directional query branch stopped before a request".into())
208        })?;
209        worker.responses.recv().map_err(|_| {
210            ExecError::Other("directional query branch stopped without a response".into())
211        })
212    }
213
214    fn step(&mut self, direction: PhysicalScanDirection) -> ExecResult<DirectionalPlanResponse> {
215        if self.worker.is_none() {
216            self.start_worker(direction)?;
217            return self.worker()?.responses.recv().map_err(|_| {
218                ExecError::Other("directional query branch stopped without a response".into())
219            });
220        }
221        self.request(DirectionalPlanRequest::Step(
222            direction,
223            self.diagnostics.as_ref().map(QueryDiagnostics::request),
224        ))
225    }
226}
227
228impl PhysicalOperator for DirectionalQueryPlanOperator {
229    fn row_schema(&self) -> &RowSchema {
230        &self.schema
231    }
232
233    fn backward_scan_support(&self) -> BackwardScanSupport {
234        self.support
235    }
236
237    fn open(&mut self) -> ExecResult<()> {
238        if self.input.is_some() || self.worker.is_some() {
239            Ok(())
240        } else {
241            Err(ExecError::Other(
242                "directional query branch is closed".into(),
243            ))
244        }
245    }
246
247    fn next(&mut self) -> ExecResult<Option<Batch>> {
248        self.next_direction(PhysicalScanDirection::Forward)
249    }
250
251    fn next_direction(&mut self, direction: PhysicalScanDirection) -> ExecResult<Option<Batch>> {
252        match self.step(direction)? {
253            DirectionalPlanResponse::Row(row) => Ok(Some(Batch::from_physical_rows(
254                self.schema.clone(),
255                vec![row],
256            ))),
257            DirectionalPlanResponse::Eof => Ok(None),
258            DirectionalPlanResponse::Error(error) => Err(ExecError::SQL(error)),
259            DirectionalPlanResponse::Rewound => Err(ExecError::Other(
260                "directional query branch returned an invalid row response".into(),
261            )),
262        }
263    }
264
265    fn rewind(&mut self) -> ExecResult<()> {
266        if self.input.is_some() {
267            return Ok(());
268        }
269        match self.request(DirectionalPlanRequest::Rewind(
270            self.diagnostics.as_ref().map(QueryDiagnostics::request),
271        ))? {
272            DirectionalPlanResponse::Rewound => Ok(()),
273            DirectionalPlanResponse::Error(error) => Err(ExecError::SQL(error)),
274            DirectionalPlanResponse::Row(_) | DirectionalPlanResponse::Eof => {
275                Err(ExecError::Other(
276                    "directional query branch returned an invalid rewind response".into(),
277                ))
278            }
279        }
280    }
281
282    fn close(&mut self) -> ExecResult<()> {
283        self.worker = None;
284        self.input = None;
285        Ok(())
286    }
287}