uqa-execution 0.1.6

Volcano physical operators with row-batch pipelines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Scan operators.
//!
//! [`TableScan`] pulls rows from any [`RowSource`] in fixed-size
//! batches. The trait is the integration seam: the engine implements
//! it over its in-memory and SQLite-backed table state, the FDW layer
//! implements it over `MemoryHandler` / `DuckDBHandler` /
//! `ArrowHandler`, and tests can implement it directly over an
//! in-memory `Vec<ResultRow>`.

use crate::batch::{Batch, PhysicalRow, RowSchema, DEFAULT_BATCH_SIZE};
use crate::physical::{ExecResult, PhysicalOperator, PhysicalOrder};
use uqa_sql::ast::ColumnType;
use uqa_sql::ResultRow;

/// Source of rows feeding a [`TableScan`]. Implementors typically own
/// a snapshot of the underlying table or external relation; the scan
/// operator holds the source as a boxed trait object so callers can
/// mix and match implementations across one query.
pub trait RowSource: Send {
    /// Stable column order for the rows produced by [`Self::next_row`].
    fn schema(&self) -> &[String];

    /// Optional non-identity schema used by positional sources. This carries
    /// hidden lookup aliases and slot remaps that cannot be represented by the
    /// legacy column-name slice.
    fn physical_schema(&self) -> Option<&RowSchema> {
        None
    }

    /// Estimated total rows available from this source.
    fn estimated_cardinality(&self) -> Option<u64> {
        None
    }

    /// Leading row order guaranteed by the source.
    fn output_ordering(&self) -> &[PhysicalOrder] {
        &[]
    }

    /// Pull the next row. Returns `None` when the source is exhausted.
    fn next_row(&mut self) -> ExecResult<Option<ResultRow>>;

    /// Pull up to `max_rows` without forcing batch-capable sources through a
    /// row-at-a-time lock or backend call. The default preserves compatibility
    /// for iterator-like sources.
    fn next_batch(&mut self, max_rows: usize) -> ExecResult<Vec<ResultRow>> {
        let mut rows = Vec::with_capacity(max_rows);
        while rows.len() < max_rows {
            match self.next_row()? {
                Some(row) => rows.push(row),
                None => break,
            }
        }
        Ok(rows)
    }

    /// Pull a positional batch directly. Backend-native sources override this
    /// to avoid constructing named maps at the scan boundary; compatibility
    /// sources are converted exactly once here.
    fn next_physical_batch(&mut self, max_rows: usize) -> ExecResult<Vec<PhysicalRow>> {
        let schema = RowSchema::new(self.schema().to_vec());
        self.next_batch(max_rows).map(|rows| {
            rows.into_iter()
                .map(|row| PhysicalRow::from_result_row(&schema, row))
                .collect()
        })
    }

    /// Feed backend-native projected rows directly to an aggregate. Sources
    /// that cannot preserve their normal filter and virtual-column semantics
    /// return `false` without advancing their cursor.
    fn consume_into_aggregate(
        &mut self,
        _executor: &mut dyn crate::relational::AggregateExecutor,
    ) -> ExecResult<bool> {
        Ok(false)
    }
}

/// In-memory source from a precomputed `Vec<ResultRow>`. Useful for
/// tests and for materialising CTE bodies.
pub struct VecSource {
    schema: Vec<String>,
    physical_schema: RowSchema,
    rows: std::vec::IntoIter<ResultRow>,
}

/// In-memory positional source that preserves a structured [`RowSchema`] and shared physical row fragments without round-tripping through named maps.
pub struct PhysicalVecSource {
    schema: RowSchema,
    rows: std::vec::IntoIter<PhysicalRow>,
}

/// Physical scan over a fallible row iterator. Unlike [`VecSource`], this
/// adapter preserves producer backpressure and late errors without requiring a
/// cardinality-sized staging vector.
pub struct RowIteratorScan<'a> {
    schema: RowSchema,
    rows: Box<dyn Iterator<Item = ExecResult<ResultRow>> + Send + 'a>,
    exhausted: bool,
}

impl<'a> RowIteratorScan<'a> {
    pub fn new(
        schema: Vec<String>,
        rows: Box<dyn Iterator<Item = ExecResult<ResultRow>> + Send + 'a>,
    ) -> Self {
        Self {
            schema: RowSchema::new(schema),
            rows,
            exhausted: false,
        }
    }

    pub fn with_types(
        schema: Vec<String>,
        types: Vec<Option<ColumnType>>,
        rows: Box<dyn Iterator<Item = ExecResult<ResultRow>> + Send + 'a>,
    ) -> Self {
        Self {
            schema: RowSchema::with_types(schema, types),
            rows,
            exhausted: false,
        }
    }

    pub fn with_row_schema(
        schema: RowSchema,
        rows: Box<dyn Iterator<Item = ExecResult<ResultRow>> + Send + 'a>,
    ) -> Self {
        Self {
            schema,
            rows,
            exhausted: false,
        }
    }
}

impl PhysicalOperator for RowIteratorScan<'_> {
    fn row_schema(&self) -> &RowSchema {
        &self.schema
    }

    fn open(&mut self) -> ExecResult<()> {
        self.exhausted = false;
        Ok(())
    }

    fn next(&mut self) -> ExecResult<Option<Batch>> {
        if self.exhausted {
            return Ok(None);
        }
        let mut batch = Vec::with_capacity(DEFAULT_BATCH_SIZE);
        while batch.len() < DEFAULT_BATCH_SIZE {
            match self.rows.next() {
                Some(Ok(row)) => batch.push(row),
                Some(Err(error)) => return Err(error),
                None => {
                    self.exhausted = true;
                    break;
                }
            }
        }
        if batch.is_empty() {
            Ok(None)
        } else {
            Ok(Some(Batch::new(self.schema.clone(), batch)))
        }
    }

    fn close(&mut self) -> ExecResult<()> {
        self.exhausted = true;
        Ok(())
    }
}

impl VecSource {
    pub fn new(schema: Vec<String>, rows: Vec<ResultRow>) -> Self {
        let physical_schema = RowSchema::from_named_columns(schema.clone());
        Self {
            schema,
            physical_schema,
            rows: rows.into_iter(),
        }
    }

    pub fn with_row_schema(physical_schema: RowSchema, rows: Vec<ResultRow>) -> Self {
        Self {
            schema: physical_schema.columns().to_vec(),
            physical_schema,
            rows: rows.into_iter(),
        }
    }

    pub fn with_types(
        schema: Vec<String>,
        types: Vec<Option<ColumnType>>,
        rows: Vec<ResultRow>,
    ) -> Self {
        let physical_schema = RowSchema::with_types(schema.clone(), types);
        Self {
            schema,
            physical_schema,
            rows: rows.into_iter(),
        }
    }
}

impl RowSource for VecSource {
    fn schema(&self) -> &[String] {
        &self.schema
    }

    fn physical_schema(&self) -> Option<&RowSchema> {
        Some(&self.physical_schema)
    }

    fn estimated_cardinality(&self) -> Option<u64> {
        u64::try_from(self.rows.len()).ok()
    }

    fn next_row(&mut self) -> ExecResult<Option<ResultRow>> {
        Ok(self.rows.next())
    }
}

impl PhysicalVecSource {
    pub fn new(schema: RowSchema, rows: Vec<PhysicalRow>) -> Self {
        Self {
            schema,
            rows: rows.into_iter(),
        }
    }
}

impl RowSource for PhysicalVecSource {
    fn schema(&self) -> &[String] {
        self.schema.columns()
    }

    fn physical_schema(&self) -> Option<&RowSchema> {
        Some(&self.schema)
    }

    fn estimated_cardinality(&self) -> Option<u64> {
        u64::try_from(self.rows.len()).ok()
    }

    fn next_row(&mut self) -> ExecResult<Option<ResultRow>> {
        Ok(self
            .rows
            .next()
            .map(|row| self.schema.view(&row).to_result_row()))
    }

    fn next_physical_batch(&mut self, max_rows: usize) -> ExecResult<Vec<PhysicalRow>> {
        Ok(self.rows.by_ref().take(max_rows).collect())
    }
}

/// `TableScan`: a leaf operator that drains its [`RowSource`].
///
/// Emits batches of at most [`DEFAULT_BATCH_SIZE`] rows. Idempotent
/// `open` / `close` so the operator can be re-opened in tests.
pub struct TableScan {
    source: Option<Box<dyn RowSource>>,
    schema: RowSchema,
    ordering: Vec<PhysicalOrder>,
    estimated_cardinality: Option<u64>,
    exhausted: bool,
}

impl TableScan {
    pub fn new(source: Box<dyn RowSource>) -> Self {
        let schema = source
            .physical_schema()
            .cloned()
            .unwrap_or_else(|| RowSchema::new(source.schema().to_vec()));
        let ordering = source.output_ordering().to_vec();
        let estimated_cardinality = source.estimated_cardinality();
        Self {
            source: Some(source),
            schema,
            ordering,
            estimated_cardinality,
            exhausted: false,
        }
    }

    pub fn from_rows(schema: Vec<String>, rows: Vec<ResultRow>) -> Self {
        Self::new(Box::new(VecSource::new(schema, rows)))
    }

    pub fn from_typed_rows(
        schema: Vec<String>,
        types: Vec<Option<ColumnType>>,
        rows: Vec<ResultRow>,
    ) -> Self {
        Self::new(Box::new(VecSource::with_types(schema, types, rows)))
    }

    pub fn from_rows_with_schema(schema: RowSchema, rows: Vec<ResultRow>) -> Self {
        Self::new(Box::new(VecSource::with_row_schema(schema, rows)))
    }

    pub fn from_physical_rows(schema: RowSchema, rows: Vec<PhysicalRow>) -> Self {
        Self::new(Box::new(PhysicalVecSource::new(schema, rows)))
    }
}

impl PhysicalOperator for TableScan {
    fn row_schema(&self) -> &RowSchema {
        &self.schema
    }

    fn estimated_cardinality(&self) -> Option<u64> {
        self.estimated_cardinality
    }

    fn output_ordering(&self) -> &[PhysicalOrder] {
        &self.ordering
    }

    fn consume_into_aggregate(
        &mut self,
        executor: &mut dyn crate::relational::AggregateExecutor,
    ) -> ExecResult<bool> {
        let Some(source) = self.source.as_mut() else {
            return Ok(false);
        };
        source.consume_into_aggregate(executor)
    }

    fn open(&mut self) -> ExecResult<()> {
        self.exhausted = false;
        Ok(())
    }

    fn next(&mut self) -> ExecResult<Option<Batch>> {
        if self.exhausted {
            return Ok(None);
        }
        let Some(src) = self.source.as_mut() else {
            return Ok(None);
        };
        let buf = src.next_physical_batch(DEFAULT_BATCH_SIZE)?;
        if buf.is_empty() {
            self.exhausted = true;
            return Ok(None);
        }
        Ok(Some(Batch::from_physical_rows(self.schema.clone(), buf)))
    }

    fn close(&mut self) -> ExecResult<()> {
        self.source = None;
        self.exhausted = true;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::physical::run_to_rows;
    use uqa_core::Value;

    fn row<const N: usize>(pairs: [(&str, Value); N]) -> ResultRow {
        pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
    }

    #[test]
    fn table_scan_drains_source() {
        let rows = vec![
            row([("id", Value::Int(1)), ("name", Value::Str("a".into()))]),
            row([("id", Value::Int(2)), ("name", Value::Str("b".into()))]),
        ];
        let mut scan = TableScan::from_rows(vec!["id".into(), "name".into()], rows);
        let (cols, rows) = run_to_rows(&mut scan).unwrap();
        assert_eq!(cols, vec!["id", "name"]);
        assert_eq!(rows.len(), 2);
    }

    #[test]
    fn table_scan_empty_source_returns_no_batch() {
        let mut scan = TableScan::from_rows(vec!["id".into()], Vec::new());
        let (_cols, rows) = run_to_rows(&mut scan).unwrap();
        assert!(rows.is_empty());
    }

    #[test]
    fn iterator_scan_propagates_a_late_producer_error() {
        let rows = vec![
            Ok(row([("id", Value::Int(1))])),
            Err(crate::ExecError::Other("late producer failure".into())),
        ];
        let mut scan = RowIteratorScan::new(vec!["id".into()], Box::new(rows.into_iter()));
        let error = run_to_rows(&mut scan).unwrap_err();
        assert!(error.to_string().contains("late producer failure"));
    }
}