Skip to main content

uqa_sql/binding/
mod.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Static relational row-type binding.
8//!
9//! This module derives source and query output schemas from plans, catalog
10//! declarations, and already-bound CTE schemas. It never executes a query or
11//! samples a result row, so empty, spilled, and correlated relations retain
12//! the same declared `PostgreSQL` type identities as non-empty relations.
13
14mod analysis;
15pub mod catalog_sources;
16mod command_scopes;
17mod commands;
18pub mod composite_dependencies;
19mod composite_inputs;
20pub mod composite_rename;
21mod cte_controls;
22mod ctes;
23mod dependencies;
24mod execution;
25pub mod legacy_collations;
26pub mod legacy_patterns;
27mod merge_scopes;
28mod ordered_calls;
29mod preparation;
30pub mod production;
31pub use production::{
32    analyze_query_plan_schema_with_control, analyze_source_plan_schema_with_control,
33    bind_query_plan_schema_with_control,
34};
35mod projection;
36mod record_fields;
37mod routine_binding;
38mod routine_parameters;
39mod scope;
40pub mod scoped_references;
41mod source_schemas;
42mod sources;
43pub use sources::bind_source_plan_schema_in_scope;
44pub mod statements;
45mod type_resolution;
46mod variable_sites;
47
48pub use commands::{analyze_prepared_command_schema, analyze_prepared_command_schema_with_control};
49pub use execution::{
50    bind_query_block_for_execution, bind_query_block_for_execution_with_control,
51    bind_query_block_with_sources, bind_query_block_with_sources_with_control, BoundExecutionBlock,
52    ControlledExecutionBlock, ExecutionBindingOptions, ExecutionQueryBlock,
53    ExecutionSourceBindings, SharedExecutionSourceBindings,
54};
55pub use preparation::bind_expression_plan_routines_for_storage_owned;
56pub use preparation::{
57    analyze_column_type_transform, assign_stored_query_input_collations,
58    bind_routine_parameter_references_owned, infer_prepared_parameter_types,
59    parameter_input_types_with_control, prepare_routine_body_inputs_owned,
60    read_prepared_inputs_owned, read_procedural_inputs_owned, read_procedure_inputs_owned,
61    restore_query_layouts, restore_query_layouts_owned, retain_prepared_input_metadata_owned,
62    PreparedOwnedInputs, PreparedOwnedRoutineBody, ProceduralOwnedInputs,
63};
64pub(crate) use preparation::{
65    analyze_default_inputs, analyze_routine_body_argument, analyze_routine_body_inputs,
66    prepare_routine_body_inputs, read_procedure_inputs,
67};
68pub(crate) use preparation::{
69    analyze_domain_check, analyze_stored_expression_inputs, analyze_table_check,
70    assign_stored_input_collations, read_prepared_inputs, retain_prepared_input_metadata,
71};
72
73#[cfg(test)]
74mod tests;
75
76pub use cte_controls::{analyze_recursive_control_step, extend_cte_generated_schema};
77pub use preparation::resolve_variable_sites_owned;
78pub use projection::{
79    analyze_projection_output_schema, analyze_projection_output_schema_with_control,
80    bind_projection_output_schema, bind_projection_output_schema_with_control,
81    validate_query_block_expression_types, validate_query_block_expression_types_with_control,
82    validate_query_block_references, validate_query_block_references_with_control,
83    ProjectionSchemas,
84};
85pub use routine_binding::{
86    bind_expression_plan_routines_for_storage, bind_query_plan_routines_for_storage,
87    bind_syntax_query_plan_routines,
88};
89pub use routine_parameters::{bind_routine_parameter_references, RoutineParameterScope};
90pub use scope::SourceScope;
91pub use scope::{
92    analyze_expression_plan_type, analyze_query_plan_schema,
93    analyze_query_plan_schema_with_catalog, bind_expression_plan_type, bind_query_plan_schema,
94};
95pub use scope::{
96    overlay_outer_schema, overlay_outer_schema_with_control, values_schema_in_scope,
97    values_types_in_scope,
98};
99pub use sources::{
100    analyze_source_plan_schema, bind_source_input_schema, bind_source_plan_for_execution_owned,
101    bind_source_plan_schema, bind_source_plan_schema_for_execution,
102    with_query_table_pseudo_columns, with_query_table_pseudo_columns_with_control,
103    SourceBindingInput,
104};
105pub use variable_sites::{resolve_variable_sites, VariableSiteResolution};
106
107use catalog_sources::operator_join_relation_schemas;
108use cte_controls::extend_recursive_cte_binding_schema;
109pub use cte_controls::hide_recursive_generated_schema;
110use projection::rename_schema;
111use sources::{alias_table_schema, JoinSchemaBinding};
112use type_resolution::QueryFunctionTypeResolver;
113
114use crate::plan::{QueryBlockPlan, QueryPlan, RelationalPlan, SourcePlan};
115use crate::semantics::{cte_references_own_name, projection_columns};
116use crate::{SQLError, SQLParam, ScalarExpr};
117pub use context::BindingContext;
118
119pub mod context;
120mod rule_inputs;
121use crate::ast::ColumnType;
122use crate::catalog::analysis::CatalogReadView;
123use crate::catalog::resolution::RelationNameResolution;
124use crate::routines::RoutineResolution;
125use crate::RowSchema;
126
127#[cfg(test)]
128thread_local! {
129    static SOURCE_BINDINGS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
130}
131
132#[derive(Clone, Copy)]
133enum ScalarBindingMode {
134    References,
135    Stored,
136    CompositeInputs,
137}
138
139struct SchemaScope {
140    execution_sources: Option<execution::CapturedSources>,
141    collations: preparation::PendingCollations,
142    catalog: CatalogReadView,
143    resolution: production::BindingResolution,
144    ctes: production::BindingMap<RowSchema>,
145    deferred_ctes: production::BindingMap<crate::plan::RetainedCtePlan>,
146    non_returning_ctes: production::BindingNameSet,
147    production: uqa_core::memory::OwnedProductionControl,
148    visiting_views: production::BindingNameSet,
149    validate_references: bool,
150    stored_expression_outer: Option<RowSchema>,
151    rule_condition_event: Option<crate::ast::RuleEvent>,
152    /// Native MERGE action syntax is legal in a RETURNING expression and its descendant queries.
153    merge_returning: bool,
154    /// The kind of expression under analysis at this query level, which decides where a set-returning call may appear, as `PostgreSQL`'s `p_expr_kind` does.
155    set_placement: crate::semantics::sets::placement::SetPlacement,
156    /// The set-returning calls analyzed so far at this query level. Two readings differ exactly when an expression analyzed between them contains one, as `PostgreSQL` compares `p_last_srf`.
157    set_calls: usize,
158    stored_whole_rows: [Option<crate::plan::OwnedScalarExpr>; 2],
159    /// The parameters of the SQL routine whose body is bound, as the outermost scope: a reference that resolves into them, because no column of any query level takes its name, becomes the positional parameter it names.
160    routine_parameters: Option<RoutineParameterScope>,
161    /// Select reference resolution, complete stored binding, or prepared composite identity retention.
162    scalar_binding: ScalarBindingMode,
163    /// The names of a `PL/pgSQL` statement that the function's variables take, checked against what the statement can see.
164    variable_sites: Option<variable_sites::VariableSites>,
165    /// Keep `*` projections and `GROUP BY` output-name references as written, so a bound copy of stored syntax still corresponds to that syntax node for node.
166    preserve_syntax_shape: bool,
167    prepared_dependencies: Option<crate::prepared::dependencies::PreparedAnalysisDependencies>,
168    composite_dependencies: Option<Vec<crate::catalog::dependencies::ObjectAddress>>,
169}
170
171fn non_returning_cte_error(name: &str) -> SQLError {
172    SQLError::Unsupported(format!(
173        "WITH query \"{name}\" does not have a RETURNING clause"
174    ))
175}
176
177impl SchemaScope {
178    fn from_context(ctes: &BindingContext) -> Result<Self, SQLError> {
179        let control = uqa_core::memory::ProductionControl::uncontrolled();
180        Self::from_context_with_control(ctes.copy_with_control(&control)?, &control)
181    }
182
183    fn for_analysis(ctes: &BindingContext) -> Result<Self, SQLError> {
184        let control = uqa_core::memory::ProductionControl::uncontrolled();
185        Self::for_analysis_with_control(ctes.copy_with_control(&control)?, &control)
186    }
187
188    fn for_catalog_analysis(catalog: CatalogReadView, resolution: RelationNameResolution) -> Self {
189        let control = uqa_core::memory::ProductionControl::uncontrolled();
190        Self::for_analysis_with_control(
191            production::ControlledBindingContext {
192                catalog,
193                resolution: resolution.into(),
194                ctes: production::BindingMap::new(),
195                deferred_ctes: production::BindingMap::new(),
196                non_returning_ctes: production::BindingNameSet::new(),
197                scalar_subqueries: &[],
198            },
199            &control,
200        )
201        .expect("ordinary catalog scope construction")
202    }
203
204    fn bind_query(
205        &mut self,
206        routines: &dyn RoutineResolution,
207        plan: &QueryPlan,
208        params: &[SQLParam],
209        outer: Option<&RowSchema>,
210    ) -> Result<RowSchema, SQLError> {
211        let lookup_mode = if plan.relations_bound {
212            crate::catalog::resolution::RelationLookupMode::Bound
213        } else {
214            crate::catalog::resolution::RelationLookupMode::Dynamic
215        };
216        let previous = self.resolution.set_lookup_mode(lookup_mode);
217        let result = self.bind_query_inner(routines, plan, params, outer);
218        self.resolution.set_lookup_mode(previous);
219        result
220    }
221
222    fn bind_query_inner(
223        &mut self,
224        routines: &dyn RoutineResolution,
225        plan: &QueryPlan,
226        params: &[SQLParam],
227        outer: Option<&RowSchema>,
228    ) -> Result<RowSchema, SQLError> {
229        let previous = self.bind_cte_schemas(routines, &plan.ctes, params, outer)?;
230
231        let result = self.bind_root(routines, &plan.root, params, outer);
232        self.restore_cte_schemas(previous);
233        let output = result?;
234        self.collations.validate_query(plan)?;
235        Ok(output)
236    }
237
238    fn bind_recursive_seed(
239        &mut self,
240        routines: &dyn RoutineResolution,
241        plan: &QueryPlan,
242        params: &[SQLParam],
243        outer: Option<&RowSchema>,
244    ) -> Result<RowSchema, SQLError> {
245        match &plan.root {
246            RelationalPlan::SetOp { left, .. } => self.bind_query(routines, left, params, outer),
247            _ => self.bind_root(routines, &plan.root, params, outer),
248        }
249    }
250
251    fn bind_root(
252        &mut self,
253        routines: &dyn RoutineResolution,
254        root: &RelationalPlan,
255        params: &[SQLParam],
256        outer: Option<&RowSchema>,
257    ) -> Result<RowSchema, SQLError> {
258        match root {
259            RelationalPlan::QueryBlock(block) => {
260                self.bind_query_block(routines, block, params, outer)
261            }
262            RelationalPlan::SetOp { .. } => {
263                preparation::set_metadata(self, routines, root, outer, params)
264            }
265            RelationalPlan::Values { rows, subqueries } => {
266                self.bind_values_schema(routines, rows, subqueries, outer, params)
267            }
268        }
269    }
270
271    fn bind_query_block(
272        &mut self,
273        routines: &dyn RoutineResolution,
274        block: &QueryBlockPlan,
275        params: &[SQLParam],
276        outer: Option<&RowSchema>,
277    ) -> Result<RowSchema, SQLError> {
278        let production = self.production.clone();
279        let control = production.control();
280        let captured_outer = outer
281            .map(|schema| {
282                crate::semantics::view_rewrite::bind_outer_rewrite_scope_with_control(
283                    block, schema, &control,
284                )
285            })
286            .transpose()?;
287        let outer = captured_outer.as_deref();
288        let source_rewrites = if block.deferred_outer_rewrites.is_empty() || block.from.is_none() {
289            None
290        } else {
291            Some(crate::semantics::view_rewrite::resolve_outer_sources_owned(
292                block.copy_for_rewrite(&control)?,
293                outer,
294                &mut |source, subqueries, scope| {
295                    self.bind_source_input(routines, source, subqueries, params, scope)
296                },
297                &control,
298            )?)
299        };
300        let block = match &source_rewrites {
301            Some(query) => {
302                let RelationalPlan::QueryBlock(block) = &query.root else {
303                    unreachable!("retained query block")
304                };
305                block.as_ref()
306            }
307            None => block,
308        };
309        let source = match block.from.as_ref() {
310            Some(source) => self.bind_source(routines, source, &block.subqueries, params, outer)?,
311            None => RowSchema::new_with_control(
312                control.finish(Vec::new(), control.empty_reservation())?,
313                &control,
314            )?,
315        };
316        if let Some(sources) = &mut self.execution_sources {
317            sources.record(block, &source, outer);
318        }
319        // Query-owned metadata types belong to both analysis and metadata-only binding.
320        let source = analysis::with_query_source_columns_with_control(&source, block, &control)?;
321        let rewritten = if block.deferred_outer_rewrites.is_empty() {
322            None
323        } else {
324            Some(
325                crate::semantics::view_rewrite::resolve_outer_rewrites_owned(
326                    block.copy_for_rewrite(&control)?,
327                    &source,
328                    &control,
329                )?,
330            )
331        };
332        let block = match &rewritten {
333            Some(query) => {
334                let RelationalPlan::QueryBlock(block) = &query.root else {
335                    unreachable!("retained query block")
336                };
337                block.as_ref()
338            }
339            None => block,
340        };
341        let expression_schema = overlay_outer_schema_with_control(&source, outer, &control)?;
342        let output = preparation::block_metadata(self, routines, block, &source, outer, params)?;
343        let output = analysis::with_projected_open_columns_with_control(
344            &output,
345            &block.projections,
346            &source,
347            &control,
348        )?;
349        if self.validate_references {
350            self.validate_query_block_clauses(
351                routines,
352                block,
353                &expression_schema,
354                &output,
355                params,
356                outer,
357            )?;
358        }
359        Ok(output)
360    }
361
362    fn bind_expression_type(
363        &mut self,
364        routines: &dyn RoutineResolution,
365        expression: &ScalarExpr,
366        schema: &RowSchema,
367        subqueries: &[QueryPlan],
368        params: &[SQLParam],
369    ) -> Result<Option<ColumnType>, SQLError> {
370        if let ScalarExpr::ScalarSubquery(index) = expression {
371            let plan = subqueries.get(*index).ok_or_else(|| {
372                SQLError::Internal(format!("scalar subquery slot {index} is out of bounds"))
373            })?;
374            // Result typing and validation share the complete lexical row scope.
375            let subquery_outer = Some(schema);
376            let output = self.bind_query(routines, plan, params, subquery_outer)?;
377            return Ok(output.column_type(0).cloned());
378        }
379        let schema = self.with_stored_outer_internal_aliases(schema)?;
380        let schema = &schema;
381        let resolver =
382            self.query_function_type_resolver(routines, expression, schema, subqueries, params)?;
383        if self.validate_references {
384            Self::validate_expression_references_with_resolver(
385                self.rule_condition_event,
386                routines,
387                expression,
388                schema,
389                None,
390                params,
391                &resolver,
392            )?;
393        }
394        crate::type_resolution::validate_catalog_literals(expression, schema, params, &resolver)?;
395        crate::scalar_type_with_resolver(expression, schema, params, &resolver)
396    }
397
398    fn bind_projection_metadata(
399        &mut self,
400        routines: &dyn RoutineResolution,
401        expression: &ScalarExpr,
402        schema: &RowSchema,
403        subqueries: &[QueryPlan],
404        params: &[SQLParam],
405    ) -> Result<projection::ProjectionMetadata, SQLError> {
406        let schema = self.with_stored_outer_internal_aliases(schema)?;
407        preparation::projection_metadata(self, routines, expression, &schema, subqueries, params)
408    }
409
410    #[expect(
411        clippy::too_many_lines,
412        reason = "preserves SELECT schema and row identity"
413    )]
414    fn bind_source_inner(
415        &mut self,
416        routines: &dyn RoutineResolution,
417        source: &SourcePlan,
418        subqueries: &[QueryPlan],
419        params: &[SQLParam],
420        scope: SourceScope<'_>,
421    ) -> Result<RowSchema, SQLError> {
422        #[cfg(test)]
423        SOURCE_BINDINGS.with(|count| count.set(count.get() + 1));
424        let input = (!matches!(source, SourcePlan::Join { .. }))
425            .then(|| scope.input_with_control(source, &self.control()))
426            .transpose()?
427            .flatten();
428        let outer = input.as_ref();
429        match source {
430            SourcePlan::Table { .. } => self.bind_relation_source(routines, source, params, outer),
431            SourcePlan::Values {
432                rows,
433                alias,
434                column_aliases,
435                internal_relation,
436                internal_column_types,
437                ..
438            } => {
439                if internal_relation.is_some()
440                    && internal_column_types.iter().any(Option::is_none)
441                    && !rows.is_empty()
442                {
443                    let inferred =
444                        self.bind_values_schema(routines, rows, subqueries, outer, params)?;
445                    if let Some(schema) = source
446                        .internal_values_schema_with_control(Some(&inferred), &self.control())?
447                    {
448                        return Ok(schema);
449                    }
450                }
451                if let Some(schema) =
452                    source.internal_values_schema_with_control(None, &self.control())?
453                {
454                    return Ok(schema);
455                }
456                let schema = self.bind_values_schema(routines, rows, subqueries, outer, params)?;
457                projection::rename_schema_with_control(
458                    &schema,
459                    column_aliases,
460                    alias.as_deref(),
461                    &self.control(),
462                )
463            }
464            SourcePlan::RetainedRows(source) => Ok(source.schema().clone()),
465            SourcePlan::Function { .. } => {
466                self.bind_function_source(routines, source, subqueries, params, outer)
467            }
468            SourcePlan::FunctionGroup { .. } => {
469                self.bind_function_group_source(routines, source, subqueries, params, outer)
470            }
471            SourcePlan::Subquery {
472                body,
473                alias,
474                column_aliases,
475                ..
476            } => {
477                let schema = self.bind_query(routines, body, params, outer)?;
478                Ok(match source {
479                    SourcePlan::Subquery {
480                        captured_output: Some(relation),
481                        ..
482                    } => {
483                        RowSchema::capture_output_with_control(&schema, *relation, &self.control())?
484                    }
485                    _ => match alias {
486                        Some(alias) if !schema.columns_are_open(None) => {
487                            alias_table_schema(&schema, alias, column_aliases, &self.control())?
488                        }
489                        alias => projection::rename_schema_with_control(
490                            &schema,
491                            column_aliases,
492                            alias.as_deref(),
493                            &self.control(),
494                        )?,
495                    },
496                })
497            }
498            SourcePlan::Join {
499                left,
500                right,
501                kind,
502                on,
503                using,
504                natural,
505                alias,
506                column_aliases,
507                lateral,
508                ..
509            } => {
510                let left_schema = self.bind_source_in_scope(
511                    routines,
512                    left,
513                    subqueries,
514                    params,
515                    scope.with_names(),
516                )?;
517                let preceding = scope.right_namespace_with_control(
518                    left,
519                    &left_schema,
520                    *kind,
521                    &self.control(),
522                )?;
523                let right_schema = self.bind_source_in_scope(
524                    routines,
525                    right,
526                    subqueries,
527                    params,
528                    SourceScope {
529                        outer: scope.outer,
530                        preceding: Some(&preceding),
531                        inherited_lateral: *lateral,
532                        retain_names: true,
533                    },
534                )?;
535                let condition = scope.condition_with_control(&self.control())?;
536                self.bind_join_output_schema(JoinSchemaBinding {
537                    routines,
538                    kind: *kind,
539                    on: on.as_ref(),
540                    using: using.as_ref(),
541                    natural: *natural,
542                    alias: alias.as_deref(),
543                    column_aliases,
544                    left: &left_schema,
545                    right: &right_schema,
546                    subqueries,
547                    params,
548                    outer: condition.as_ref(),
549                })
550            }
551        }
552    }
553}
554
555#[cfg(test)]
556pub(crate) mod fixture;
557
558pub mod correlation;
559
560pub mod stored_columns;
561pub mod stored_relations;
562pub mod stored_routines;
563pub mod stored_types;
564pub mod syntax_sites;
565
566pub mod scoped_types;
567pub mod snapshot;
568
569pub mod view_dependencies;
570
571pub mod portals;