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