Skip to main content

uqa_sql/routines/invocation/descriptions/
table.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The table caller retains a successful declaration, never its returned rows.
8
9use super::{Produced, ProductionControl, RoutineCallDescription, RoutineConversionEnvironment};
10use crate::{
11    ast::CreateFunction,
12    routines::{
13        declaration::RoutineTypeCatalog,
14        result_check::{declared_sql_function_result, SQLFunctionResultLayout},
15    },
16    SQLError,
17};
18use std::borrow::Cow;
19use uqa_core::ValueRetentionError;
20
21impl RoutineCallDescription {
22    /// Resolve the selected routine's declared table shape at the original call
23    /// boundary. Caller-specific anonymous-record checks and every value stay live.
24    pub fn table_result_layout<'a>(
25        &'a self,
26        types: &dyn RoutineTypeCatalog,
27        definition: &CreateFunction,
28        environment: RoutineConversionEnvironment<'_>,
29    ) -> Result<Cow<'a, SQLFunctionResultLayout>, SQLError> {
30        environment.control.check()?;
31        let reusable = self.is_current((environment.scope)().as_ref());
32        if reusable {
33            if let Some(saved) = self.table_result.get() {
34                return Ok(Cow::Borrowed(saved));
35            }
36        }
37        let layout = declared_sql_function_result(types, definition)?;
38        if reusable
39            && self.table_result.get().is_none()
40            && super::body::fixed_result(definition)
41            && self.is_current((environment.scope)().as_ref())
42        {
43            match retained_layout(&layout, &environment.control) {
44                Ok(saved) => {
45                    if self.table_result.set(saved).is_ok() {
46                        return Ok(Cow::Borrowed(
47                            self.table_result.get().expect("published table result"),
48                        ));
49                    }
50                }
51                Err(ValueRetentionError::Memory(_)) => {}
52                Err(error) => return Err(error.into()),
53            }
54        }
55        Ok(Cow::Owned(layout))
56    }
57}
58
59fn retained_layout(
60    layout: &SQLFunctionResultLayout,
61    control: &ProductionControl<'_>,
62) -> Result<Box<Produced<SQLFunctionResultLayout>>, ValueRetentionError> {
63    let allocation = control.reserve(size_of::<Produced<SQLFunctionResultLayout>>())?;
64    let (layout, memory) = layout.clone_with_control(control)?.into_parts();
65    Ok(Box::new(
66        control.finish(layout, control.combine(allocation, memory))?,
67    ))
68}