Skip to main content

uqa_sql/assignment/
routines.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7use crate::{
8    ast::ColumnType, expr::cast_value, type_resolution::canonical_routine_type_name, SQLError,
9};
10use uqa_core::Value;
11pub trait RoutineValueContext: super::AssignmentContext {
12    fn catalog_column_type(&self, name: &str) -> Option<ColumnType>;
13}
14pub fn coerce_routine_value(
15    context: &dyn RoutineValueContext,
16    value: &Value,
17    type_name: &str,
18) -> Result<Value, SQLError> {
19    coerce_routine_value_from(context, value, type_name, None)
20}
21
22pub fn coerce_routine_value_from(
23    context: &dyn RoutineValueContext,
24    value: &Value,
25    type_name: &str,
26    source: Option<&ColumnType>,
27) -> Result<Value, SQLError> {
28    match RoutineValueDescription::resolve(context, type_name) {
29        Some(description) => description.coerce(context, value, source),
30        None => cast_value(value, type_name),
31    }
32}
33
34/// The assignment semantics selected by a routine's declared type. This describes a conversion, never a converted value; callers may retain it only while the catalog and name-resolution scope that selected it remain unchanged.
35#[derive(Debug)]
36pub struct RoutineValueDescription(RoutineValueKind);
37
38#[derive(Debug)]
39enum RoutineValueKind {
40    Record,
41    Trigger,
42    AnyArray,
43    RefCursor,
44    Void,
45    Catalog(ColumnType),
46}
47
48impl RoutineValueDescription {
49    /// Resolve at the original conversion boundary. An unresolved name keeps the ordinary value-dependent cast path and is not a reusable description.
50    pub fn resolve(context: &dyn RoutineValueContext, name: &str) -> Option<Self> {
51        Some(Self(match canonical_routine_type_name(name).as_str() {
52            "record" => RoutineValueKind::Record,
53            "trigger" => RoutineValueKind::Trigger,
54            "anyarray" => RoutineValueKind::AnyArray,
55            "refcursor" => RoutineValueKind::RefCursor,
56            "void" => RoutineValueKind::Void,
57            _ => RoutineValueKind::Catalog(context.catalog_column_type(name)?),
58        }))
59    }
60
61    /// Admit a retained copy of the descriptor's owned type payload before copying it.
62    pub fn clone_with_control(
63        &self,
64        control: &uqa_core::memory::ProductionControl<'_>,
65    ) -> Result<uqa_core::memory::Produced<Self>, uqa_core::ValueRetentionError> {
66        let kind = match &self.0 {
67            RoutineValueKind::Record => RoutineValueKind::Record,
68            RoutineValueKind::Trigger => RoutineValueKind::Trigger,
69            RoutineValueKind::AnyArray => RoutineValueKind::AnyArray,
70            RoutineValueKind::RefCursor => RoutineValueKind::RefCursor,
71            RoutineValueKind::Void => RoutineValueKind::Void,
72            RoutineValueKind::Catalog(target) => {
73                let (target, memory) = target.clone_with_control(control)?.into_parts();
74                return control.finish(Self(RoutineValueKind::Catalog(target)), memory);
75            }
76        };
77        control.finish(Self(kind), control.empty_reservation())
78    }
79
80    /// Apply the original assignment kernel with live input/domain callbacks and session settings. The caller must revalidate its scope after evaluating the input and any preceding callback.
81    pub fn coerce(
82        &self,
83        context: &dyn RoutineValueContext,
84        value: &Value,
85        source: Option<&ColumnType>,
86    ) -> Result<Value, SQLError> {
87        match &self.0 {
88            RoutineValueKind::Record => match value {
89                Value::Record(_) | Value::Null => Ok(value.clone()),
90                Value::Datum(datum)
91                    if crate::expr::composites::datum_is_composite(datum, context)? =>
92                {
93                    Ok(value.clone())
94                }
95                Value::Row(row) if row.field_types().is_some() => Ok(value.clone()),
96                Value::Row(values) => Ok(Value::Record(
97                    values
98                        .iter()
99                        .cloned()
100                        .enumerate()
101                        .map(|(index, value)| (format!("f{}", index + 1), value))
102                        .collect::<Vec<_>>()
103                        .into(),
104                )),
105                _ => Err(SQLError::Routine {
106                    sqlstate: "42804".into(),
107                    message: "cannot cast non-composite value to type record".into(),
108                }),
109            },
110            RoutineValueKind::Trigger => match value {
111                Value::Record(_) | Value::Row(_) | Value::Null => Ok(value.clone()),
112                Value::Datum(datum)
113                    if crate::expr::composites::datum_is_composite(datum, context)? =>
114                {
115                    Ok(value.clone())
116                }
117                _ => Err(SQLError::Routine {
118                    sqlstate: "42804".into(),
119                    message: "trigger function must return a row or NULL".into(),
120                }),
121            },
122            RoutineValueKind::AnyArray => match value {
123                Value::Array(_) | Value::LegacyVector(_) | Value::List(_) | Value::Null => {
124                    Ok(value.clone())
125                }
126                _ => Err(SQLError::Routine {
127                    sqlstate: "42804".into(),
128                    message: "cannot cast non-array value to type anyarray".into(),
129                }),
130            },
131            RoutineValueKind::RefCursor => match value {
132                Value::Str(_) | Value::Null => Ok(value.clone()),
133                _ => Err(SQLError::Routine {
134                    sqlstate: "42804".into(),
135                    message: "cannot cast value to type refcursor".into(),
136                }),
137            },
138            RoutineValueKind::Void if matches!(value, Value::Null) => Ok(Value::Null),
139            RoutineValueKind::Void => Err(SQLError::Routine {
140                sqlstate: "42804".into(),
141                message: "cannot cast non-null value to type void".into(),
142            }),
143            RoutineValueKind::Catalog(target) => {
144                crate::assignment::conversion::coerce_assignment_value(
145                    context,
146                    value.clone(),
147                    target,
148                    source,
149                )
150            }
151        }
152    }
153}
154
155#[cfg(test)]
156mod tests;