Skip to main content

uqa_sql/routines/
result_check.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The final statement of a SQL function body checked against the declared result, as `PostgreSQL`'s `check_sql_fn_retval` checks it at creation and before execution.
8
9use super::declaration::RoutineTypeCatalog;
10use crate::{
11    ast::{ColumnType, CreateFunction, FunctionReturns},
12    binding::statements::AnalyzedResult,
13    SQLError,
14};
15
16mod anonymous;
17pub(crate) use anonymous::validate_sql_tuple_result_with_control;
18mod production;
19pub(super) use production::declared_sql_function_result_type_with_control;
20pub use production::{
21    declared_sql_function_result_with_control, sql_function_composite_columns_with_control,
22    sql_function_result_layout_with_control,
23};
24pub(crate) mod retention;
25pub use anonymous::{
26    validate_anonymous_record_result, validate_procedural_record_identity,
27    validate_trigger_record_result,
28};
29
30/// Whether the routine returns nothing, one output value, or the complete output tuple.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum SQLFunctionResultKind {
33    Void,
34    Value,
35    Tuple,
36}
37
38/// A live attribute in the declared function result, in physical attribute order.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct SQLFunctionResultColumn {
41    pub name: String,
42    pub ty: ColumnType,
43}
44
45/// The SQL-owned result decision. A lone row value is distinct from a tuple whose individual columns need assignment coercion. Domains remain scalar, even when their base type is composite.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SQLFunctionResultLayout {
48    pub kind: SQLFunctionResultKind,
49    pub declared_type: ColumnType,
50    /// Descriptor of a lone returned row, captured before the statement executes.
51    pub source_record: Option<Vec<Option<ColumnType>>>,
52    /// Named composite attributes or OUT parameters; absent for scalar and unspecified record results.
53    pub columns: Option<Vec<SQLFunctionResultColumn>>,
54}
55
56/// Check the final statement without exposing its execution layout to callers that only validate a definition.
57pub fn check_sql_function_result(
58    types: &dyn RoutineTypeCatalog,
59    def: &CreateFunction,
60    last: Option<&AnalyzedResult>,
61) -> Result<(), SQLError> {
62    sql_function_result_layout(types, def, last).map(|_| ())
63}
64
65/// Decide whether the final statement returns a single value or its complete row, using the same assignment rules at creation and invocation.
66pub fn sql_function_result_layout(
67    types: &dyn RoutineTypeCatalog,
68    def: &CreateFunction,
69    last: Option<&AnalyzedResult>,
70) -> Result<SQLFunctionResultLayout, SQLError> {
71    sql_function_result_layout_with_control(
72        types,
73        def,
74        last,
75        &uqa_core::memory::ProductionControl::uncontrolled(),
76    )
77    .map(|layout| {
78        layout
79            .into_uncontrolled()
80            .expect("ordinary function result layout")
81    })
82}
83
84/// Resolve the result declaration independently of a final statement.
85pub fn declared_sql_function_result(
86    types: &dyn RoutineTypeCatalog,
87    def: &CreateFunction,
88) -> Result<SQLFunctionResultLayout, SQLError> {
89    declared_sql_function_result_with_control(
90        types,
91        def,
92        &uqa_core::memory::ProductionControl::uncontrolled(),
93    )
94    .map(|layout| {
95        layout
96            .into_uncontrolled()
97            .expect("ordinary function declaration layout")
98    })
99}
100
101/// Read the live descriptor of a named row value. An anonymous row's descriptor must come from expression analysis, rather than inspecting its values.
102pub fn sql_function_composite_columns(
103    types: &dyn RoutineTypeCatalog,
104    source: Option<&ColumnType>,
105) -> Result<Option<Vec<Option<ColumnType>>>, SQLError> {
106    sql_function_composite_columns_with_control(
107        types,
108        source,
109        &uqa_core::memory::ProductionControl::uncontrolled(),
110    )
111    .map(|columns| {
112        columns.map(|columns| {
113            columns
114                .into_uncontrolled()
115                .expect("ordinary composite result columns")
116        })
117    })
118}
119
120/// A whole returned record must match the caller's tuple descriptor; its fields are not assignment-coerced as independently selected columns are.
121pub fn validate_sql_function_record(
122    types: &dyn RoutineTypeCatalog,
123    source: &[Option<ColumnType>],
124    target: &[ColumnType],
125) -> Result<(), SQLError> {
126    if source.len() != target.len() {
127        return Err(record_mismatch(format!(
128            "Returned row contains {} attribute{}, but query expects {}.",
129            source.len(),
130            if source.len() == 1 { "" } else { "s" },
131            target.len()
132        )));
133    }
134    for (index, (source, target)) in source.iter().zip(target).enumerate() {
135        let Some(source) = source else {
136            return Err(record_mismatch(format!(
137                "Returned type unknown at ordinal position {}, but query expects {}.",
138                index + 1,
139                types.format_type(target)?
140            )));
141        };
142        let source_oid = crate::catalog::type_metadata::pg_type_oid(source);
143        let target_oid = crate::catalog::type_metadata::pg_type_oid(target);
144        let source_modifier = crate::catalog::type_metadata::pg_type_modifier(source);
145        let target_modifier = crate::catalog::type_metadata::pg_type_modifier(target);
146        if source_oid != target_oid || (target_modifier >= 0 && source_modifier != target_modifier)
147        {
148            return Err(record_mismatch(format!(
149                "Returned type {} at ordinal position {}, but query expects {}.",
150                types.format_type(source)?,
151                index + 1,
152                types.format_type(target)?
153            )));
154        }
155    }
156    Ok(())
157}
158
159fn record_mismatch(detail: String) -> SQLError {
160    SQLError::Diagnostic {
161        sqlstate: "42804".into(),
162        message: "function return row and query-specified return row do not match".into(),
163        detail: Some(detail),
164        hint: None,
165    }
166}
167
168/// A SQL set-returning function materializes one record descriptor for all non-null rows before the caller checks the declared result. Inspect borrowed values without copying their fields.
169pub fn validate_sql_function_record_rows(result: &crate::SQLResult) -> Result<(), SQLError> {
170    let mut descriptor = None;
171    for index in 0..result.rows.len() {
172        if let Some(uqa_core::Value::Row(row)) = result.value_at(index, 0) {
173            if let Some(fields) = row.field_types() {
174                if descriptor.is_some_and(|previous| previous != fields) {
175                    return Err(SQLError::Routine {
176                        sqlstate: "42804".into(),
177                        message: "rows returned by function are not all of the same row type"
178                            .into(),
179                    });
180                }
181                descriptor = Some(fields);
182            }
183        }
184    }
185    Ok(())
186}
187
188/// Validate the descriptor carried by the selected runtime row, including CASE branches and materialized intermediate rows whose record shapes differ.
189pub fn validate_sql_function_record_identity(
190    types: &dyn RoutineTypeCatalog,
191    source: &[uqa_core::RecordFieldType],
192    target: &[ColumnType],
193) -> Result<(), SQLError> {
194    if source.len() != target.len() {
195        return Err(record_mismatch(format!(
196            "Returned row contains {} attribute{}, but query expects {}.",
197            source.len(),
198            if source.len() == 1 { "" } else { "s" },
199            target.len(),
200        )));
201    }
202    for (index, (source, target)) in source.iter().zip(target).enumerate() {
203        let target_modifier = crate::catalog::type_metadata::pg_type_modifier(target);
204        if i64::from(source.oid) == crate::catalog::type_metadata::pg_type_oid(target)
205            && (target_modifier < 0 || i64::from(source.type_modifier) == target_modifier)
206        {
207            continue;
208        }
209        let source_name = if source.oid == 705 {
210            "unknown".into()
211        } else {
212            types.format_type_oid(source.oid)?
213        };
214        return Err(record_mismatch(format!(
215            "Returned type {source_name} at ordinal position {}, but query expects {}.",
216            index + 1,
217            types.format_type(target)?,
218        )));
219    }
220    Ok(())
221}
222
223#[cfg(test)]
224mod tests;