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, projection::rename_schema, BindingContext,
16    ScalarExpr, SchemaScope, SourceScope,
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
71/// Inputs already visited by an ordered source traversal. Join binding consumes the child descriptors without analyzing their sources again.
72#[doc(hidden)]
73pub enum SourceBindingInput<'a> {
74    Leaf(&'a SourcePlan),
75    Join {
76        source: &'a SourcePlan,
77        left: &'a RowSchema,
78        right: &'a RowSchema,
79    },
80}
81
82impl<'a> SourceBindingInput<'a> {
83    pub fn source(&self) -> &'a SourcePlan {
84        match self {
85            Self::Leaf(source) | Self::Join { source, .. } => source,
86        }
87    }
88}
89
90pub(super) fn table_function_member_source(function: &TableFunctionPlan) -> SourcePlan {
91    SourcePlan::Function {
92        name: function.name.clone(),
93        binding: function.binding.clone(),
94        output_name: function.output_name.clone(),
95        relations: function.relations.clone(),
96        args: function.args.clone(),
97        alias: None,
98        column_aliases: function.column_aliases.clone(),
99        ordinality: false,
100        column_types: function.column_types.clone(),
101    }
102}
103
104/// Derive the exact row type of one FROM source without executing it.
105pub fn bind_source_plan_schema(
106    routines: &dyn RoutineResolution,
107    source: &SourcePlan,
108    params: &[SQLParam],
109    ctes: &BindingContext,
110    outer: Option<&RowSchema>,
111) -> Result<RowSchema, SQLError> {
112    SchemaScope::from_context(ctes)?.bind_source(
113        routines,
114        source,
115        ctes.scalar_subqueries,
116        params,
117        outer,
118    )
119}
120
121/// Bind a FROM item while retaining the distinction between lexical ancestors and preceding peers for consumers which traverse a source tree.
122pub fn bind_source_plan_schema_in_scope(
123    routines: &dyn RoutineResolution,
124    source: &SourcePlan,
125    params: &[SQLParam],
126    ctes: &BindingContext,
127    scope: SourceScope<'_>,
128) -> Result<RowSchema, SQLError> {
129    SchemaScope::from_context(ctes)?.bind_source_in_scope(
130        routines,
131        source,
132        ctes.scalar_subqueries,
133        params,
134        scope,
135    )
136}
137
138/// Bind one visited source using its already analyzed child descriptors.
139pub fn bind_source_input_schema(
140    routines: &dyn RoutineResolution,
141    input: SourceBindingInput<'_>,
142    params: &[SQLParam],
143    ctes: &BindingContext,
144    scope: SourceScope<'_>,
145) -> Result<RowSchema, SQLError> {
146    SchemaScope::from_context(ctes)?.bind_source_input(
147        routines,
148        input,
149        ctes.scalar_subqueries,
150        params,
151        scope,
152    )
153}
154
155/// 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.
156pub fn with_query_table_pseudo_columns(schema: &RowSchema) -> RowSchema {
157    analysis::with_unqualified_table_pseudo_columns(schema)
158}
159
160/// Derive and validate one FROM source's exact row type without executing it.
161pub fn analyze_source_plan_schema(
162    routines: &dyn RoutineResolution,
163    source: &SourcePlan,
164    params: &[SQLParam],
165    ctes: &BindingContext,
166    outer: Option<&RowSchema>,
167) -> Result<RowSchema, SQLError> {
168    SchemaScope::for_analysis(ctes)?.bind_source(
169        routines,
170        source,
171        ctes.scalar_subqueries,
172        params,
173        outer,
174    )
175}
176
177/// 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.
178pub fn bind_source_plan_schema_for_execution(
179    routines: &dyn RoutineResolution,
180    source: &mut SourcePlan,
181    params: &[SQLParam],
182    ctes: &BindingContext,
183    outer: Option<&RowSchema>,
184) -> Result<RowSchema, SQLError> {
185    SchemaScope::from_context(ctes)?.bind_source_for_execution(
186        routines,
187        source,
188        ctes.scalar_subqueries,
189        params,
190        outer,
191    )
192}
193
194impl SchemaScope {
195    pub(super) fn bind_source_input(
196        &mut self,
197        routines: &dyn RoutineResolution,
198        input: SourceBindingInput<'_>,
199        subqueries: &[QueryPlan],
200        params: &[SQLParam],
201        scope: SourceScope<'_>,
202    ) -> Result<RowSchema, SQLError> {
203        let SourceBindingInput::Join {
204            source,
205            left,
206            right,
207        } = input
208        else {
209            return self.bind_source_in_scope(routines, input.source(), subqueries, params, scope);
210        };
211        let SourcePlan::Join {
212            kind,
213            on,
214            using,
215            natural,
216            alias,
217            column_aliases,
218            ..
219        } = source
220        else {
221            unreachable!("join inputs belong to a join source")
222        };
223        let condition = scope.condition();
224        let schema = self.bind_join_output_schema(JoinSchemaBinding {
225            routines,
226            kind: *kind,
227            on: on.as_ref(),
228            using: using.as_ref(),
229            natural: *natural,
230            alias: alias.as_deref(),
231            column_aliases,
232            left,
233            right,
234            subqueries,
235            params,
236            outer: condition.as_ref(),
237        })?;
238        Ok(if scope.retain_names {
239            SourceScope::describe_output(source, schema)
240        } else {
241            schema
242        })
243    }
244
245    pub(super) fn bind_source(
246        &mut self,
247        routines: &dyn RoutineResolution,
248        source: &SourcePlan,
249        subqueries: &[QueryPlan],
250        params: &[SQLParam],
251        outer: Option<&RowSchema>,
252    ) -> Result<RowSchema, SQLError> {
253        self.bind_source_in_scope(
254            routines,
255            source,
256            subqueries,
257            params,
258            SourceScope::new(outer),
259        )
260    }
261
262    pub(super) fn bind_source_in_scope(
263        &mut self,
264        routines: &dyn RoutineResolution,
265        source: &SourcePlan,
266        subqueries: &[QueryPlan],
267        params: &[SQLParam],
268        scope: SourceScope<'_>,
269    ) -> Result<RowSchema, SQLError> {
270        let bound = matches!(
271            source,
272            SourcePlan::Table {
273                bound_columns: Some(_),
274                ..
275            }
276        );
277        let previous = bound.then(|| {
278            self.resolution
279                .set_lookup_mode(crate::catalog::resolution::RelationLookupMode::Bound)
280        });
281        let result = self.bind_source_inner(routines, source, subqueries, params, scope);
282        if let Some(previous) = previous {
283            self.resolution.set_lookup_mode(previous);
284        }
285        result.map(|schema| {
286            if scope.retain_names {
287                SourceScope::describe_output(source, schema)
288            } else {
289                schema
290            }
291        })
292    }
293}
294
295impl SchemaScope {
296    pub(super) fn bind_source_for_execution(
297        &mut self,
298        routines: &dyn RoutineResolution,
299        source: &mut SourcePlan,
300        subqueries: &[QueryPlan],
301        params: &[SQLParam],
302        outer: Option<&RowSchema>,
303    ) -> Result<RowSchema, SQLError> {
304        self.bind_source_for_execution_in_scope(
305            routines,
306            source,
307            subqueries,
308            params,
309            SourceScope::new(outer),
310        )
311    }
312
313    fn bind_source_for_execution_in_scope(
314        &mut self,
315        routines: &dyn RoutineResolution,
316        source: &mut SourcePlan,
317        subqueries: &[QueryPlan],
318        params: &[SQLParam],
319        scope: SourceScope<'_>,
320    ) -> Result<RowSchema, SQLError> {
321        let schema = self.bind_source_for_execution_in_scope_inner(
322            routines, source, subqueries, params, scope,
323        )?;
324        Ok(if scope.retain_names {
325            SourceScope::describe_output(source, schema)
326        } else {
327            schema
328        })
329    }
330
331    fn bind_source_for_execution_in_scope_inner(
332        &mut self,
333        routines: &dyn RoutineResolution,
334        source: &mut SourcePlan,
335        subqueries: &[QueryPlan],
336        params: &[SQLParam],
337        scope: SourceScope<'_>,
338    ) -> Result<RowSchema, SQLError> {
339        let input = (!matches!(source, SourcePlan::Join { .. }))
340            .then(|| scope.input(source))
341            .flatten();
342        let outer = input.as_ref();
343        match source {
344            crate::plan::SourcePlan::RetainedRows(_) => {}
345            SourcePlan::Join {
346                left,
347                right,
348                kind,
349                on,
350                using,
351                natural,
352                alias,
353                column_aliases,
354                lateral,
355                ..
356            } => {
357                let left_schema = self.bind_source_for_execution_in_scope(
358                    routines,
359                    left,
360                    subqueries,
361                    params,
362                    scope.with_names(),
363                )?;
364                let preceding = scope.right_namespace(left, &left_schema, *kind);
365                let right_schema = self.bind_source_for_execution_in_scope(
366                    routines,
367                    right,
368                    subqueries,
369                    params,
370                    SourceScope {
371                        outer: scope.outer,
372                        preceding: Some(&preceding),
373                        inherited_lateral: *lateral,
374                        retain_names: true,
375                    },
376                )?;
377                let condition = scope.condition();
378                return self.bind_join_output_schema(JoinSchemaBinding {
379                    routines,
380                    kind: *kind,
381                    on: on.as_ref(),
382                    using: using.as_ref(),
383                    natural: *natural,
384                    alias: alias.as_deref(),
385                    column_aliases,
386                    left: &left_schema,
387                    right: &right_schema,
388                    subqueries,
389                    params,
390                    outer: condition.as_ref(),
391                });
392            }
393            SourcePlan::Function {
394                name, relations, ..
395            } => {
396                let lower = crate::semantics::builtin_function_dispatch_name(name);
397                if crate::registry::is_operator_join_table_function(&lower) {
398                    operator_join_relation_schemas(
399                        &self.catalog,
400                        &self.resolution,
401                        relations.as_ref(),
402                    )?;
403                    return self.bind_source(routines, source, subqueries, params, outer);
404                }
405                self.bind_table_function_for_execution(
406                    routines, source, subqueries, params, outer,
407                )?;
408            }
409            SourcePlan::FunctionGroup { functions, .. } => {
410                for function in functions {
411                    let mut member = table_function_member_source(function);
412                    self.bind_source_for_execution(
413                        routines,
414                        &mut member,
415                        subqueries,
416                        params,
417                        outer,
418                    )?;
419                    let SourcePlan::Function { binding, .. } = member else {
420                        unreachable!("table-function member changed source kind during binding")
421                    };
422                    function.binding = binding;
423                }
424            }
425            SourcePlan::Table { .. } | SourcePlan::Values { .. } | SourcePlan::Subquery { .. } => {}
426        }
427        self.bind_source(routines, source, subqueries, params, outer)
428    }
429
430    /// 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.
431    fn bind_table_function_for_execution(
432        &mut self,
433        routines: &dyn RoutineResolution,
434        source: &mut SourcePlan,
435        subqueries: &[QueryPlan],
436        params: &[SQLParam],
437        outer: Option<&RowSchema>,
438    ) -> Result<(), SQLError> {
439        let SourcePlan::Function {
440            name,
441            binding,
442            args,
443            ..
444        } = source
445        else {
446            unreachable!("table-function source");
447        };
448        let input = outer.cloned().unwrap_or_default();
449        let resolver = self.query_function_type_resolver_for_subqueries(
450            routines, args, &input, subqueries, params,
451        )?;
452        let Some(mut selected) = crate::semantics::resolve_table_function_binding(
453            routines,
454            name,
455            binding.as_ref(),
456            args,
457            &input,
458            params,
459            &resolver,
460        )?
461        else {
462            return Ok(());
463        };
464        if binding.is_none()
465            && selected.builtin
466            && crate::expr::binds_input_collation_by_name(
467                &crate::semantics::builtin_function_dispatch_name(name),
468            )
469        {
470            selected.input_collation = super::preparation::call_input_collation(
471                self, routines, name, args, &input, subqueries, params,
472            )?;
473        }
474        *binding = Some(selected);
475        Ok(())
476    }
477}