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    operator_join_relation_schemas, projection::rename_schema_with_control, BindingContext,
16    ScalarExpr, SchemaScope, SourceScope,
17};
18use crate::routines::RoutineResolution;
19
20mod execution;
21mod functions;
22mod relations;
23pub use execution::bind_source_plan_for_execution_owned;
24
25pub(super) fn alias_table_schema(
26    schema: &RowSchema,
27    qualifier: &str,
28    column_aliases: &[String],
29    control: &uqa_core::memory::ProductionControl<'_>,
30) -> Result<RowSchema, SQLError> {
31    if column_aliases.len() > schema.len() {
32        return Err(SQLError::Routine {
33            sqlstate: "42P10".into(),
34            message: control
35                .format(format_args!(
36                    "table \"{qualifier}\" has {} columns available but {} columns specified",
37                    schema.len(),
38                    column_aliases.len()
39                ))?
40                .into_parts()
41                .0,
42        });
43    }
44    rename_schema_with_control(schema, column_aliases, Some(qualifier), control)
45}
46
47impl SchemaScope {
48    pub(super) fn alias_relation_schema(
49        &self,
50        schema: &RowSchema,
51        name: &str,
52        qualifier: &str,
53        column_aliases: &[String],
54    ) -> Result<RowSchema, SQLError> {
55        let control = self.control();
56        let schema = alias_table_schema(schema, qualifier, column_aliases, &control)?;
57        match self
58            .catalog
59            .relation_row_type_with_control(&self.resolution, name, &control)?
60        {
61            Some(row_type) => {
62                let (row_type, memory) = row_type.into_parts();
63                let ty = control.finish(crate::ColumnType::Composite(row_type), memory)?;
64                schema.with_relation_row_type_with_control(qualifier, &ty, &control)
65            }
66            None => Ok(schema),
67        }
68    }
69}
70
71pub(super) struct JoinSchemaBinding<'a> {
72    pub(super) routines: &'a dyn RoutineResolution,
73    pub(super) kind: JoinKind,
74    pub(super) on: Option<&'a ScalarExpr>,
75    pub(super) using: Option<&'a JoinUsing>,
76    pub(super) natural: bool,
77    pub(super) alias: Option<&'a str>,
78    pub(super) column_aliases: &'a [String],
79    pub(super) left: &'a RowSchema,
80    pub(super) right: &'a RowSchema,
81    pub(super) subqueries: &'a [QueryPlan],
82    pub(super) params: &'a [SQLParam],
83    pub(super) outer: Option<&'a RowSchema>,
84}
85
86/// Inputs already visited by an ordered source traversal. Join binding consumes the child descriptors without analyzing their sources again.
87#[doc(hidden)]
88pub enum SourceBindingInput<'a> {
89    Leaf(&'a SourcePlan),
90    Join {
91        source: &'a SourcePlan,
92        left: &'a RowSchema,
93        right: &'a RowSchema,
94    },
95}
96
97impl<'a> SourceBindingInput<'a> {
98    pub fn source(&self) -> &'a SourcePlan {
99        match self {
100            Self::Leaf(source) | Self::Join { source, .. } => source,
101        }
102    }
103}
104
105pub(super) fn table_function_member_source(function: &TableFunctionPlan) -> SourcePlan {
106    SourcePlan::Function {
107        name: function.name.clone(),
108        binding: function.binding.clone(),
109        output_name: function.output_name.clone(),
110        relations: function.relations.clone(),
111        args: function.args.clone(),
112        alias: None,
113        column_aliases: function.column_aliases.clone(),
114        ordinality: false,
115        column_types: function.column_types.clone(),
116    }
117}
118
119/// Derive the exact row type of one FROM source without executing it.
120pub fn bind_source_plan_schema(
121    routines: &dyn RoutineResolution,
122    source: &SourcePlan,
123    params: &[SQLParam],
124    ctes: &BindingContext,
125    outer: Option<&RowSchema>,
126) -> Result<RowSchema, SQLError> {
127    SchemaScope::from_context(ctes)?.bind_source(
128        routines,
129        source,
130        ctes.scalar_subqueries,
131        params,
132        outer,
133    )
134}
135
136/// Bind a FROM item while retaining the distinction between lexical ancestors and preceding peers for consumers which traverse a source tree.
137pub fn bind_source_plan_schema_in_scope(
138    routines: &dyn RoutineResolution,
139    source: &SourcePlan,
140    params: &[SQLParam],
141    ctes: &BindingContext,
142    scope: SourceScope<'_>,
143) -> Result<RowSchema, SQLError> {
144    SchemaScope::from_context(ctes)?.bind_source_in_scope(
145        routines,
146        source,
147        ctes.scalar_subqueries,
148        params,
149        scope,
150    )
151}
152
153/// Bind one visited source using its already analyzed child descriptors.
154pub fn bind_source_input_schema(
155    routines: &dyn RoutineResolution,
156    input: SourceBindingInput<'_>,
157    params: &[SQLParam],
158    ctes: &BindingContext,
159    scope: SourceScope<'_>,
160) -> Result<RowSchema, SQLError> {
161    SchemaScope::from_context(ctes)?.bind_source_input(
162        routines,
163        input,
164        ctes.scalar_subqueries,
165        params,
166        scope,
167    )
168}
169
170mod pseudo_columns;
171pub use pseudo_columns::with_query_table_pseudo_columns_with_control;
172
173/// 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.
174pub fn with_query_table_pseudo_columns(schema: &RowSchema) -> RowSchema {
175    with_query_table_pseudo_columns_with_control(
176        schema,
177        &uqa_core::memory::ProductionControl::uncontrolled(),
178    )
179    .expect("ordinary pseudo-column schema")
180}
181
182/// Derive and validate one FROM source's exact row type without executing it.
183pub fn analyze_source_plan_schema(
184    routines: &dyn RoutineResolution,
185    source: &SourcePlan,
186    params: &[SQLParam],
187    ctes: &BindingContext,
188    outer: Option<&RowSchema>,
189) -> Result<RowSchema, SQLError> {
190    SchemaScope::for_analysis(ctes)?.bind_source(
191        routines,
192        source,
193        ctes.scalar_subqueries,
194        params,
195        outer,
196    )
197}
198
199/// 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.
200pub fn bind_source_plan_schema_for_execution(
201    routines: &dyn RoutineResolution,
202    source: &mut SourcePlan,
203    params: &[SQLParam],
204    ctes: &BindingContext,
205    outer: Option<&RowSchema>,
206) -> Result<RowSchema, SQLError> {
207    SchemaScope::from_context(ctes)?.bind_source_for_execution(
208        routines,
209        source,
210        ctes.scalar_subqueries,
211        params,
212        outer,
213    )
214}
215
216impl SchemaScope {
217    pub(super) fn bind_source_input(
218        &mut self,
219        routines: &dyn RoutineResolution,
220        input: SourceBindingInput<'_>,
221        subqueries: &[QueryPlan],
222        params: &[SQLParam],
223        scope: SourceScope<'_>,
224    ) -> Result<RowSchema, SQLError> {
225        let SourceBindingInput::Join {
226            source,
227            left,
228            right,
229        } = input
230        else {
231            return self.bind_source_in_scope(routines, input.source(), subqueries, params, scope);
232        };
233        let SourcePlan::Join {
234            kind,
235            on,
236            using,
237            natural,
238            alias,
239            column_aliases,
240            ..
241        } = source
242        else {
243            unreachable!("join inputs belong to a join source")
244        };
245        let condition = scope.condition_with_control(&self.control())?;
246        let schema = self.bind_join_output_schema(JoinSchemaBinding {
247            routines,
248            kind: *kind,
249            on: on.as_ref(),
250            using: using.as_ref(),
251            natural: *natural,
252            alias: alias.as_deref(),
253            column_aliases,
254            left,
255            right,
256            subqueries,
257            params,
258            outer: condition.as_ref(),
259        })?;
260        Ok(if scope.retain_names {
261            SourceScope::describe_output_with_control(source, schema, &self.control())?
262        } else {
263            schema
264        })
265    }
266
267    pub(super) fn bind_source(
268        &mut self,
269        routines: &dyn RoutineResolution,
270        source: &SourcePlan,
271        subqueries: &[QueryPlan],
272        params: &[SQLParam],
273        outer: Option<&RowSchema>,
274    ) -> Result<RowSchema, SQLError> {
275        self.bind_source_in_scope(
276            routines,
277            source,
278            subqueries,
279            params,
280            SourceScope::new(outer),
281        )
282    }
283
284    pub(super) fn bind_source_in_scope(
285        &mut self,
286        routines: &dyn RoutineResolution,
287        source: &SourcePlan,
288        subqueries: &[QueryPlan],
289        params: &[SQLParam],
290        scope: SourceScope<'_>,
291    ) -> Result<RowSchema, SQLError> {
292        let bound = matches!(
293            source,
294            SourcePlan::Table {
295                bound_columns: Some(_),
296                ..
297            }
298        );
299        let previous = bound.then(|| {
300            self.resolution
301                .set_lookup_mode(crate::catalog::resolution::RelationLookupMode::Bound)
302        });
303        let result = self.bind_source_inner(routines, source, subqueries, params, scope);
304        if let Some(previous) = previous {
305            self.resolution.set_lookup_mode(previous);
306        }
307        result.and_then(|schema| {
308            if scope.retain_names {
309                SourceScope::describe_output_with_control(source, schema, &self.control())
310            } else {
311                Ok(schema)
312            }
313        })
314    }
315}
316
317impl SchemaScope {
318    pub(super) fn bind_source_for_execution(
319        &mut self,
320        routines: &dyn RoutineResolution,
321        source: &mut SourcePlan,
322        subqueries: &[QueryPlan],
323        params: &[SQLParam],
324        outer: Option<&RowSchema>,
325    ) -> Result<RowSchema, SQLError> {
326        self.bind_source_for_execution_in_scope(
327            routines,
328            source,
329            subqueries,
330            params,
331            SourceScope::new(outer),
332        )
333    }
334
335    fn bind_source_for_execution_in_scope(
336        &mut self,
337        routines: &dyn RoutineResolution,
338        source: &mut SourcePlan,
339        subqueries: &[QueryPlan],
340        params: &[SQLParam],
341        scope: SourceScope<'_>,
342    ) -> Result<RowSchema, SQLError> {
343        let schema = self.bind_source_for_execution_in_scope_inner(
344            routines, source, subqueries, params, scope,
345        )?;
346        Ok(if scope.retain_names {
347            SourceScope::describe_output_with_control(source, schema, &self.control())?
348        } else {
349            schema
350        })
351    }
352
353    fn bind_source_for_execution_in_scope_inner(
354        &mut self,
355        routines: &dyn RoutineResolution,
356        source: &mut SourcePlan,
357        subqueries: &[QueryPlan],
358        params: &[SQLParam],
359        scope: SourceScope<'_>,
360    ) -> Result<RowSchema, SQLError> {
361        let input = (!matches!(source, SourcePlan::Join { .. }))
362            .then(|| scope.input_with_control(source, &self.control()))
363            .transpose()?
364            .flatten();
365        let outer = input.as_ref();
366        match source {
367            crate::plan::SourcePlan::RetainedRows(_) => {}
368            SourcePlan::Join {
369                left,
370                right,
371                kind,
372                on,
373                using,
374                natural,
375                alias,
376                column_aliases,
377                lateral,
378                ..
379            } => {
380                let left_schema = self.bind_source_for_execution_in_scope(
381                    routines,
382                    left,
383                    subqueries,
384                    params,
385                    scope.with_names(),
386                )?;
387                let preceding = scope.right_namespace_with_control(
388                    left,
389                    &left_schema,
390                    *kind,
391                    &self.control(),
392                )?;
393                let right_schema = self.bind_source_for_execution_in_scope(
394                    routines,
395                    right,
396                    subqueries,
397                    params,
398                    SourceScope {
399                        outer: scope.outer,
400                        preceding: Some(&preceding),
401                        inherited_lateral: *lateral,
402                        retain_names: true,
403                    },
404                )?;
405                let condition = scope.condition_with_control(&self.control())?;
406                return self.bind_join_output_schema(JoinSchemaBinding {
407                    routines,
408                    kind: *kind,
409                    on: on.as_ref(),
410                    using: using.as_ref(),
411                    natural: *natural,
412                    alias: alias.as_deref(),
413                    column_aliases,
414                    left: &left_schema,
415                    right: &right_schema,
416                    subqueries,
417                    params,
418                    outer: condition.as_ref(),
419                });
420            }
421            SourcePlan::Function {
422                name, relations, ..
423            } => {
424                let lower = crate::semantics::builtin_function_dispatch_name(name);
425                if crate::registry::is_operator_join_table_function(&lower) {
426                    operator_join_relation_schemas(
427                        &self.catalog,
428                        &self.resolution,
429                        relations.as_ref(),
430                    )?;
431                    return self.bind_source(routines, source, subqueries, params, outer);
432                }
433                self.bind_table_function_for_execution(
434                    routines, source, subqueries, params, outer,
435                )?;
436            }
437            SourcePlan::FunctionGroup { functions, .. } => {
438                for function in functions {
439                    let mut member = table_function_member_source(function);
440                    self.bind_source_for_execution(
441                        routines,
442                        &mut member,
443                        subqueries,
444                        params,
445                        outer,
446                    )?;
447                    let SourcePlan::Function { binding, .. } = member else {
448                        unreachable!("table-function member changed source kind during binding")
449                    };
450                    function.binding = binding;
451                }
452            }
453            SourcePlan::Table { .. } | SourcePlan::Values { .. } | SourcePlan::Subquery { .. } => {}
454        }
455        self.bind_source(routines, source, subqueries, params, outer)
456    }
457
458    /// 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.
459    fn bind_table_function_for_execution(
460        &mut self,
461        routines: &dyn RoutineResolution,
462        source: &mut SourcePlan,
463        subqueries: &[QueryPlan],
464        params: &[SQLParam],
465        outer: Option<&RowSchema>,
466    ) -> Result<(), SQLError> {
467        let selected =
468            self.select_execution_table_function(routines, source, subqueries, params, outer)?;
469        if let Some(selected) = selected {
470            let SourcePlan::Function { binding, .. } = source else {
471                unreachable!("table-function source")
472            };
473            *binding = Some(
474                selected
475                    .into_uncontrolled()
476                    .expect("ordinary execution binding"),
477            );
478        }
479        Ok(())
480    }
481
482    fn select_execution_table_function(
483        &mut self,
484        routines: &dyn RoutineResolution,
485        source: &SourcePlan,
486        subqueries: &[QueryPlan],
487        params: &[SQLParam],
488        outer: Option<&RowSchema>,
489    ) -> Result<Option<uqa_core::memory::Produced<crate::ast::FunctionBinding>>, SQLError> {
490        let resources = self.production.clone();
491        let control = resources.control();
492        let SourcePlan::Function {
493            name,
494            binding,
495            args,
496            ..
497        } = source
498        else {
499            unreachable!("table-function source")
500        };
501        let input = outer.cloned().unwrap_or_default();
502        let resolver = self.query_function_type_resolver_for_subqueries(
503            routines, args, &input, subqueries, params,
504        )?;
505        let Some(selected) = crate::semantics::resolve_table_function_binding_with_control(
506            crate::semantics::TableFunctionAnalysis {
507                routines,
508                types: &resolver,
509            },
510            name,
511            binding.as_ref(),
512            args,
513            &input,
514            params,
515            &control,
516        )?
517        else {
518            return Ok(None);
519        };
520        let (mut selected, memory) = selected.into_parts();
521        if binding.is_none()
522            && selected.builtin
523            && crate::expr::binds_input_collation_by_name(
524                &crate::semantics::builtin_function_dispatch_name_with_control(name, &control)?,
525            )
526        {
527            selected.input_collation = super::preparation::call_input_collation(
528                self, routines, name, args, &input, subqueries, params,
529            )?;
530        }
531        Ok(Some(control.finish(selected, memory)?))
532    }
533}