1use super::declaration::RoutineTypeCatalog;
10use crate::{
11 ast::{ColumnType, CreateFunction, FunctionReturns},
12 binding::statements::AnalyzedResult,
13 expr::composites,
14 type_resolution::canonical_routine_type_name,
15 SQLError,
16};
17
18mod anonymous;
19pub(crate) mod retention;
20pub use anonymous::{
21 validate_anonymous_record_result, validate_procedural_record_identity,
22 validate_trigger_record_result,
23};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum SQLFunctionResultKind {
28 Void,
29 Value,
30 Tuple,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct SQLFunctionResultColumn {
36 pub name: String,
37 pub ty: ColumnType,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct SQLFunctionResultLayout {
43 pub kind: SQLFunctionResultKind,
44 pub declared_type: ColumnType,
45 pub source_record: Option<Vec<Option<ColumnType>>>,
47 pub columns: Option<Vec<SQLFunctionResultColumn>>,
49}
50
51pub fn check_sql_function_result(
53 types: &dyn RoutineTypeCatalog,
54 def: &CreateFunction,
55 last: Option<&AnalyzedResult>,
56) -> Result<(), SQLError> {
57 sql_function_result_layout(types, def, last).map(|_| ())
58}
59
60pub fn sql_function_result_layout(
62 types: &dyn RoutineTypeCatalog,
63 def: &CreateFunction,
64 last: Option<&AnalyzedResult>,
65) -> Result<SQLFunctionResultLayout, SQLError> {
66 let mut layout = declared_sql_function_result(types, def)?;
67 if layout.kind == SQLFunctionResultKind::Void {
68 return Ok(layout);
69 }
70 let mismatch = |detail: String| -> Result<SQLError, SQLError> {
71 Ok(SQLError::Diagnostic {
72 sqlstate: "42P13".into(),
73 message: format!(
74 "return type mismatch in function declared to return {}",
75 types.format_type(&layout.declared_type)?
76 ),
77 detail: Some(detail),
78 hint: None,
79 })
80 };
81 let Some(columns) = last.and_then(AnalyzedResult::column_types) else {
82 return Err(mismatch(
83 "Function's final statement must be SELECT or INSERT/UPDATE/DELETE/MERGE RETURNING."
84 .into(),
85 )?);
86 };
87 if let [actual] = columns {
88 layout.source_record = last
89 .and_then(|result| result.record_fields(0))
90 .map(|fields| fields.to_vec())
91 .or(sql_function_composite_columns(types, actual.as_ref())?);
92 }
93 if layout.kind == SQLFunctionResultKind::Value {
94 let [actual] = columns else {
95 return Err(mismatch(
96 "Final statement must return exactly one column.".into(),
97 )?);
98 };
99 if let Some(actual) = actual {
100 if !crate::assignment_type_compatible(actual, &layout.declared_type) {
101 return Err(mismatch(format!(
102 "Actual return type is {}.",
103 types.format_type(actual)?
104 ))?);
105 }
106 }
107 return Ok(layout);
108 }
109 if !def.is_procedure {
110 if let [Some(actual)] = columns {
111 if crate::assignment_type_compatible(actual, &layout.declared_type) {
112 layout.kind = SQLFunctionResultKind::Value;
113 if matches!(actual, ColumnType::Record)
114 && matches!(layout.declared_type, ColumnType::Composite(_))
115 {
116 if let Some(source) = &layout.source_record {
117 check_composite_assignment(types, source, &layout)?;
118 }
119 }
120 return Ok(layout);
121 }
122 }
123 }
124 if let Some(expected) = &layout.columns {
125 for (position, actual) in columns.iter().enumerate() {
126 let Some(expected) = expected.get(position) else {
127 return Err(mismatch(
128 "Final statement returns too many columns.".into(),
129 )?);
130 };
131 if let Some(actual) = actual {
132 if !crate::assignment_type_compatible(actual, &expected.ty) {
133 return Err(mismatch(format!(
134 "Final statement returns {} instead of {} at column {}.",
135 types.format_type(actual)?,
136 types.format_type(&expected.ty)?,
137 position + 1
138 ))?);
139 }
140 }
141 }
142 if columns.len() < expected.len() {
143 return Err(mismatch("Final statement returns too few columns.".into())?);
144 }
145 }
146 Ok(layout)
147}
148
149pub fn declared_sql_function_result(
151 types: &dyn RoutineTypeCatalog,
152 def: &CreateFunction,
153) -> Result<SQLFunctionResultLayout, SQLError> {
154 let mut outputs = def.output_params();
155 if def.is_procedure || outputs.clone().nth(1).is_some() {
156 let columns = outputs
157 .map(|parameter| {
158 Ok(SQLFunctionResultColumn {
159 name: parameter.name.clone(),
160 ty: types.resolve_catalog_column_type_name(¶meter.type_name)?,
161 })
162 })
163 .collect::<Result<Vec<_>, SQLError>>()?;
164 return Ok(SQLFunctionResultLayout {
165 kind: if columns.is_empty() {
166 SQLFunctionResultKind::Void
167 } else {
168 SQLFunctionResultKind::Tuple
169 },
170 declared_type: ColumnType::Record,
171 source_record: None,
172 columns: Some(columns),
173 });
174 }
175 let type_name = match (outputs.next(), &def.returns) {
176 (Some(parameter), _) => parameter.type_name.as_str(),
177 (None, FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name }) => {
178 type_name.as_str()
179 }
180 (None, FunctionReturns::None | FunctionReturns::Table) => "void",
181 };
182 let declared_type = match canonical_routine_type_name(type_name).as_str() {
183 "void" => ColumnType::Void,
184 "record" => ColumnType::Record,
185 _ => types.resolve_catalog_column_type_name(type_name)?,
186 };
187 let (kind, columns) = match &declared_type {
188 ColumnType::Void => (SQLFunctionResultKind::Void, None),
189 ColumnType::Record => (SQLFunctionResultKind::Tuple, None),
190 ColumnType::Composite(reference) => {
191 let descriptor = composites::descriptor(types.composite_types(), reference.oid)?;
192 let columns = descriptor
193 .attributes
194 .iter()
195 .map(|attribute| SQLFunctionResultColumn {
196 name: attribute.name.clone(),
197 ty: attribute.ty.clone(),
198 })
199 .collect();
200 (SQLFunctionResultKind::Tuple, Some(columns))
201 }
202 _ => (SQLFunctionResultKind::Value, None),
203 };
204 Ok(SQLFunctionResultLayout {
205 kind,
206 declared_type,
207 source_record: None,
208 columns,
209 })
210}
211
212fn check_composite_assignment(
213 types: &dyn RoutineTypeCatalog,
214 source: &[Option<ColumnType>],
215 layout: &SQLFunctionResultLayout,
216) -> Result<(), SQLError> {
217 let target = layout.columns.as_deref().unwrap_or_default();
218 let detail = match source.len().cmp(&target.len()) {
219 std::cmp::Ordering::Less => Some("Input has too few columns.".into()),
220 std::cmp::Ordering::Greater => Some("Input has too many columns.".into()),
221 std::cmp::Ordering::Equal => source
222 .iter()
223 .zip(target)
224 .enumerate()
225 .find_map(|(index, (source, target))| {
226 source
227 .as_ref()
228 .filter(|source| !crate::assignment_type_compatible(source, &target.ty))
229 .map(|source| {
230 Ok::<_, SQLError>(format!(
231 "Cannot cast type {} to {} in column {}.",
232 types.format_type(source)?,
233 types.format_type(&target.ty)?,
234 index + 1
235 ))
236 })
237 })
238 .transpose()?,
239 };
240 if let Some(detail) = detail {
241 return Err(SQLError::Diagnostic {
242 sqlstate: "42846".into(),
243 message: format!(
244 "cannot cast type record to {}",
245 types.format_type(&layout.declared_type)?
246 ),
247 detail: Some(detail),
248 hint: None,
249 });
250 }
251 Ok(())
252}
253
254pub fn sql_function_composite_columns(
256 types: &dyn RoutineTypeCatalog,
257 source: Option<&ColumnType>,
258) -> Result<Option<Vec<Option<ColumnType>>>, SQLError> {
259 match source {
260 Some(ColumnType::Composite(reference)) => {
261 let descriptor = composites::descriptor(types.composite_types(), reference.oid)?;
262 Ok(Some(
263 descriptor
264 .attributes
265 .iter()
266 .map(|attribute| Some(attribute.ty.clone()))
267 .collect(),
268 ))
269 }
270 Some(ColumnType::Domain { base, .. }) => sql_function_composite_columns(types, Some(base)),
271 _ => Ok(None),
272 }
273}
274
275pub fn validate_sql_function_record(
277 types: &dyn RoutineTypeCatalog,
278 source: &[Option<ColumnType>],
279 target: &[ColumnType],
280) -> Result<(), SQLError> {
281 if source.len() != target.len() {
282 return Err(record_mismatch(format!(
283 "Returned row contains {} attribute{}, but query expects {}.",
284 source.len(),
285 if source.len() == 1 { "" } else { "s" },
286 target.len()
287 )));
288 }
289 for (index, (source, target)) in source.iter().zip(target).enumerate() {
290 let Some(source) = source else {
291 return Err(record_mismatch(format!(
292 "Returned type unknown at ordinal position {}, but query expects {}.",
293 index + 1,
294 types.format_type(target)?
295 )));
296 };
297 let source_oid = crate::catalog::type_metadata::pg_type_oid(source);
298 let target_oid = crate::catalog::type_metadata::pg_type_oid(target);
299 let source_modifier = crate::catalog::type_metadata::pg_type_modifier(source);
300 let target_modifier = crate::catalog::type_metadata::pg_type_modifier(target);
301 if source_oid != target_oid || (target_modifier >= 0 && source_modifier != target_modifier)
302 {
303 return Err(record_mismatch(format!(
304 "Returned type {} at ordinal position {}, but query expects {}.",
305 types.format_type(source)?,
306 index + 1,
307 types.format_type(target)?
308 )));
309 }
310 }
311 Ok(())
312}
313
314fn record_mismatch(detail: String) -> SQLError {
315 SQLError::Diagnostic {
316 sqlstate: "42804".into(),
317 message: "function return row and query-specified return row do not match".into(),
318 detail: Some(detail),
319 hint: None,
320 }
321}
322
323pub fn validate_sql_function_record_rows(result: &crate::SQLResult) -> Result<(), SQLError> {
325 let mut descriptor = None;
326 for index in 0..result.rows.len() {
327 if let Some(uqa_core::Value::Row(row)) = result.value_at(index, 0) {
328 if let Some(fields) = row.field_types() {
329 if descriptor.is_some_and(|previous| previous != fields) {
330 return Err(SQLError::Routine {
331 sqlstate: "42804".into(),
332 message: "rows returned by function are not all of the same row type"
333 .into(),
334 });
335 }
336 descriptor = Some(fields);
337 }
338 }
339 }
340 Ok(())
341}
342
343pub fn validate_sql_function_record_identity(
345 types: &dyn RoutineTypeCatalog,
346 source: &[uqa_core::RecordFieldType],
347 target: &[ColumnType],
348) -> Result<(), SQLError> {
349 if source.len() != target.len() {
350 return Err(record_mismatch(format!(
351 "Returned row contains {} attribute{}, but query expects {}.",
352 source.len(),
353 if source.len() == 1 { "" } else { "s" },
354 target.len(),
355 )));
356 }
357 for (index, (source, target)) in source.iter().zip(target).enumerate() {
358 let target_modifier = crate::catalog::type_metadata::pg_type_modifier(target);
359 if i64::from(source.oid) == crate::catalog::type_metadata::pg_type_oid(target)
360 && (target_modifier < 0 || i64::from(source.type_modifier) == target_modifier)
361 {
362 continue;
363 }
364 let source_name = if source.oid == 705 {
365 "unknown".into()
366 } else {
367 types.format_type_oid(source.oid)?
368 };
369 return Err(record_mismatch(format!(
370 "Returned type {source_name} at ordinal position {}, but query expects {}.",
371 index + 1,
372 types.format_type(target)?,
373 )));
374 }
375 Ok(())
376}
377
378#[cfg(test)]
379mod tests;