Skip to main content

uqa_sql/routines/
compilation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Routine language validation and body lowering over declared types and fresh binding inputs.
8
9mod ownership;
10pub use ownership::bind_analyzed_sql_body_types_owned;
11
12use super::{
13    declaration::{
14        resolve_plpgsql_datum_types, routine_definition_error, routine_parameter_regrole_constants,
15        validate_routine_declaration, RoutineTypeCatalog,
16    },
17    merge_columns::StoredMergeColumnCatalog,
18    CompiledFunctionBody, RoutineResolution,
19};
20use crate::{
21    ast::{ColumnType, CreateFunction, FunctionBody, FunctionReturns, Statement},
22    binding::{
23        snapshot::BindingSnapshot,
24        stored_relations::{
25            self, StoredQueryBindingContext, StoredQueryNamespace, StoredQuerySequences,
26            StoredRelationCatalog,
27        },
28    },
29    catalog::{
30        regrole_dependencies::{StoredRegroleConstants, StoredRegroleResolver},
31        resolution::RelationLookupMode,
32    },
33    plan::UnifiedPlan,
34    plpgsql::PlpgsqlCatalog,
35    type_resolution::canonical_routine_type_name,
36    SQLError, ScalarExpr,
37};
38
39pub trait RoutineParserCatalog {
40    fn plpgsql_catalog(&self) -> Result<PlpgsqlCatalog, SQLError>;
41    fn parser_settings(&self) -> crate::parser::ParserSettings {
42        crate::parser::ParserSettings::default()
43    }
44    fn parser_notice(&self, _notice: crate::SQLNotice) {}
45}
46pub trait RoutineCompilationCatalog: crate::schema::dependencies::oid_alias::OidAliasInput {
47    fn has_registered_aggregate_function(&self, name: &str) -> bool;
48    fn binding_snapshot(&self) -> Result<BindingSnapshot, SQLError>;
49    fn stored_query_namespace(&self) -> StoredQueryNamespace;
50    /// External adapters retain their ordinary callback boundary; native implementations construct each captured name under this control.
51    fn binding_snapshot_with_control(
52        &self,
53        control: &uqa_core::memory::ProductionControl<'_>,
54    ) -> Result<crate::binding::production::ControlledBindingSnapshot, SQLError> {
55        control.check()?;
56        self.binding_snapshot()?.copy_with_control(control)
57    }
58    fn stored_query_namespace_with_control(
59        &self,
60        control: &uqa_core::memory::ProductionControl<'_>,
61    ) -> Result<crate::binding::production::ControlledStoredQueryNamespace, SQLError> {
62        control.check()?;
63        self.stored_query_namespace().copy_with_control(control)
64    }
65}
66#[derive(Clone, Copy)]
67pub struct RoutineCompilationContext<'a> {
68    pub types: &'a dyn RoutineTypeCatalog,
69    pub parsers: &'a dyn RoutineParserCatalog,
70    pub catalog: &'a dyn RoutineCompilationCatalog,
71    pub routines: &'a dyn RoutineResolution,
72    pub relations: &'a dyn StoredRelationCatalog,
73    pub sequences: &'a dyn StoredQuerySequences,
74    pub merge: &'a dyn StoredMergeColumnCatalog,
75    pub regroles: &'a dyn StoredRegroleResolver,
76}
77
78pub fn compile_function_body(
79    context: &RoutineCompilationContext<'_>,
80    def: &CreateFunction,
81) -> Result<CompiledFunctionBody, SQLError> {
82    compile_function_body_inner(
83        context,
84        def,
85        false,
86        crate::plpgsql::PLpgSQLCompileMode::Validate,
87    )
88}
89
90/// Compile executable procedural structure without validating unreached SQL fragments.
91pub fn compile_function_body_for_execution(
92    context: &RoutineCompilationContext<'_>,
93    def: &CreateFunction,
94) -> Result<CompiledFunctionBody, SQLError> {
95    compile_function_body_inner(
96        context,
97        def,
98        false,
99        crate::plpgsql::PLpgSQLCompileMode::Runtime,
100    )
101}
102
103pub fn compile_persisted_function_body(
104    context: &RoutineCompilationContext<'_>,
105    def: &CreateFunction,
106) -> Result<CompiledFunctionBody, SQLError> {
107    compile_function_body_inner(
108        context,
109        def,
110        true,
111        crate::plpgsql::PLpgSQLCompileMode::Validate,
112    )
113}
114
115/// The body `CREATE FUNCTION` compiles under `check_function_bodies = off`: the declaration is checked as always, a SQL-standard body, which the statement itself analyzes, is compiled, and a body given as a string is left unexamined, `None`, for each session to compile when it first calls the routine.
116pub fn defer_function_body(
117    context: &RoutineCompilationContext<'_>,
118    def: &CreateFunction,
119) -> Result<Option<CompiledFunctionBody>, SQLError> {
120    if matches!(def.body, FunctionBody::Statements(_)) {
121        return compile_function_body(context, def).map(Some);
122    }
123    validate_routine_signature(context, def)?.reject_with(context.regroles)?;
124    Ok(None)
125}
126
127/// The checks `CREATE FUNCTION` makes whatever `check_function_bodies` says: the language and the body form it accepts, the declared types, and the role constants of parameter defaults, which are returned for the body's own checks.
128pub(super) fn validate_routine_signature(
129    context: &RoutineCompilationContext<'_>,
130    def: &CreateFunction,
131) -> Result<StoredRegroleConstants, SQLError> {
132    if !matches!(def.language.as_str(), "plpgsql" | "sql") {
133        return Err(SQLError::Routine {
134            sqlstate: "42704".into(),
135            message: format!("language \"{}\" does not exist", def.language),
136        });
137    }
138    if def.language == "plpgsql" && matches!(def.body, FunctionBody::Statements(_)) {
139        return Err(routine_definition_error(
140            "inline SQL function body only valid for language SQL",
141        ));
142    }
143    let stored_regrole_constants = routine_parameter_regrole_constants(context.types, def);
144    stored_regrole_constants.validate_inputs_with(context.regroles)?;
145    validate_routine_declaration(def)?;
146    Ok(stored_regrole_constants)
147}
148
149/// PL/pgSQL's compiler rejects declared arguments of a trigger function, which reads its arguments from `TG_ARGV`.
150fn reject_trigger_function_arguments(def: &CreateFunction) -> Result<(), SQLError> {
151    let returns_trigger = matches!(
152        &def.returns,
153        FunctionReturns::Scalar { type_name } if canonical_routine_type_name(type_name) == "trigger"
154    );
155    if returns_trigger && def.identity_arity() != 0 {
156        return Err(SQLError::Diagnostic {
157            sqlstate: "42P13".into(),
158            message: "trigger functions cannot have declared arguments".into(),
159            detail: None,
160            hint: Some(
161                "The arguments of the trigger can be accessed through TG_NARGS and TG_ARGV instead."
162                    .into(),
163            ),
164        });
165    }
166    Ok(())
167}
168
169fn compile_function_body_inner(
170    context: &RoutineCompilationContext<'_>,
171    def: &CreateFunction,
172    persisted_definition: bool,
173    mode: crate::plpgsql::PLpgSQLCompileMode,
174) -> Result<CompiledFunctionBody, SQLError> {
175    with_parser_context(context.parsers, || {
176        compile_body(context, def, persisted_definition, mode)
177    })
178}
179
180/// Read live lexical settings only after the routine's own configuration has been applied, and deliver parser notices even if compilation fails.
181pub fn with_parser_context<T>(
182    parsers: &dyn RoutineParserCatalog,
183    compile: impl FnOnce() -> Result<T, SQLError>,
184) -> Result<T, SQLError> {
185    let (result, metadata) = crate::parser::with_settings(parsers.parser_settings(), compile);
186    for notice in metadata.notices.iter() {
187        parsers.parser_notice(notice.clone());
188    }
189    result
190}
191
192fn compile_body(
193    context: &RoutineCompilationContext<'_>,
194    def: &CreateFunction,
195    persisted_definition: bool,
196    mode: crate::plpgsql::PLpgSQLCompileMode,
197) -> Result<CompiledFunctionBody, SQLError> {
198    let mut stored_regrole_constants = validate_routine_signature(context, def)?;
199    match def.language.as_str() {
200        "plpgsql" => {
201            stored_regrole_constants.reject_with(context.regroles)?;
202            reject_trigger_function_arguments(def)?;
203            let catalog = context.parsers.plpgsql_catalog()?;
204            let mut function =
205                crate::plpgsql::parse_function_with_catalog_mode(def, &catalog, mode)?;
206            resolve_plpgsql_datum_types(context.types, &mut function)?;
207            Ok(CompiledFunctionBody::PLpgSQL(function))
208        }
209        "sql" => {
210            let (statements, bind_catalog_dependencies) = match &def.body {
211                FunctionBody::Source(source) => {
212                    stored_regrole_constants.reject_with(context.regroles)?;
213                    (
214                        crate::compile(source).map_err(|error| def.source_body_error(error))?,
215                        false,
216                    )
217                }
218                FunctionBody::Statements(statements) => (statements.clone(), true),
219            };
220            let mut plans = compile_sql_routine_plans(
221                context,
222                def,
223                statements,
224                bind_catalog_dependencies,
225                persisted_definition && matches!(def.body, FunctionBody::Statements(_)),
226            )?;
227            if bind_catalog_dependencies {
228                for plan in &mut plans {
229                    stored_regrole_constants.collect_plan(plan);
230                }
231                stored_regrole_constants.reject_with(context.regroles)?;
232            }
233            Ok(CompiledFunctionBody::SQL(plans))
234        }
235        _ => unreachable!("routine language was validated above"),
236    }
237}
238
239fn compile_sql_routine_plans(
240    context: &RoutineCompilationContext<'_>,
241    def: &CreateFunction,
242    statements: Vec<Statement>,
243    bind_catalog_dependencies: bool,
244    persisted_definition: bool,
245) -> Result<Vec<UnifiedPlan>, SQLError> {
246    let positional_parameters =
247        super::body_validation::routine_parameter_values(context.types, def);
248    let parameters = super::body_parameters::sql_body_parameter_scope(def, &positional_parameters)?;
249    statements
250        .into_iter()
251        .map(|statement| {
252            let mut plan = lower_sql_routine_statement(
253                context,
254                statement,
255                SQLRoutineLowering {
256                    bind_catalog_dependencies,
257                    persisted_definition,
258                    preserve_target_expressions: false,
259                },
260            )?;
261            // A SQL-standard body keeps definition-time names. Source syntax
262            // stays unbound so statement reanalysis can use the current path;
263            // successful first-use analysis retains its own type identities.
264            if bind_catalog_dependencies {
265                let binding = context.catalog.binding_snapshot()?;
266                crate::binding::bind_routine_parameter_references(
267                    context.routines,
268                    &mut plan,
269                    &positional_parameters,
270                    &binding.context(),
271                    &parameters,
272                )?;
273                if let UnifiedPlan::Query(query) = &mut plan {
274                    crate::binding::bind_query_plan_routines_for_storage(
275                        context.routines,
276                        query,
277                        &positional_parameters,
278                        &binding.context(),
279                        None,
280                    )?;
281                }
282            }
283            // Stored definitions retain their analyzed logical expressions;
284            // immutable evaluation belongs to invocation planning.
285            Ok(plan)
286        })
287        .collect()
288}
289
290/// How a SQL routine statement is lowered from its stored syntax.
291#[derive(Clone, Copy)]
292pub struct SQLRoutineLowering {
293    /// Bind relations, sequences and `MERGE` target columns of catalog-owned syntax.
294    pub bind_catalog_dependencies: bool,
295    /// The syntax comes from a persisted definition, whose legacy call markers are upgraded.
296    pub persisted_definition: bool,
297    /// Keep `MERGE` target columns as written.
298    pub preserve_target_expressions: bool,
299}
300
301/// Lower one statement of a SQL routine body with its relations bound, before routine calls are bound.
302pub fn lower_sql_routine_statement(
303    context: &RoutineCompilationContext<'_>,
304    mut statement: Statement,
305    lowering: SQLRoutineLowering,
306) -> Result<UnifiedPlan, SQLError> {
307    if lowering.bind_catalog_dependencies {
308        validate_sql_standard_statement(&statement)?;
309    }
310    if lowering.bind_catalog_dependencies && !lowering.preserve_target_expressions {
311        super::merge_columns::normalize_stored_merge_target_columns(context.merge, &mut statement)?;
312    }
313    let mut plan = UnifiedPlan::lower_with(statement, &|name: &str| {
314        context.catalog.has_registered_aggregate_function(name)
315    });
316    if lowering.persisted_definition {
317        plan.rewrite_scalar_expressions(&mut |expression| {
318            let ScalarExpr::Func {
319                name,
320                binding,
321                args,
322                ..
323            } = expression
324            else {
325                return;
326            };
327            crate::ast::FunctionBinding::upgrade_legacy_serialized_dispatch(name, binding);
328            crate::ast::FunctionBinding::upgrade_legacy_array_slices(
329                binding,
330                args.len(),
331                |index| matches!(args[index], ScalarExpr::Literal(uqa_core::Value::Null)),
332            );
333        });
334    }
335    if lowering.bind_catalog_dependencies {
336        match &mut plan {
337            UnifiedPlan::Query(query) => {
338                let namespace = context.catalog.stored_query_namespace();
339                stored_relations::bind_stored_query_relations(
340                    &StoredQueryBindingContext {
341                        relations: context.relations,
342                        lookup_mode: if lowering.persisted_definition {
343                            RelationLookupMode::Bound
344                        } else {
345                            RelationLookupMode::Dynamic
346                        },
347                        sequences: context.sequences,
348                        temporary_schema: &namespace.temporary_schema,
349                        transition_relations: &namespace.transition_relations,
350                    },
351                    query,
352                    "SQL routine body",
353                    false,
354                    lowering.persisted_definition,
355                )?;
356            }
357            UnifiedPlan::Command(_) => {
358                crate::binding::stored_routines::mark_catalog_statement_relations_bound(&mut plan)?;
359            }
360        }
361    }
362    Ok(plan)
363}
364
365/// SQL-standard bodies retain analyzed queries and DML, never utility commands. Use the same command name as ordinary SQL diagnostics.
366pub(super) fn validate_sql_standard_statement(statement: &Statement) -> Result<(), SQLError> {
367    match sql_standard_utility(statement) {
368        Some(command) => Err(sql_standard_utility_error(&command)),
369        None => Ok(()),
370    }
371}
372
373fn sql_standard_utility(statement: &Statement) -> Option<Box<crate::plan::CommandPlan>> {
374    match statement {
375        Statement::Select(_)
376        | Statement::Values { .. }
377        | Statement::Insert(_)
378        | Statement::Update(_)
379        | Statement::Delete(_)
380        | Statement::Merge(_) => None,
381        _ => match UnifiedPlan::lower(statement.clone()) {
382            UnifiedPlan::Command(command) => Some(command),
383            UnifiedPlan::Query(_) => None,
384        },
385    }
386}
387
388fn sql_standard_utility_error(command: &crate::plan::CommandPlan) -> SQLError {
389    SQLError::Unsupported(format!(
390        "{} is not yet supported in unquoted SQL function body",
391        crate::result::completion::command_tag_name(command)
392    ))
393}
394
395/// `PostgreSQL` transforms the query inputs of CTAS, EXPLAIN and cursors, and resolves CALL, before rejecting the resulting utility. Other utility targets remain unexamined.
396pub(super) fn validate_sql_standard_statement_inputs(
397    context: &RoutineCompilationContext<'_>,
398    overloads: &super::resolution::RoutineOverloadContext<'_>,
399    statement: &Statement,
400    params: &[crate::SQLParam],
401    parameters: &crate::binding::RoutineParameterScope,
402) -> Result<(), SQLError> {
403    use crate::plan::CommandPlan;
404    let Some(command) = sql_standard_utility(statement) else {
405        return Ok(());
406    };
407    let error = sql_standard_utility_error(&command);
408    let plan = match *command {
409        CommandPlan::Explain { body, .. } => *body,
410        CommandPlan::CreateTableAs { query, .. }
411        | CommandPlan::CreateMaterializedView { query, .. }
412        | CommandPlan::DeclareCursor { query, .. } => UnifiedPlan::Query(query),
413        command @ CommandPlan::Call { .. } => UnifiedPlan::Command(Box::new(command)),
414        _ => return Err(error),
415    };
416    analyze_sql_standard_utility_input(context, overloads, plan, params, parameters)?;
417    Err(error)
418}
419
420fn analyze_sql_standard_utility_input(
421    context: &RoutineCompilationContext<'_>,
422    overloads: &super::resolution::RoutineOverloadContext<'_>,
423    mut plan: UnifiedPlan,
424    params: &[crate::SQLParam],
425    parameters: &crate::binding::RoutineParameterScope,
426) -> Result<(), SQLError> {
427    use crate::plan::CommandPlan;
428    if let UnifiedPlan::Command(command) = plan {
429        match *command {
430            CommandPlan::Explain { body, .. } => {
431                return analyze_sql_standard_utility_input(
432                    context, overloads, *body, params, parameters,
433                )
434            }
435            CommandPlan::CreateTableAs { query, .. }
436            | CommandPlan::CreateMaterializedView { query, .. }
437            | CommandPlan::DeclareCursor { query, .. } => plan = UnifiedPlan::Query(query),
438            command => plan = UnifiedPlan::Command(Box::new(command)),
439        }
440    }
441    let binding = context.catalog.binding_snapshot()?;
442    if matches!(&plan, UnifiedPlan::Command(command) if matches!(command.as_ref(), CommandPlan::Call { .. }))
443    {
444        crate::binding::bind_routine_parameter_references(
445            context.routines,
446            &mut plan,
447            params,
448            &binding.context(),
449            parameters,
450        )?;
451        super::body_validation::analyze_body_statement(
452            &super::body_validation::SQLBodyValidationContext {
453                compilation: *context,
454                overloads: super::resolution::RoutineOverloadContext {
455                    catalog: overloads.catalog,
456                },
457            },
458            &plan,
459            params,
460            &binding,
461            false,
462        )?;
463    } else {
464        crate::binding::analyze_routine_body_inputs(
465            context.routines,
466            &plan,
467            params,
468            &binding.context(),
469            context.catalog,
470            Some(parameters),
471        )?;
472    }
473    Ok(())
474}
475
476/// A successfully analyzed body keeps resolved type identities independently of
477/// its raw source. Domain coercions still resolve current constraint definitions.
478pub fn bind_analyzed_sql_body_types(
479    types: &dyn RoutineTypeCatalog,
480    plan: &mut UnifiedPlan,
481) -> Result<(), SQLError> {
482    crate::binding::stored_types::bind_unified_plan_type_identities(plan, &mut |name| {
483        let resolved = types.resolve_catalog_column_type(name);
484        let mut element = resolved.as_ref();
485        while let Some(ColumnType::Array(inner)) = element {
486            element = Some(inner.as_ref());
487        }
488        let domain = matches!(element, Some(ColumnType::Domain { .. }));
489        Ok(resolved.filter(|_| !domain))
490    })
491}
492
493#[cfg(test)]
494mod tests;