Skip to main content

uqa_execution/query/
cursor.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bounded result cursors backed by an owned spill buffer.
8
9use crate::{ColumnarBatch, SharedSpill, SharedSpillReader};
10use uqa_sql::{ColumnType, SQLError};
11
12/// Metadata known before a cursor is consumed.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct SQLCursorSummary {
15    pub columns: Vec<String>,
16    pub column_types: Vec<Option<ColumnType>>,
17    pub row_count: usize,
18    pub spilled_to_disk: bool,
19}
20
21/// Iterator over schema-ordered column batches backed by a work-mem-bounded
22/// [`SharedSpill`]. Dropping the cursor releases its temporary file. Positional
23/// conversion preserves separately-valued duplicate labels in [`ColumnarBatch`].
24pub struct SQLCursor {
25    summary: SQLCursorSummary,
26    reader: SharedSpillReader,
27}
28
29impl SQLCursor {
30    pub fn from_spill(
31        columns: Vec<String>,
32        column_types: Vec<Option<ColumnType>>,
33        spill: SharedSpill,
34    ) -> Result<Self, SQLError> {
35        debug_assert_eq!(columns.len(), column_types.len());
36        let summary = SQLCursorSummary {
37            columns,
38            column_types,
39            row_count: spill.rows(),
40            spilled_to_disk: spill.has_spilled(),
41        };
42        let reader = spill
43            .into_reader()
44            .map_err(crate::physical::physical_exec_error)?;
45        Ok(Self { summary, reader })
46    }
47
48    pub fn columns(&self) -> &[String] {
49        &self.summary.columns
50    }
51
52    pub fn column_types(&self) -> &[Option<ColumnType>] {
53        &self.summary.column_types
54    }
55
56    pub fn row_count(&self) -> usize {
57        self.summary.row_count
58    }
59
60    pub fn spilled_to_disk(&self) -> bool {
61        self.summary.spilled_to_disk
62    }
63
64    pub fn summary(&self) -> SQLCursorSummary {
65        self.summary.clone()
66    }
67}
68
69impl Iterator for SQLCursor {
70    type Item = Result<ColumnarBatch, SQLError>;
71
72    fn next(&mut self) -> Option<Self::Item> {
73        loop {
74            let batch = match self.reader.next()? {
75                Ok(batch) => batch,
76                Err(error) => return Some(Err(crate::physical::physical_exec_error(error))),
77            };
78            if !batch.is_empty() {
79                return Some(Ok(ColumnarBatch::from_batch(&self.summary.columns, batch)));
80            }
81        }
82    }
83}