Skip to main content

uqa_sql/binding/
sources.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Source row-type adapters and join binding inputs.
8
9use crate::ast::{JoinKind, JoinUsing};
10use crate::plan::{QueryPlan, SourcePlan, TableFunctionPlan};
11use crate::RowSchema;
12use crate::{SQLError, SQLParam};
13
14use super::{
15    analysis, operator_join_relation_schemas, overlay_outer_schema, projection::rename_schema,
16    BindingContext, ScalarExpr, SchemaScope,
17};
18use crate::routines::RoutineResolution;
19
20pub(super) fn alias_table_schema(
21    schema: &RowSchema,
22    qualifier: &str,
23    column_aliases: &[String],
24) -> Result<RowSchema, SQLError> {
25    if column_aliases.len() > schema.len() {
26        return Err(SQLError::Routine {
27            sqlstate: "42P10".into(),
28            message: format!(
29                "table \"{qualifier}\" has {} columns available but {} columns specified",
30                schema.len(),
31                column_aliases.len()
32            ),
33        });
34    }
35    Ok(rename_schema(schema, column_aliases, Some(qualifier)))
36}
37
38impl SchemaScope {
39    pub(super) fn alias_relation_schema(
40        &self,
41        schema: &RowSchema,
42        name: &str,
43        qualifier: &str,
44        column_aliases: &[String],
45    ) -> Result<RowSchema, SQLError> {
46        let schema = alias_table_schema(schema, qualifier, column_aliases)?;
47        match self.catalog.relation_row_type(&self.resolution, name)? {
48            Some(row_type) => {
49                schema.with_relation_row_type(qualifier, crate::ColumnType::Composite(row_type))
50            }
51            None => Ok(schema),
52        }
53    }
54}
55
56pub(super) struct JoinSchemaBinding<'a> {
57    pub(super) routines: &'a dyn RoutineResolution,
58    pub(super) kind: JoinKind,
59    pub(super) on: Option<&'a ScalarExpr>,
60    pub(super) using: Option<&'a JoinUsing>,
61    pub(super) natural: bool,
62    pub(super) alias: Option<&'a str>,
63    pub(super) column_aliases: &'a [String],
64    pub(super) left: &'a RowSchema,
65    pub(super) right: &'a RowSchema,
66    pub(super) subqueries: &'a [QueryPlan],
67    pub(super) params: &'a [SQLParam],
68    pub(super) outer: Option<&'a RowSchema>,
69}
70
71pub(super) fn table_function_member_source(function: &TableFunctionPlan) -> SourcePlan {
72    SourcePlan::Function {
73        name: function.name.clone(),
74        binding: function.binding.clone(),
75        output_name: function.output_name.clone(),
76        relations: function.relations.clone(),
77        args: function.args.clone(),
78        alias: None,
79        column_aliases: function.column_aliases.clone(),
80        ordinality: false,
81        column_types: function.column_types.clone(),
82    }
83}
84
85/// Derive the exact row type of one FROM source without executing it.
86pub fn bind_source_plan_schema(
87    routines: &dyn RoutineResolution,
88    source: &SourcePlan,
89    params: &[SQLParam],
90    ctes: &BindingContext,
91    outer: Option<&RowSchema>,
92) -> Result<RowSchema, SQLError> {
93    SchemaScope::from_context(ctes)?.bind_source(
94        routines,
95        source,
96        ctes.scalar_subqueries,
97        params,
98        outer,
99    )
100}
101
102/// Add query-block pseudo columns after the complete source scope is known, so `_meta` is exposed only for one unambiguous local-table source and never shadows a real relation alias.
103pub fn with_query_table_pseudo_columns(schema: &RowSchema) -> RowSchema {
104    analysis::with_unqualified_table_pseudo_columns(schema)
105}
106
107/// Derive and validate one FROM source's exact row type without executing it.
108pub fn analyze_source_plan_schema(
109    routines: &dyn RoutineResolution,
110    source: &SourcePlan,
111    params: &[SQLParam],
112    ctes: &BindingContext,
113    outer: Option<&RowSchema>,
114) -> Result<RowSchema, SQLError> {
115    SchemaScope::for_analysis(ctes)?.bind_source(
116        routines,
117        source,
118        ctes.scalar_subqueries,
119        params,
120        outer,
121    )
122}
123
124/// Bind every table-function source in one execution-owned source plan to its exact routine identity and return the schema derived from those same bindings.
125pub fn bind_source_plan_schema_for_execution(
126    routines: &dyn RoutineResolution,
127    source: &mut SourcePlan,
128    params: &[SQLParam],
129    ctes: &BindingContext,
130    outer: Option<&RowSchema>,
131) -> Result<RowSchema, SQLError> {
132    SchemaScope::from_context(ctes)?.bind_source_for_execution(
133        routines,
134        source,
135        ctes.scalar_subqueries,
136        params,
137        outer,
138    )
139}
140
141impl SchemaScope {
142    pub(super) fn bind_source(
143        &mut self,
144        routines: &dyn RoutineResolution,
145        source: &SourcePlan,
146        subqueries: &[QueryPlan],
147        params: &[SQLParam],
148        outer: Option<&RowSchema>,
149    ) -> Result<RowSchema, SQLError> {
150        let bound = matches!(
151            source,
152            SourcePlan::Table {
153                bound_columns: Some(_),
154                ..
155            }
156        );
157        let previous = bound.then(|| {
158            self.resolution
159                .set_lookup_mode(crate::catalog::resolution::RelationLookupMode::Bound)
160        });
161        let result = self.bind_source_inner(routines, source, subqueries, params, outer);
162        if let Some(previous) = previous {
163            self.resolution.set_lookup_mode(previous);
164        }
165        result
166    }
167}
168
169impl SchemaScope {
170    pub(super) fn bind_source_for_execution(
171        &mut self,
172        routines: &dyn RoutineResolution,
173        source: &mut SourcePlan,
174        subqueries: &[QueryPlan],
175        params: &[SQLParam],
176        outer: Option<&RowSchema>,
177    ) -> Result<RowSchema, SQLError> {
178        match source {
179            crate::plan::SourcePlan::RetainedRows(_) => {}
180            SourcePlan::Join {
181                left,
182                right,
183                kind,
184                on,
185                using,
186                natural,
187                alias,
188                column_aliases,
189                lateral,
190                ..
191            } => {
192                let left_schema =
193                    self.bind_source_for_execution(routines, left, subqueries, params, outer)?;
194                let implicit_lateral_function = matches!(
195                    right.as_ref(),
196                    SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. }
197                );
198                let right_scope = (*lateral || implicit_lateral_function)
199                    .then(|| overlay_outer_schema(&left_schema, outer));
200                let right_schema = self.bind_source_for_execution(
201                    routines,
202                    right,
203                    subqueries,
204                    params,
205                    right_scope.as_ref().or(outer),
206                )?;
207                return self.bind_join_output_schema(JoinSchemaBinding {
208                    routines,
209                    kind: *kind,
210                    on: on.as_ref(),
211                    using: using.as_ref(),
212                    natural: *natural,
213                    alias: alias.as_deref(),
214                    column_aliases,
215                    left: &left_schema,
216                    right: &right_schema,
217                    subqueries,
218                    params,
219                    outer,
220                });
221            }
222            SourcePlan::Function {
223                name, relations, ..
224            } => {
225                let lower = crate::semantics::builtin_function_dispatch_name(name);
226                if crate::registry::is_operator_join_table_function(&lower) {
227                    operator_join_relation_schemas(
228                        &self.catalog,
229                        &self.resolution,
230                        relations.as_ref(),
231                    )?;
232                    return self.bind_source(routines, source, subqueries, params, outer);
233                }
234                self.bind_table_function_for_execution(
235                    routines, source, subqueries, params, outer,
236                )?;
237            }
238            SourcePlan::FunctionGroup { functions, .. } => {
239                for function in functions {
240                    let mut member = table_function_member_source(function);
241                    self.bind_source_for_execution(
242                        routines,
243                        &mut member,
244                        subqueries,
245                        params,
246                        outer,
247                    )?;
248                    let SourcePlan::Function { binding, .. } = member else {
249                        unreachable!("table-function member changed source kind during binding")
250                    };
251                    function.binding = binding;
252                }
253            }
254            SourcePlan::Table { .. } | SourcePlan::Values { .. } | SourcePlan::Subquery { .. } => {}
255        }
256        self.bind_source(routines, source, subqueries, params, outer)
257    }
258
259    /// Select a table function's binding against the row it reads. A built-in that reads its input collation also records the collation of its arguments, as analysis records every other call's.
260    fn bind_table_function_for_execution(
261        &mut self,
262        routines: &dyn RoutineResolution,
263        source: &mut SourcePlan,
264        subqueries: &[QueryPlan],
265        params: &[SQLParam],
266        outer: Option<&RowSchema>,
267    ) -> Result<(), SQLError> {
268        let SourcePlan::Function {
269            name,
270            binding,
271            args,
272            ..
273        } = source
274        else {
275            unreachable!("table-function source");
276        };
277        let input = outer.cloned().unwrap_or_default();
278        let resolver = self.query_function_type_resolver_for_subqueries(
279            routines, args, &input, subqueries, params,
280        )?;
281        let Some(mut selected) = crate::semantics::resolve_table_function_binding(
282            routines,
283            name,
284            binding.as_ref(),
285            args,
286            &input,
287            params,
288            &resolver,
289        )?
290        else {
291            return Ok(());
292        };
293        if binding.is_none()
294            && selected.builtin
295            && crate::expr::binds_input_collation_by_name(
296                &crate::semantics::builtin_function_dispatch_name(name),
297            )
298        {
299            selected.input_collation = super::preparation::call_input_collation(
300                self, routines, name, args, &input, subqueries, params,
301            )?;
302        }
303        *binding = Some(selected);
304        Ok(())
305    }
306}