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