Skip to main content

uqa_sql/routines/inlining/
owned.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Owned selected calls materialize argument and binding destinations before publication.
8
9use super::{owned_arguments, RoutineInliningContext};
10use crate::{
11    ast::{
12        CreateFunction, FunctionBinding, FunctionDispatch, RoutineInvocationBinding,
13        RoutineVariadicMode,
14    },
15    plan::OwnedScalarExpr,
16    type_resolution::FunctionBindingParts,
17    SQLError, ScalarExpr,
18};
19use uqa_core::memory::{MemoryReservation, Produced, ProductionControl, ProductionVec};
20
21impl RoutineInliningContext<'_> {
22    /// Normalize a selected call without separating its scalar children from their allocation owners. Declined materialization returns the complete original input.
23    pub fn materialize_owned_call(
24        &self,
25        expression: OwnedScalarExpr,
26        control: &ProductionControl<'_>,
27    ) -> Result<OwnedScalarExpr, SQLError> {
28        control.check()?;
29        let ScalarExpr::Func {
30            binding: Some(binding),
31            args,
32            ..
33        } = &*expression
34        else {
35            return Ok(expression);
36        };
37        let Some((selected, arguments)) =
38            self.materialized_owned_arguments(binding, args, control)?
39        else {
40            return Ok(expression);
41        };
42        let output = expression.replace_call_arguments(arguments, control)?;
43        Ok(output.replace_call_binding(Some(selected), control)?)
44    }
45
46    pub(super) fn materialized_owned_arguments(
47        &self,
48        binding: &FunctionBinding,
49        arguments: &[ScalarExpr],
50        control: &ProductionControl<'_>,
51    ) -> Result<Option<(Produced<FunctionBinding>, OwnedScalarExpr)>, SQLError> {
52        let Some(function) =
53            super::super::selected_bound_function_with_control(self.routines, binding, control)?
54        else {
55            return Ok(None);
56        };
57        let Some(invocation) = binding.invocation.as_deref() else {
58            return Ok(None);
59        };
60        super::super::invocation::validate_specialized_definition(&function.def, invocation)?;
61        // Parameter modes and retained defaults do not change during polymorphic specialization; all coercion targets already come from the concrete invocation.
62        let definition = &function.def;
63        let Some(arguments) =
64            owned_arguments::prepare(self, definition, invocation, arguments, control)?
65        else {
66            return Ok(None);
67        };
68        let selected = materialized_binding(binding, definition, invocation, control)?;
69        let variadic =
70            selected
71                .invocation
72                .as_ref()
73                .and_then(|invocation| match invocation.variadic_mode {
74                    RoutineVariadicMode::Explicit { parameter_index } => Some((
75                        parameter_index,
76                        invocation
77                            .argument_positions
78                            .iter()
79                            .position(|index| *index == parameter_index),
80                    )),
81                    _ => None,
82                });
83        let mut arguments = arguments.into_container(control)?;
84        if let Some((_, position)) = variadic {
85            let position = position
86                .ok_or_else(|| SQLError::Internal("variadic call lost its argument".into()))?;
87            arguments = arguments.map_child(position, control, |argument| {
88                let marker = FunctionBinding::dispatched_with_control(
89                    FunctionDispatch::VariadicArgument,
90                    control,
91                )?;
92                let name = control.copy_text(&marker.name)?;
93                Ok::<_, SQLError>(OwnedScalarExpr::call(
94                    name,
95                    Some(marker),
96                    std::iter::once(argument),
97                    control,
98                )?)
99            })?;
100        }
101        Ok(Some((selected, arguments)))
102    }
103}
104
105pub(super) fn materialized_binding(
106    binding: &FunctionBinding,
107    definition: &CreateFunction,
108    invocation: &RoutineInvocationBinding,
109    control: &ProductionControl<'_>,
110) -> Result<Produced<FunctionBinding>, SQLError> {
111    FunctionBindingParts {
112        object_id: binding.object_id,
113        name: control.copy_text(&binding.name)?,
114        argument_types: texts(&binding.argument_types, control)?,
115        builtin: binding.builtin,
116        dispatch: binding.dispatch,
117        invocation: Some(materialized_invocation(definition, invocation, control)?),
118        value_binding: binding
119            .value_binding
120            .as_deref()
121            .map(|value| crate::plan::copy::copy_syntax_with_control(value, control))
122            .transpose()?,
123        resolution_error: binding
124            .resolution_error
125            .as_deref()
126            .map(|error| crate::plan::copy::copy_syntax_with_control(error, control))
127            .transpose()?,
128        input_collation: binding.input_collation,
129    }
130    .finish(control)
131}
132
133fn materialized_invocation(
134    definition: &CreateFunction,
135    invocation: &RoutineInvocationBinding,
136    control: &ProductionControl<'_>,
137) -> Result<Produced<RoutineInvocationBinding>, SQLError> {
138    let mut positions = ProductionVec::new(*control);
139    positions.reserve(definition.identity_arity())?;
140    for (index, parameter) in definition.params.iter().enumerate() {
141        control.check()?;
142        if super::super::body_parameters::is_sql_body_parameter(parameter) {
143            positions.push_copy(index)?;
144        }
145    }
146    let positions = positions.finish()?;
147    let mut targets = ProductionVec::new(*control);
148    targets.reserve(positions.len())?;
149    for index in &*positions {
150        targets.push_produced(control.copy_text(&invocation.parameter_types[*index])?)?;
151    }
152    let targets = targets.finish()?;
153    let mut sources = ProductionVec::new(*control);
154    sources.reserve(targets.len())?;
155    for target in &*targets {
156        let (target, memory) = control.copy_text(target)?.into_parts();
157        sources.push_produced(control.finish(Some(target), memory)?)?;
158    }
159    let sources = sources.finish()?;
160    let parameter_types = texts(&invocation.parameter_types, control)?;
161    let return_type = invocation
162        .return_type
163        .as_deref()
164        .map(|name| control.copy_text(name))
165        .transpose()?;
166    let mut memory = control.empty_reservation();
167    let value = RoutineInvocationBinding {
168        argument_positions: take(positions, &mut memory, control),
169        argument_targets: take(targets, &mut memory, control),
170        argument_sources: take(sources, &mut memory, control),
171        parameter_types: take(parameter_types, &mut memory, control),
172        return_type: return_type.map(|name| take(name, &mut memory, control)),
173        variadic_mode: match invocation.variadic_mode {
174            RoutineVariadicMode::Expanded { parameter_index } => {
175                RoutineVariadicMode::Explicit { parameter_index }
176            }
177            mode => mode,
178        },
179    };
180    Ok(control.finish(value, memory)?)
181}
182
183fn texts(
184    values: &[String],
185    control: &ProductionControl<'_>,
186) -> Result<Produced<Vec<String>>, SQLError> {
187    let mut output = ProductionVec::new(*control);
188    output.reserve(values.len())?;
189    for value in values {
190        output.push_produced(control.copy_text(value)?)?;
191    }
192    Ok(output.finish()?)
193}
194
195fn take<T>(
196    produced: Produced<T>,
197    memory: &mut Option<MemoryReservation>,
198    control: &ProductionControl<'_>,
199) -> T {
200    let (value, retained) = produced.into_parts();
201    *memory = control.combine(memory.take(), retained);
202    value
203}