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