Skip to main content

uqa_sql/routines/
dependencies.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Bind stored routine relation, column, and routine identities against fresh catalog inputs.
8
9use super::compilation::RoutineCompilationContext;
10use crate::{
11    ast::{CreateFunction, FunctionBody},
12    binding::{
13        bind_expression_plan_routines_for_storage,
14        stored_columns::StoredSourceCatalog,
15        stored_relations::bind_stored_statement_relations,
16        stored_routines::{
17            bind_catalog_statement_routines, bind_prepared_catalog_statement_routines,
18            CatalogRoutineContext,
19        },
20        syntax_sites::expression_syntax_sites,
21    },
22    catalog::{resolution::RelationLookupMode, stored_ast},
23    plan::ExpressionPlan,
24    RowSchema, SQLError,
25};
26
27#[derive(Clone, Copy)]
28pub enum RoutineCompilationMode {
29    Definition,
30    Persisted,
31}
32
33pub fn bind_routine_definition_dependencies(
34    context: &RoutineCompilationContext<'_>,
35    sources: &dyn StoredSourceCatalog,
36    overloads: &super::resolution::RoutineOverloadContext<'_>,
37    def: &mut CreateFunction,
38    mode: RoutineCompilationMode,
39) -> Result<bool, SQLError> {
40    let mut changed = false;
41    if matches!(mode, RoutineCompilationMode::Persisted) {
42        if let FunctionBody::Statements(statements) = &mut def.body {
43            for statement in statements {
44                changed |= crate::binding::legacy_patterns::restore_statement(
45                    statement,
46                    context.routines,
47                )?;
48            }
49        }
50        for default in def
51            .params
52            .iter_mut()
53            .filter_map(|parameter| parameter.default.as_mut())
54        {
55            changed |=
56                crate::binding::legacy_patterns::restore_expression(default, context.routines)
57                    .map_err(SQLError::Internal)?;
58        }
59    }
60    changed |= bind_sql_standard_body(context, sources, overloads, def, mode)?;
61    for parameter in &mut def.params {
62        let Some(default) = &mut parameter.default else {
63            continue;
64        };
65        let lowered = ExpressionPlan::lower_with(default.clone(), &|name: &str| {
66            context.catalog.has_registered_aggregate_function(name)
67        });
68        let mut plan = lowered.clone();
69        let binding = context.catalog.binding_snapshot()?;
70        let default_type = bind_expression_plan_routines_for_storage(
71            context.routines,
72            &mut plan,
73            &[],
74            &binding.context(),
75            &RowSchema::default(),
76        )?;
77        let default_type =
78            if crate::type_resolution::routine_polymorphic_type(&parameter.type_name).is_some() {
79                default_type
80            } else {
81                Some(
82                    context
83                        .types
84                        .resolve_catalog_column_type_name(&parameter.type_name)?
85                        .without_type_modifiers(),
86                )
87            };
88        let default_type =
89            super::defaults::default_expression_type(&parameter.type_name, default, default_type);
90        if parameter.default_type != default_type {
91            parameter.default_type = default_type;
92            changed = true;
93        }
94        let sites = expression_syntax_sites(&lowered, &plan)?;
95        changed |= stored_ast::bind_stored_expression_sites(default, &sites)?;
96        // A default is assigned to its parameter.
97        if let Some(ty) = user_defined_type(context, &parameter.type_name)? {
98            changed |= stored_ast::fold_assigned_stored_literal(
99                default,
100                &ty,
101                context.routines.enum_labels(),
102            )?;
103        }
104    }
105    Ok(changed)
106}
107
108/// Bind a copy of every statement of a SQL-standard body and carry the bound routine identities, user-defined type identities and enum constants back into the stored statements, then convert the result literals the final statement assigns to the declared result. A name resolves to a parameter only when no column of its statement takes it, as `sql_fn_post_column_ref` resolves it; the final statement's result is checked when the body is validated.
109fn bind_sql_standard_body(
110    context: &RoutineCompilationContext<'_>,
111    sources: &dyn StoredSourceCatalog,
112    overloads: &super::resolution::RoutineOverloadContext<'_>,
113    def: &mut CreateFunction,
114    mode: RoutineCompilationMode,
115) -> Result<bool, SQLError> {
116    if !matches!(def.body, FunctionBody::Statements(_)) {
117        return Ok(false);
118    }
119    // Declaration errors precede body input functions, which can execute domain checks.
120    super::compilation::validate_routine_signature(context, def)?;
121    let positional = super::body_validation::routine_parameter_values(context.types, def);
122    let parameters = super::body_parameters::sql_body_parameter_scope(def, &positional)?;
123    let result_types = def_result_types(context, &def.params, &def.returns)?;
124    let recording = matches!(mode, RoutineCompilationMode::Definition)
125        .then(|| super::body_parameters::ParameterRecording::new(context, def))
126        .transpose()?;
127    let FunctionBody::Statements(statements) = &mut def.body else {
128        return Ok(false);
129    };
130    let lowering = super::compilation::SQLRoutineLowering {
131        bind_catalog_dependencies: true,
132        persisted_definition: matches!(mode, RoutineCompilationMode::Persisted),
133        preserve_target_expressions: true,
134    };
135    let mut changed = false;
136    for statement in statements.iter_mut() {
137        super::compilation::validate_sql_standard_statement_inputs(
138            context,
139            overloads,
140            statement,
141            &positional,
142            &parameters,
143        )?;
144        changed |= bind_stored_statement_relations(
145            context.relations,
146            statement,
147            match mode {
148                RoutineCompilationMode::Definition => RelationLookupMode::Dynamic,
149                RoutineCompilationMode::Persisted => RelationLookupMode::Bound,
150            },
151            matches!(mode, RoutineCompilationMode::Persisted),
152            "SQL routine body",
153        )?;
154        changed |=
155            super::merge_columns::bind_stored_merge_target_columns(context.merge, statement)?;
156        changed |= sources.stored_source_columns().bind_statement(statement)?;
157        if let Some(recording) = &recording {
158            changed |= recording.record(statement)?;
159        }
160        let mut lowered =
161            super::compilation::lower_sql_routine_statement(context, statement.clone(), lowering)?;
162        let binding = context.catalog.binding_snapshot()?;
163        crate::binding::bind_routine_parameter_references(
164            context.routines,
165            &mut lowered,
166            &positional,
167            &binding.context(),
168            &parameters,
169        )?;
170        let routines = CatalogRoutineContext {
171            routines: context.routines,
172            binding: &binding.context(),
173        };
174        let routines = match mode {
175            RoutineCompilationMode::Definition => {
176                // Fresh syntax completes input/target analysis before the next statement. Retain its original sites when storing converted constants.
177                let mut prepared = lowered.clone();
178                crate::binding::prepare_routine_body_inputs(
179                    context.routines,
180                    &mut prepared,
181                    &positional,
182                    routines.binding,
183                    context.catalog,
184                    None,
185                )?;
186                bind_prepared_catalog_statement_routines(
187                    &routines,
188                    &lowered,
189                    &prepared,
190                    &positional,
191                )?
192            }
193            // A stored definition keeps analyzed targets, including dropped MERGE attributes whose expressions remain dependencies. Execution normalizes its own copy against live target identities.
194            RoutineCompilationMode::Persisted => {
195                bind_catalog_statement_routines(&routines, &lowered, &positional)?
196            }
197        };
198        changed |= stored_ast::bind_stored_statement_sites(statement, &routines.sites)?;
199    }
200    if let Some(statement) = statements.last_mut() {
201        changed |= fold_sql_function_result(context, result_types, statement)?;
202    }
203    Ok(changed)
204}
205
206/// A declared routine type that is user-defined, the only kind whose `unknown` literals parse analysis converts to stored enum constants. Declarations name user-defined types by identity.
207fn user_defined_type(
208    context: &RoutineCompilationContext<'_>,
209    name: &str,
210) -> Result<Option<crate::ColumnType>, SQLError> {
211    if crate::ast::UserTypeIdentity::parse(name).is_none() {
212        return Ok(None);
213    }
214    context.routines.resolve_type_name(name)
215}
216
217/// The column types a SQL function's final statement is coerced to: the `OUT` and `TABLE` parameters, or else the declared result. Built-in and pseudo-type columns are `None`.
218fn def_result_types(
219    context: &RoutineCompilationContext<'_>,
220    params: &[crate::ast::FunctionParam],
221    returns: &crate::ast::FunctionReturns,
222) -> Result<Vec<Option<crate::ColumnType>>, SQLError> {
223    use crate::ast::{FunctionParamMode, FunctionReturns};
224    let outputs = params
225        .iter()
226        .filter(|parameter| {
227            matches!(
228                parameter.mode,
229                FunctionParamMode::Out | FunctionParamMode::InOut | FunctionParamMode::Table
230            )
231        })
232        .collect::<Vec<_>>();
233    let names = if outputs.is_empty() {
234        match returns {
235            FunctionReturns::Scalar { type_name } | FunctionReturns::SetOf { type_name } => {
236                vec![type_name.as_str()]
237            }
238            FunctionReturns::None | FunctionReturns::Table => Vec::new(),
239        }
240    } else {
241        outputs
242            .iter()
243            .map(|parameter| parameter.type_name.as_str())
244            .collect()
245    };
246    names
247        .into_iter()
248        .map(|name| user_defined_type(context, name))
249        .collect()
250}
251
252/// `check_sql_fn_retval` coerces each result column of the final statement to its declared type; an `unknown` literal selected directly becomes a constant of that type.
253fn fold_sql_function_result(
254    context: &RoutineCompilationContext<'_>,
255    types: Vec<Option<crate::ColumnType>>,
256    statement: &mut crate::ast::Statement,
257) -> Result<bool, SQLError> {
258    let crate::ast::Statement::Select(select) = statement else {
259        return Ok(false);
260    };
261    if types.is_empty()
262        || select.set_op.is_some()
263        || !select.values.is_empty()
264        || select.projections.len() != types.len()
265    {
266        return Ok(false);
267    }
268    let mut changed = false;
269    for (projection, ty) in select.projections.iter_mut().zip(&types) {
270        let Some(ty) = ty else {
271            continue;
272        };
273        changed |= stored_ast::fold_assigned_stored_literal(
274            &mut projection.expr,
275            ty,
276            context.routines.enum_labels(),
277        )?;
278    }
279    Ok(changed)
280}