Skip to main content

uqa_sql/binding/
scope.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Outer-scope composition and common row-value typing.
8
9use crate::ast::ColumnType;
10use crate::plan::{ExpressionPlan, QueryPlan};
11use crate::RowSchema;
12use crate::{SQLError, SQLParam};
13
14use super::{BindingContext, ScalarExpr, SchemaScope};
15use crate::routines::RoutineResolution;
16mod production;
17pub use production::overlay_outer_schema_with_control;
18
19/// Derive the exact output row type of a query plan without executing it.
20pub fn bind_query_plan_schema(
21    routines: &dyn RoutineResolution,
22    plan: &QueryPlan,
23    params: &[SQLParam],
24    ctes: &BindingContext,
25    outer: Option<&RowSchema>,
26) -> Result<RowSchema, SQLError> {
27    SchemaScope::from_context(ctes)?.bind_query(routines, plan, params, outer)
28}
29
30/// Derive the declared SQL type of a standalone expression plan without executing it. The plan-owned subquery arena participates in type resolution so scalar subqueries retain their projected type at command boundaries such as `CALL`.
31pub fn bind_expression_plan_type(
32    routines: &dyn RoutineResolution,
33    plan: &ExpressionPlan,
34    params: &[SQLParam],
35    ctes: &BindingContext,
36) -> Result<Option<ColumnType>, SQLError> {
37    SchemaScope::from_context(ctes)?.bind_expression_type(
38        routines,
39        &plan.scalar,
40        &RowSchema::default(),
41        &plan.subqueries,
42        params,
43    )
44}
45
46/// Validate a command argument's names and types without running its expressions.
47pub fn analyze_expression_plan_type(
48    routines: &dyn RoutineResolution,
49    plan: &ExpressionPlan,
50    params: &[SQLParam],
51    ctes: &BindingContext,
52) -> Result<Option<ColumnType>, SQLError> {
53    SchemaScope::for_analysis(ctes)?.bind_expression_type(
54        routines,
55        &plan.scalar,
56        &RowSchema::default(),
57        &plan.subqueries,
58        params,
59    )
60}
61
62/// Analyze every catalog and scalar reference and derive the exact output row type without executing the query.
63pub fn analyze_query_plan_schema(
64    routines: &dyn RoutineResolution,
65    plan: &QueryPlan,
66    params: &[SQLParam],
67    ctes: &BindingContext,
68    outer: Option<&RowSchema>,
69) -> Result<RowSchema, SQLError> {
70    SchemaScope::for_analysis(ctes)?.bind_query(routines, plan, params, outer)
71}
72
73pub fn analyze_query_plan_schema_with_catalog(
74    routines: &dyn RoutineResolution,
75    plan: &QueryPlan,
76    params: &[SQLParam],
77    catalog: crate::catalog::analysis::CatalogReadView,
78    resolution: crate::catalog::resolution::RelationNameResolution,
79) -> Result<RowSchema, SQLError> {
80    SchemaScope::for_catalog_analysis(catalog, resolution).bind_query(routines, plan, params, None)
81}
82
83pub fn overlay_outer_schema(current: &RowSchema, outer: Option<&RowSchema>) -> RowSchema {
84    outer.map_or_else(
85        || current.clone(),
86        |outer| RowSchema::with_outer_schema(current, outer),
87    )
88}
89
90/// Lexical ancestors and preceding FROM items are different namespaces. Only a lateral range item activates its preceding peers; a nested join carries them to either operand without changing their query level.
91#[derive(Clone, Copy)]
92#[doc(hidden)]
93pub struct SourceScope<'a> {
94    pub outer: Option<&'a RowSchema>,
95    pub preceding: Option<&'a RowSchema>,
96    pub inherited_lateral: bool,
97    pub retain_names: bool,
98}
99
100impl<'a> SourceScope<'a> {
101    pub fn describe_output(source: &crate::plan::SourcePlan, schema: RowSchema) -> RowSchema {
102        match source {
103            crate::plan::SourcePlan::Join { alias: Some(_), .. } => {
104                RowSchema::with_join_diagnostic_namespace(&schema, source_namespace(source))
105            }
106            crate::plan::SourcePlan::Join { alias: None, .. }
107            | crate::plan::SourcePlan::RetainedRows(_) => schema,
108            _ => RowSchema::with_source_diagnostic_namespace(&schema, source_namespace(source)),
109        }
110    }
111
112    pub fn with_names(self) -> Self {
113        Self {
114            retain_names: true,
115            ..self
116        }
117    }
118
119    pub fn command_target(
120        command: &crate::plan::CommandPlan,
121        target: &RowSchema,
122    ) -> Option<RowSchema> {
123        matches!(
124            command,
125            crate::plan::CommandPlan::Update(_) | crate::plan::CommandPlan::Delete(_)
126        )
127        .then(|| {
128            let namespace = command
129                .target_qualifier()
130                .expect("mutation target qualifier");
131            let target = RowSchema::with_relation_qualifier(target, namespace);
132            let target = RowSchema::with_source_diagnostic_namespace(&target, namespace);
133            RowSchema::without_target_lateral_access(&target, namespace)
134        })
135    }
136
137    pub fn new(outer: Option<&'a RowSchema>) -> Self {
138        Self {
139            outer,
140            preceding: None,
141            inherited_lateral: false,
142            retain_names: false,
143        }
144    }
145
146    pub fn input(self, source: &crate::plan::SourcePlan) -> Option<RowSchema> {
147        use crate::plan::SourcePlan;
148        let Some(preceding) = self.preceding else {
149            return self.outer.cloned();
150        };
151        let active = self.inherited_lateral
152            || matches!(
153                source,
154                SourcePlan::Function { .. }
155                    | SourcePlan::FunctionGroup { .. }
156                    | SourcePlan::Values { lateral: true, .. }
157                    | SourcePlan::Subquery { lateral: true, .. }
158            );
159        Some(if active {
160            overlay_outer_schema(preceding, self.outer)
161        } else {
162            RowSchema::with_unavailable_names(
163                &self.outer.cloned().unwrap_or_default(),
164                preceding,
165                true,
166            )
167        })
168    }
169
170    pub fn right_namespace(
171        self,
172        source: &crate::plan::SourcePlan,
173        left: &RowSchema,
174        kind: crate::ast::JoinKind,
175    ) -> RowSchema {
176        let left = lateral_join_scope(source, left, None, kind);
177        self.preceding.map_or_else(
178            || left.clone(),
179            |preceding| RowSchema::with_peer_scope(preceding, &left),
180        )
181    }
182
183    pub fn condition(self) -> Option<RowSchema> {
184        self.preceding.map_or_else(
185            || self.outer.cloned(),
186            |preceding| {
187                Some(RowSchema::with_unavailable_names(
188                    &self.outer.cloned().unwrap_or_default(),
189                    preceding,
190                    false,
191                ))
192            },
193        )
194    }
195}
196
197pub(super) fn lateral_join_scope(
198    source: &crate::plan::SourcePlan,
199    left: &RowSchema,
200    outer: Option<&RowSchema>,
201    kind: crate::ast::JoinKind,
202) -> RowSchema {
203    if matches!(
204        kind,
205        crate::ast::JoinKind::Right | crate::ast::JoinKind::Full
206    ) {
207        let namespace = source_namespace(source);
208        overlay_outer_schema(&RowSchema::without_lateral_access(left, namespace), outer)
209    } else {
210        overlay_outer_schema(left, outer)
211    }
212}
213
214pub fn values_types_in_scope(
215    routines: &dyn RoutineResolution,
216    rows: &[Vec<ScalarExpr>],
217    subqueries: &[QueryPlan],
218    schema: Option<&RowSchema>,
219    params: &[SQLParam],
220    ctes: &BindingContext,
221) -> Result<Vec<Option<ColumnType>>, SQLError> {
222    SchemaScope::from_context(ctes)?.bind_values_types(routines, rows, subqueries, schema, params)
223}
224
225/// Preserve the complete analyzed VALUES output metadata for physical execution.
226pub fn values_schema_in_scope(
227    routines: &dyn RoutineResolution,
228    rows: &[Vec<ScalarExpr>],
229    subqueries: &[QueryPlan],
230    schema: Option<&RowSchema>,
231    params: &[SQLParam],
232    ctes: &BindingContext,
233) -> Result<RowSchema, SQLError> {
234    SchemaScope::from_context(ctes)?.bind_values_schema(routines, rows, subqueries, schema, params)
235}
236
237fn source_namespace(source: &crate::plan::SourcePlan) -> &str {
238    use crate::plan::SourcePlan;
239    // These diagnostic range-entry names do not expose a SQL qualifier.
240    match source {
241        SourcePlan::Table {
242            qualifier, alias, ..
243        } => alias.as_deref().unwrap_or(qualifier),
244        SourcePlan::Function {
245            output_name, alias, ..
246        } => alias.as_deref().unwrap_or(output_name),
247        SourcePlan::FunctionGroup {
248            functions, alias, ..
249        } => alias.as_deref().unwrap_or_else(|| {
250            &functions
251                .first()
252                .expect("bound ROWS FROM source has a member")
253                .output_name
254        }),
255        SourcePlan::Join { alias, .. } => alias.as_deref().unwrap_or("unnamed_join"),
256        SourcePlan::Values { alias, .. } | SourcePlan::Subquery { alias, .. } => {
257            alias.as_deref().unwrap_or("unnamed_subquery")
258        }
259        SourcePlan::RetainedRows(_) => "unnamed_subquery",
260    }
261}