1use thiserror::Error;
10
11use crate::batch::{Batch, RowSchema};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct PhysicalOrder {
18 pub position: usize,
19 pub descending: bool,
20 pub nulls_first: Option<bool>,
21 pub nullable: bool,
22}
23
24#[derive(Debug, Error)]
27pub enum ExecError {
28 #[error("execution error: {0}")]
29 Other(String),
30 #[error("SQL error: {0}")]
31 SQL(#[from] uqa_sql::SQLError),
32}
33
34impl From<uqa_sql::schema::SchemaLayoutError> for ExecError {
35 fn from(error: uqa_sql::schema::SchemaLayoutError) -> Self {
36 Self::Other(error.to_string())
37 }
38}
39
40pub type ExecResult<T> = std::result::Result<T, ExecError>;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum PhysicalScanDirection {
45 Forward,
46 Backward,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum BackwardScanSupport {
52 Unsupported,
54 Materialize,
56 Native,
58}
59
60pub(crate) fn with_cleanup<T>(
65 primary: ExecResult<T>,
66 cleanup: ExecResult<()>,
67 cleanup_context: &str,
68) -> ExecResult<T> {
69 match (primary, cleanup) {
70 (Ok(value), Ok(())) => Ok(value),
71 (Ok(_), Err(cleanup_error)) => Err(cleanup_error),
72 (Err(primary_error), Ok(())) => Err(primary_error),
73 (Err(primary_error), Err(cleanup_error)) => Err(ExecError::Other(format!(
74 "{primary_error}; {cleanup_context}: {cleanup_error}"
75 ))),
76 }
77}
78
79pub trait PhysicalOperator: Send {
93 fn row_schema(&self) -> &RowSchema;
95
96 fn schema(&self) -> &[String] {
98 self.row_schema().columns()
99 }
100
101 fn estimated_cardinality(&self) -> Option<u64> {
105 None
106 }
107
108 fn output_ordering(&self) -> &[PhysicalOrder] {
110 &[]
111 }
112
113 fn consume_into_aggregate(
117 &mut self,
118 _executor: &mut dyn crate::relational::AggregateExecutor,
119 ) -> ExecResult<bool> {
120 Ok(false)
121 }
122
123 fn backward_scan_support(&self) -> BackwardScanSupport {
125 BackwardScanSupport::Unsupported
126 }
127
128 fn open(&mut self) -> ExecResult<()>;
129 fn next(&mut self) -> ExecResult<Option<Batch>>;
130 fn next_direction(&mut self, direction: PhysicalScanDirection) -> ExecResult<Option<Batch>> {
132 match direction {
133 PhysicalScanDirection::Forward => self.next(),
134 PhysicalScanDirection::Backward => Err(ExecError::Other(
135 "physical operator does not support backwards scanning".into(),
136 )),
137 }
138 }
139 fn rewind(&mut self) -> ExecResult<()> {
141 Err(ExecError::Other(
142 "physical operator does not support rewind".into(),
143 ))
144 }
145 fn close(&mut self) -> ExecResult<()>;
146}
147
148pub fn ordering_satisfies(actual: &[PhysicalOrder], required: &[PhysicalOrder]) -> bool {
150 actual.len() >= required.len()
151 && actual.iter().zip(required).all(|(actual, required)| {
152 actual.position == required.position
153 && actual.descending == required.descending
154 && (!actual.nullable
155 || actual.nulls_first == required.nulls_first
156 || required.nulls_first.is_none())
157 })
158}
159
160pub fn order_expression_position(
162 schema: &RowSchema,
163 expression: &crate::ScalarExpr,
164) -> Option<usize> {
165 match expression {
166 crate::ScalarExpr::Column(column) => schema.unqualified_position(column),
167 crate::ScalarExpr::Position(position) => (*position < schema.len()).then_some(*position),
168 crate::ScalarExpr::QualifiedColumn { qualifier, column } => {
169 schema.qualified_position(qualifier, column)
170 }
171 _ => None,
172 }
173}
174
175pub struct OperatorBatchCursor<'operator> {
179 operator: &'operator mut dyn PhysicalOperator,
180 finished: bool,
181}
182
183impl<'operator> OperatorBatchCursor<'operator> {
184 pub fn open(operator: &'operator mut dyn PhysicalOperator) -> ExecResult<Self> {
185 if let Err(open_error) = operator.open() {
186 return match operator.close() {
187 Ok(()) => Err(open_error),
188 Err(close_error) => Err(ExecError::Other(format!(
189 "{open_error}; operator close after open failure also failed: {close_error}"
190 ))),
191 };
192 }
193 Ok(Self {
194 operator,
195 finished: false,
196 })
197 }
198
199 fn finish(&mut self) -> ExecResult<()> {
200 if self.finished {
201 return Ok(());
202 }
203 self.finished = true;
204 self.operator.close()
205 }
206}
207
208impl Iterator for OperatorBatchCursor<'_> {
209 type Item = ExecResult<Batch>;
210
211 fn next(&mut self) -> Option<Self::Item> {
212 if self.finished {
213 return None;
214 }
215 match self.operator.next() {
216 Ok(Some(batch)) => Some(Ok(batch)),
217 Ok(None) => match self.finish() {
218 Ok(()) => None,
219 Err(error) => Some(Err(error)),
220 },
221 Err(next_error) => {
222 let close = self.finish();
223 Some(with_cleanup(
224 Err(next_error),
225 close,
226 "operator close after execution failure also failed",
227 ))
228 }
229 }
230 }
231}
232
233impl Drop for OperatorBatchCursor<'_> {
234 fn drop(&mut self) {
235 let _ = self.finish();
236 }
237}
238
239pub fn run_to_batches(op: &mut dyn PhysicalOperator) -> ExecResult<Vec<Batch>> {
243 OperatorBatchCursor::open(op)?.collect()
244}
245
246pub fn run_to_rows(
249 op: &mut dyn PhysicalOperator,
250) -> ExecResult<(Vec<String>, Vec<uqa_sql::ResultRow>)> {
251 let schema = op.schema().to_vec();
252 let mut rows: Vec<uqa_sql::ResultRow> = Vec::new();
253 for batch in OperatorBatchCursor::open(op)? {
254 let batch = batch?;
255 rows.extend(batch.into_result_rows());
256 }
257 Ok((schema, rows))
258}
259
260pub fn physical_exec_error(error: crate::ExecError) -> uqa_sql::SQLError {
262 match error {
263 crate::ExecError::SQL(error) => error,
264 crate::ExecError::Other(message) => uqa_sql::SQLError::Internal(message),
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 struct FailingOperator {
273 fail_open: bool,
274 fail_close: bool,
275 closed: bool,
276 }
277
278 impl PhysicalOperator for FailingOperator {
279 fn row_schema(&self) -> &RowSchema {
280 static SCHEMA: std::sync::OnceLock<RowSchema> = std::sync::OnceLock::new();
281 SCHEMA.get_or_init(RowSchema::default)
282 }
283
284 fn open(&mut self) -> ExecResult<()> {
285 if self.fail_open {
286 Err(ExecError::Other("open failed".into()))
287 } else {
288 Ok(())
289 }
290 }
291
292 fn next(&mut self) -> ExecResult<Option<Batch>> {
293 Err(ExecError::Other("next failed".into()))
294 }
295
296 fn close(&mut self) -> ExecResult<()> {
297 self.closed = true;
298 if self.fail_close {
299 Err(ExecError::Other("close failed".into()))
300 } else {
301 Ok(())
302 }
303 }
304 }
305
306 #[test]
307 fn runner_closes_after_open_and_next_failures() {
308 let mut open = FailingOperator {
309 fail_open: true,
310 fail_close: false,
311 closed: false,
312 };
313 assert!(run_to_batches(&mut open)
314 .unwrap_err()
315 .to_string()
316 .contains("open failed"));
317 assert!(open.closed);
318
319 let mut next = FailingOperator {
320 fail_open: false,
321 fail_close: false,
322 closed: false,
323 };
324 assert!(run_to_batches(&mut next)
325 .unwrap_err()
326 .to_string()
327 .contains("next failed"));
328 assert!(next.closed);
329 }
330
331 #[test]
332 fn runner_reports_execution_and_cleanup_failures() {
333 let mut operator = FailingOperator {
334 fail_open: false,
335 fail_close: true,
336 closed: false,
337 };
338 let error = run_to_batches(&mut operator).unwrap_err().to_string();
339 assert!(error.contains("next failed"), "{error}");
340 assert!(error.contains("close failed"), "{error}");
341 assert!(operator.closed);
342 }
343
344 #[test]
345 fn cleanup_combiner_preserves_both_errors() {
346 let error = with_cleanup::<()>(
347 Err(ExecError::Other("primary".into())),
348 Err(ExecError::Other("cleanup".into())),
349 "cleanup failed",
350 )
351 .unwrap_err()
352 .to_string();
353 assert!(error.contains("primary"), "{error}");
354 assert!(error.contains("cleanup"), "{error}");
355 }
356
357 #[test]
358 fn dropping_cursor_closes_an_unfinished_pipeline() {
359 let mut operator = FailingOperator {
360 fail_open: false,
361 fail_close: false,
362 closed: false,
363 };
364 {
365 let _cursor = OperatorBatchCursor::open(&mut operator).unwrap();
366 }
367 assert!(operator.closed);
368 }
369
370 #[test]
371 fn ordering_positions_keep_duplicate_structured_identities_distinct() {
372 let schema = RowSchema::with_identities(
373 vec!["id".into(), "id".into()],
374 vec![
375 crate::ColumnIdentity::qualified("left", "id"),
376 crate::ColumnIdentity::qualified("right", "id"),
377 ],
378 vec![None, None],
379 );
380 assert_eq!(
381 order_expression_position(&schema, &crate::ScalarExpr::qualified_column("left", "id")),
382 Some(0)
383 );
384 assert_eq!(
385 order_expression_position(&schema, &crate::ScalarExpr::qualified_column("right", "id")),
386 Some(1)
387 );
388 assert_eq!(
389 order_expression_position(&schema, &crate::ScalarExpr::Column("id".into())),
390 None
391 );
392 let actual = [PhysicalOrder {
393 position: 0,
394 descending: false,
395 nulls_first: None,
396 nullable: false,
397 }];
398 let required = [PhysicalOrder {
399 position: 1,
400 descending: false,
401 nulls_first: Some(false),
402 nullable: true,
403 }];
404 assert!(!ordering_satisfies(&actual, &required));
405 }
406}