Skip to main content

uqa_sql/
result.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Result rows returned by `Engine::sql`.
8
9use std::collections::BTreeMap;
10
11use uqa_core::Value;
12
13use crate::ast::ColumnType;
14use crate::RowSchema;
15
16mod labels;
17mod text;
18pub use labels::render_result_enum_labels;
19pub use text::format_postgres_text_with_catalog_and_control;
20pub use text::{format_postgres_text, format_postgres_text_with_catalog};
21
22pub type ResultRow = BTreeMap<String, Value>;
23
24/// Whether execution produced a row descriptor, independently of its column or row count.
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
26pub enum SQLResultKind {
27    #[default]
28    Command,
29    Rows,
30    /// An external result source did not provide descriptor information.
31    Unknown,
32}
33
34#[derive(Debug, Clone, Default)]
35pub struct SQLResult {
36    /// Descriptor presence, including zero-column and empty row results.
37    pub kind: SQLResultKind,
38    /// `PostgreSQL` command completion, including its command-specific row count. Execution sets this from the command that actually ran; row constructors leave it absent because rows alone do not identify a SQL command.
39    pub command_tag: Option<String>,
40    /// Column order as the SELECT clause specified.
41    pub columns: Vec<String>,
42    /// Statically bound SQL type for each output position. A missing entry
43    /// represents a type that has not yet been resolved, never a type inferred
44    /// from the first runtime value.
45    pub column_types: Vec<Option<ColumnType>>,
46    /// Complete, densely ordered native output metadata, including selected collations and nested record descriptors. External result sources may omit it.
47    pub row_schema: Option<RowSchema>,
48    /// One row per result document, with the named columns in
49    /// `columns`. Extra columns from `_score` etc. are included here
50    /// too.
51    pub rows: Vec<ResultRow>,
52    /// Positional values for result sets whose output contains repeated column
53    /// labels. `rows` remains available for named lookup, while this carrier
54    /// preserves values that cannot be represented by a string-keyed map.
55    #[doc(hidden)]
56    pub positional_rows: Option<Vec<Vec<Value>>>,
57    /// Number of rows touched by an INSERT / UPDATE / DELETE.
58    pub affected_rows: u64,
59}
60
61impl SQLResult {
62    /// Attach the completion chosen by the executing SQL command.
63    pub fn with_command_tag(mut self, tag: impl Into<String>) -> Self {
64        self.command_tag = Some(tag.into());
65        self
66    }
67
68    pub fn empty() -> Self {
69        Self::default()
70    }
71
72    pub fn from_rows(columns: Vec<String>, rows: Vec<ResultRow>) -> Self {
73        let column_types = vec![None; columns.len()];
74        Self {
75            kind: SQLResultKind::Rows,
76            command_tag: None,
77            columns,
78            column_types,
79            row_schema: None,
80            rows,
81            positional_rows: None,
82            affected_rows: 0,
83        }
84    }
85
86    pub fn from_rows_with_positions(
87        columns: Vec<String>,
88        rows: Vec<ResultRow>,
89        positional_rows: Option<Vec<Vec<Value>>>,
90    ) -> Self {
91        let column_types = vec![None; columns.len()];
92        Self::from_typed_rows_with_positions(columns, column_types, rows, positional_rows)
93    }
94
95    pub fn from_typed_rows_with_positions(
96        columns: Vec<String>,
97        column_types: Vec<Option<ColumnType>>,
98        mut rows: Vec<ResultRow>,
99        positional_rows: Option<Vec<Vec<Value>>>,
100    ) -> Self {
101        debug_assert_eq!(columns.len(), column_types.len());
102        debug_assert!(positional_rows.as_ref().is_none_or(|values| {
103            values.len() == rows.len() && values.iter().all(|row| row.len() == columns.len())
104        }));
105        if let Some(positional_rows) = positional_rows.as_ref() {
106            let compatibility_labels = unique_compatibility_labels(&columns);
107            for (row, positional) in rows.iter_mut().zip(positional_rows) {
108                for (label, value) in compatibility_labels.iter().zip(positional) {
109                    row.insert(label.clone(), value.clone());
110                }
111            }
112        }
113        Self {
114            kind: SQLResultKind::Rows,
115            command_tag: None,
116            columns,
117            column_types,
118            row_schema: None,
119            rows,
120            positional_rows,
121            affected_rows: 0,
122        }
123    }
124
125    /// Retain a native output descriptor independently of whether execution returned any rows.
126    pub fn from_schema_rows_with_positions(
127        schema: RowSchema,
128        rows: Vec<ResultRow>,
129        positional_rows: Option<Vec<Vec<Value>>>,
130    ) -> Self {
131        let mut result = Self::from_typed_rows_with_positions(
132            schema.columns().to_vec(),
133            schema.column_types().to_vec(),
134            rows,
135            positional_rows,
136        );
137        result.row_schema = Some(schema);
138        result
139    }
140
141    /// Borrow the native descriptor, or construct the metadata supplied by a legacy or external result source. Runtime values never determine declared types or collations.
142    pub fn row_schema(&self) -> std::borrow::Cow<'_, RowSchema> {
143        self.row_schema.as_ref().map_or_else(
144            || {
145                std::borrow::Cow::Owned(RowSchema::with_types(
146                    self.columns.clone(),
147                    self.column_types.clone(),
148                ))
149            },
150            std::borrow::Cow::Borrowed,
151        )
152    }
153
154    /// Return a result value by row and output-column position.
155    ///
156    /// Positional access is the canonical way to distinguish repeated output
157    /// labels. Named rows remain available for compatibility with existing
158    /// callers.
159    pub fn value_at(&self, row: usize, column: usize) -> Option<&Value> {
160        self.positional_rows
161            .as_ref()
162            .and_then(|rows| rows.get(row))
163            .and_then(|row| row.get(column))
164            .or_else(|| {
165                self.columns
166                    .get(column)
167                    .and_then(|name| self.rows.get(row)?.get(name))
168            })
169    }
170
171    pub fn from_affected(affected: u64) -> Self {
172        Self {
173            affected_rows: affected,
174            ..Self::default()
175        }
176    }
177}
178
179fn unique_compatibility_labels(columns: &[String]) -> Vec<String> {
180    let mut labels = Vec::with_capacity(columns.len());
181    for base in columns {
182        let mut label = base.clone();
183        let mut suffix = 1usize;
184        while labels.contains(&label) {
185            label = format!("{base}_{suffix}");
186            suffix += 1;
187        }
188        labels.push(label);
189    }
190    labels
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn result_metadata_survives_empty_rows_and_shared_result_clones() {
199        let schema = RowSchema::with_column_metadata(
200            None,
201            [
202                ("value".into(), Some(ColumnType::Text), Some(950)),
203                ("value".into(), Some(ColumnType::Text), Some(951)),
204            ],
205        );
206        for rows in [Vec::new(), vec![vec![Value::Null, Value::Null]]] {
207            let result = SQLResult::from_schema_rows_with_positions(
208                schema.clone(),
209                vec![ResultRow::new(); rows.len()],
210                Some(rows),
211            );
212            let retained = result.row_schema();
213            assert!(std::ptr::eq(retained.columns(), schema.columns()));
214            assert!(matches!(retained, std::borrow::Cow::Borrowed(_)));
215            assert!(std::ptr::eq(
216                retained.as_ref(),
217                result.row_schema.as_ref().unwrap()
218            ));
219            assert_eq!(result.kind, SQLResultKind::Rows);
220            assert_eq!(retained.column_collation(0), Some(950));
221            assert_eq!(retained.column_collation(1), Some(951));
222            assert_eq!(*result.clone().row_schema(), schema);
223        }
224    }
225
226    #[test]
227    fn repeated_postgresql_labels_keep_unique_named_compatibility_keys() {
228        let result = SQLResult::from_rows_with_positions(
229            vec!["value".into(), "value".into()],
230            vec![ResultRow::from([("value".into(), Value::Int(6))])],
231            Some(vec![vec![Value::Int(5), Value::Int(6)]]),
232        );
233
234        assert_eq!(result.columns, ["value", "value"]);
235        assert_eq!(result.rows[0].get("value"), Some(&Value::Int(5)));
236        assert_eq!(result.rows[0].get("value_1"), Some(&Value::Int(6)));
237        assert_eq!(result.value_at(0, 0), Some(&Value::Int(5)));
238        assert_eq!(result.value_at(0, 1), Some(&Value::Int(6)));
239    }
240}
241
242pub mod completion;
243pub mod vector;
244
245/// Execution measurements supplied to EXPLAIN rendering.
246pub struct ExplainAnalysis {
247    pub vector_searches: vector::ExplainVectorSearches,
248    pub elapsed: std::time::Duration,
249    pub rows: u64,
250    pub affected_rows: u64,
251}
252
253/// Structured physical-plan output captured before execution. Method-specific properties are rendered by the owning planner; execution only carries this diagnostic result to the renderer.
254#[derive(Debug, Clone, Default)]
255pub struct ExplainPhysicalPlan {
256    pub nodes: Vec<serde_json::Value>,
257}