Skip to main content

uqa_sql/binding/
routine_parameters.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! The parameters of a SQL routine as the outermost scope of the names in its body, resolved as `PostgreSQL`'s `sql_fn_post_column_ref` resolves them: a name is a parameter only when no column of any query level and no relation takes it, so a column of a queried table shadows the parameter of the same name, which the routine's own name then qualifies.
8
9use super::{BindingContext, QueryPlan, RowSchema, SQLError, SQLParam, ScalarExpr, SchemaScope};
10use crate::ast::{ColumnType, InternalRelationId};
11use crate::catalog::resolution::RelationLookupMode;
12use crate::plan::{CommandPlan, ExpressionPlan, ProjectionPlan, UnifiedPlan};
13use crate::routines::RoutineResolution;
14use std::sync::LazyLock;
15
16mod production;
17
18/// The opaque relation whose attributes mark the parameter slots of every row scope the parameter layer reaches, so that a name resolves to a parameter only through the layer itself.
19static ROUTINE_PARAMETERS: LazyLock<InternalRelationId> =
20    LazyLock::new(InternalRelationId::allocate);
21
22/// The parameters a SQL routine's body can name, in positional order.
23#[derive(Clone)]
24pub struct RoutineParameterScope {
25    data: std::sync::Arc<uqa_core::memory::Produced<RoutineParameterData>>,
26}
27
28struct RoutineParameterData {
29    /// The routine's unqualified name, which qualifies its parameter names.
30    function: String,
31    /// The parameter names; an unnamed parameter has an empty name and is reachable only by position.
32    names: Vec<String>,
33    schema: RowSchema,
34}
35
36impl RoutineParameterScope {
37    /// The parameters `names`, typed by `types`, of the routine whose unqualified name is `function`.
38    #[must_use]
39    pub fn new(function: &str, names: Vec<String>, types: Vec<Option<ColumnType>>) -> Self {
40        let visible = RowSchema::with_qualified_types(function, names.clone(), types.clone());
41        let marked = RowSchema::with_internal_relation_types(*ROUTINE_PARAMETERS, types);
42        let control = uqa_core::memory::ProductionControl::uncontrolled();
43        Self {
44            data: control
45                .finish(
46                    RoutineParameterData {
47                        function: function.to_owned(),
48                        names,
49                        schema: RowSchema::with_trailing_internal_aliases(&visible, &marked),
50                    },
51                    None,
52                )
53                .expect("ordinary routine parameter scope")
54                .into_shared(&control)
55                .expect("ordinary shared parameter scope"),
56        }
57    }
58
59    /// The parameters as a row scope, the outermost scope of every name in the body.
60    #[must_use]
61    pub fn schema(&self) -> &RowSchema {
62        &self.data.schema
63    }
64
65    /// The position of the parameter that occupies `slot` of `schema`.
66    fn position_at(schema: &RowSchema, slot: usize) -> Option<usize> {
67        schema
68            .unique_internal_column_for_slot(slot)
69            .filter(|column| column.relation() == *ROUTINE_PARAMETERS)
70            .map(crate::ast::InternalColumnRef::attribute)
71    }
72
73    /// Whether the parameter layer is part of `schema`.
74    fn reaches(schema: &RowSchema) -> bool {
75        schema.internal_slot(ROUTINE_PARAMETERS.column(0)).is_some()
76    }
77
78    /// The position of the parameter that `expression` names in `schema`, or `None` when it names a column, a relation, or nothing the layer holds.
79    fn parameter(&self, expression: &ScalarExpr, schema: &RowSchema) -> Option<usize> {
80        match expression {
81            ScalarExpr::Column(name) => {
82                let position = Self::position_at(schema, schema.column_slot(name)?)?;
83                // A relation of that name makes the name a whole-row reference, which the parser tries before the parameters.
84                (!self.names_relation(schema, name)).then_some(position)
85            }
86            ScalarExpr::QualifiedColumn { qualifier, column } => {
87                match schema.qualified_slot(qualifier, column) {
88                    Some(slot) => Self::position_at(schema, slot),
89                    // A relation that takes the routine's name but lacks the column leaves the name to the parameter, since the parser finds no column for it.
90                    None if *qualifier == self.data.function && Self::reaches(schema) => self
91                        .data
92                        .names
93                        .iter()
94                        .position(|name| !name.is_empty() && name == column),
95                    None => None,
96                }
97            }
98            _ => None,
99        }
100    }
101
102    /// Whether `name` is a relation visible in `schema`. The layer's own qualifier, the routine's name, is visible only where no relation takes that name.
103    fn names_relation(&self, schema: &RowSchema, name: &str) -> bool {
104        schema.has_qualifier(name)
105            && (name != self.data.function
106                || !self.data.names.iter().any(|parameter| {
107                    schema
108                        .qualified_slot(name, parameter)
109                        .and_then(|slot| Self::position_at(schema, slot))
110                        .is_some()
111                }))
112    }
113}
114
115/// The output name each select list item takes from the column it names, which the item keeps when the name turns out to be a parameter: `PostgreSQL` names the output column of a parameter reference after the reference as written.
116pub(super) fn column_labels(projections: &[ProjectionPlan]) -> Vec<Option<String>> {
117    projections
118        .iter()
119        .map(|projection| match &projection.expr {
120            ScalarExpr::Column(name) | ScalarExpr::QualifiedColumn { column: name, .. }
121                if projection.alias.is_none() =>
122            {
123                Some(name.to_string())
124            }
125            _ => None,
126        })
127        .collect()
128}
129
130/// Name each select list item that `labels` took from a column name and that now refers to a parameter after that column name.
131pub(super) fn keep_column_labels(projections: &mut [ProjectionPlan], labels: Vec<Option<String>>) {
132    for (projection, label) in projections.iter_mut().zip(labels) {
133        if let Some(label) = label {
134            if matches!(projection.expr, ScalarExpr::Param(_)) {
135                projection.alias = Some(label);
136            }
137        }
138    }
139}
140
141impl SchemaScope {
142    /// Resolve a name at the point ordered semantic analysis visits it.
143    pub(super) fn routine_parameter_reference(
144        &self,
145        expression: &ScalarExpr,
146        schema: &RowSchema,
147    ) -> Option<usize> {
148        self.routine_parameters
149            .as_ref()
150            .and_then(|parameters| parameters.parameter(expression, schema))
151            .map(|position| position + 1)
152    }
153
154    /// Replace each reference in `expression` that resolves to a parameter of the routine whose body is bound with the positional parameter it names. `schema` is the row scope `expression` resolves against.
155    pub(super) fn canonicalize_routine_parameters(
156        &self,
157        expression: &mut ScalarExpr,
158        schema: &RowSchema,
159    ) {
160        let Some(parameters) = self.routine_parameters.as_ref() else {
161            return;
162        };
163        crate::plan::rewrite_scalar_expression(expression, &mut |node| {
164            if let Some(position) = parameters.parameter(node, schema) {
165                *node = ScalarExpr::Param(position + 1);
166            }
167        });
168    }
169
170    /// Walk one statement with `outer`, the parameters of the routine whose body it belongs to, as its outermost scope.
171    pub(super) fn bind_statement_parameters(
172        &mut self,
173        routines: &dyn RoutineResolution,
174        plan: &mut UnifiedPlan,
175        params: &[SQLParam],
176        outer: Option<&RowSchema>,
177    ) -> Result<(), SQLError> {
178        let command = match plan {
179            UnifiedPlan::Query(query) => {
180                return self.bind_query_parameters(routines, query, params, outer);
181            }
182            UnifiedPlan::Command(command) => command.as_mut(),
183        };
184        match command {
185            CommandPlan::Explain { body, .. } => {
186                self.bind_statement_parameters(routines, body, params, outer)
187            }
188            CommandPlan::CreateTableAs { query, .. }
189            | CommandPlan::CreateMaterializedView { query, .. }
190            | CommandPlan::DeclareCursor { query, .. } => {
191                self.bind_query_parameters(routines, query, params, outer)
192            }
193            CommandPlan::Call { args, .. } => {
194                for argument in args {
195                    self.bind_expression_parameters(routines, argument, params, outer)?;
196                }
197                Ok(())
198            }
199            command if command.mutation_target().is_some() => {
200                self.set_command_lookup_mode(command);
201                self.bind_command_routines_for_storage(routines, command, params, outer)
202            }
203            // A utility statement is not analyzed with the routine's parameters: `PostgreSQL` runs it as written.
204            _ => Ok(()),
205        }
206    }
207
208    /// Resolve the parameter references of a query, looking its relations up as bound identities or by name as its `relations_bound` flag records.
209    fn bind_query_parameters(
210        &mut self,
211        routines: &dyn RoutineResolution,
212        query: &mut QueryPlan,
213        params: &[SQLParam],
214        outer: Option<&RowSchema>,
215    ) -> Result<(), SQLError> {
216        let previous = self.resolution.set_lookup_mode(if query.relations_bound {
217            RelationLookupMode::Bound
218        } else {
219            RelationLookupMode::Dynamic
220        });
221        let result = self
222            .bind_query_routines_for_storage(routines, query, params, outer)
223            .map(|_| ());
224        self.resolution.set_lookup_mode(previous);
225        result
226    }
227
228    fn bind_expression_parameters(
229        &mut self,
230        routines: &dyn RoutineResolution,
231        expression: &mut ExpressionPlan,
232        params: &[SQLParam],
233        outer: Option<&RowSchema>,
234    ) -> Result<(), SQLError> {
235        for subquery in &mut expression.subqueries {
236            self.bind_query_parameters(routines, subquery, params, outer)?;
237        }
238        let schema = outer.cloned().unwrap_or_default();
239        self.canonicalize_routine_parameters(&mut expression.scalar, &schema);
240        self.resolve_variable_sites(&mut expression.scalar, &schema);
241        Ok(())
242    }
243}
244
245/// Resolve the names in one statement of a SQL routine's body that refer to the routine's parameters, against the catalog that `ctes` describes, as `PostgreSQL`'s parser resolves them with the hooks `sql_fn_parser_setup` installs. The routine calls the statement makes are left to its analysis.
246pub fn bind_routine_parameter_references(
247    routines: &dyn RoutineResolution,
248    plan: &mut UnifiedPlan,
249    params: &[SQLParam],
250    ctes: &BindingContext,
251    parameters: &RoutineParameterScope,
252) -> Result<(), SQLError> {
253    let mut scope = SchemaScope::for_analysis(ctes)?;
254    scope.routine_parameters = Some(parameters.clone());
255    scope.scalar_binding = super::ScalarBindingMode::References;
256    // Parameter lookup must retain the written expression sites for stored-body binding.
257    scope.preserve_syntax_shape = true;
258    scope.bind_statement_parameters(routines, plan, params, Some(parameters.schema()))
259}