Skip to main content

uqa_execution/query/
output.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Owned physical query results and public result conversion.
8
9use crate::physical::physical_exec_error;
10use uqa_sql::{SQLError, SQLResult};
11
12mod exists;
13pub use exists::collect_exists_key_operator;
14
15#[cfg(test)]
16mod tests;
17
18pub enum QueryRows {
19    Rows(Vec<crate::PhysicalRow>),
20    SharedSpill(crate::SharedSpill),
21    ExistsKeySet(crate::CanonicalRowHashSet),
22}
23
24pub struct QueryOutput {
25    pub columns: Vec<String>,
26    pub column_types: Vec<Option<uqa_sql::ast::ColumnType>>,
27    /// Complete physical metadata for child queries; public result columns may expose only a projection of these slots.
28    pub internal_schema: crate::RowSchema,
29    pub rows: QueryRows,
30}
31
32impl QueryOutput {
33    pub fn into_cursor(self) -> Result<crate::query::cursor::SQLCursor, SQLError> {
34        match self.rows {
35            QueryRows::SharedSpill(rows) => {
36                crate::query::cursor::SQLCursor::from_spill(self.columns, self.column_types, rows)
37            }
38            QueryRows::Rows(_) | QueryRows::ExistsKeySet(_) => Err(SQLError::Internal(
39                "cursor query unexpectedly used unbounded row materialization".into(),
40            )),
41        }
42    }
43
44    pub fn into_sql_result(self) -> Result<SQLResult, SQLError> {
45        let rows = match self.rows {
46            QueryRows::Rows(rows) => rows,
47            QueryRows::SharedSpill(rows) => {
48                let mut scan = crate::SharedSpillScan::new(rows);
49                crate::physical::run_to_batches(&mut scan)
50                    .map_err(physical_exec_error)?
51                    .into_iter()
52                    .flat_map(|batch| batch.rows)
53                    .collect()
54            }
55            QueryRows::ExistsKeySet(_) => {
56                return Err(SQLError::Internal(
57                    "EXISTS key-set output cannot become a SQL result".into(),
58                ));
59            }
60        };
61        let schema = self.internal_schema.for_result_columns(&self.columns);
62        let batch = crate::Batch::from_physical_rows(self.internal_schema, rows);
63        let mut seen = std::collections::BTreeSet::new();
64        let positional_rows = self
65            .columns
66            .iter()
67            .any(|column| !seen.insert(column))
68            .then(|| {
69                crate::ColumnarBatch::from_batch(&self.columns, batch.clone())
70                    .into_positional_rows()
71            });
72        Ok(SQLResult::from_schema_rows_with_positions(
73            schema,
74            batch.into_result_rows(),
75            positional_rows,
76        ))
77    }
78
79    pub fn into_operator<'a>(self) -> Box<dyn crate::PhysicalOperator + 'a> {
80        match self.rows {
81            QueryRows::Rows(rows) => Box::new(crate::TableScan::from_physical_rows(
82                self.internal_schema,
83                rows,
84            )),
85            QueryRows::SharedSpill(rows) => Box::new(crate::SharedSpillScan::new(rows)),
86            QueryRows::ExistsKeySet(_) => {
87                panic!("EXISTS key-set output cannot become a physical operator")
88            }
89        }
90    }
91
92    pub fn into_public_operator<'a>(self) -> Box<dyn crate::PhysicalOperator + 'a> {
93        let columns = self.columns.clone();
94        let public_width = columns.len();
95        let operator = self.into_operator();
96        let positions = columns
97            .into_iter()
98            .enumerate()
99            .map(|(position, column)| (column, position))
100            .collect();
101        debug_assert!(operator.row_schema().len() >= public_width);
102        Box::new(crate::ColumnSelection::with_positions(operator, positions))
103    }
104
105    pub fn into_subquery_result(self) -> Result<crate::SubqueryResult, SQLError> {
106        let QueryOutput {
107            columns,
108            column_types: _,
109            internal_schema: schema,
110            rows,
111        } = self;
112        let rows: Box<dyn Iterator<Item = Result<crate::OwnedPhysicalRow, SQLError>> + Send> =
113            match rows {
114                QueryRows::Rows(rows) => Box::new(
115                    rows.into_iter()
116                        .map(move |row| Ok(crate::OwnedPhysicalRow::new(schema.clone(), row))),
117                ),
118                QueryRows::SharedSpill(rows) => Box::new(
119                    rows.read_rows()
120                        .map_err(physical_exec_error)?
121                        .map(|row| row.map_err(physical_exec_error)),
122                ),
123                QueryRows::ExistsKeySet(_) => {
124                    return Err(SQLError::Internal(
125                        "EXISTS key-set output cannot become a scalar subquery result".into(),
126                    ));
127                }
128            };
129        Ok(crate::SubqueryResult { columns, rows })
130    }
131}
132
133pub fn query_output_shared(
134    output: QueryOutput,
135    label: &str,
136) -> Result<crate::SharedSpill, SQLError> {
137    let QueryRows::SharedSpill(rows) = output.rows else {
138        return Err(SQLError::Internal(format!(
139            "{label} execution returned in-memory rows at an internal streaming boundary"
140        )));
141    };
142    Ok(rows)
143}