Skip to main content

uqa_sql/binding/
scoped_references.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Resolve consumed values against their lexical query and preceding-source scopes.
8
9mod substitution;
10pub use substitution::substitute_outer_columns;
11
12use crate::plan::{AnalyzedSource, QueryPlan, RelationalPlan, SourcePlan};
13use crate::{RowSchema, ScalarExpr};
14
15/// Visit input references not provided by a nested query or preceding LATERAL input. Analysis must have retained every required source layout.
16pub struct ScopedReferences<'a> {
17    visitor: &'a mut dyn FnMut(&ScalarExpr),
18    complete: bool,
19    scopes: Vec<RowSchema>,
20}
21
22impl<'a> ScopedReferences<'a> {
23    pub fn new(visitor: &'a mut dyn FnMut(&ScalarExpr)) -> Self {
24        Self {
25            visitor,
26            complete: true,
27            scopes: Vec::new(),
28        }
29    }
30
31    pub fn expression(&mut self, expression: &ScalarExpr, subqueries: &[QueryPlan]) {
32        crate::semantics::visit_input_values(expression, &mut |part| {
33            let index = match part {
34                ScalarExpr::ScalarSubquery(index)
35                | ScalarExpr::Exists {
36                    subquery: index, ..
37                }
38                | ScalarExpr::InSubquery {
39                    subquery: index, ..
40                } => Some(*index),
41                _ => None,
42            };
43            if let Some(index) = index {
44                if let Some(query) = subqueries.get(index) {
45                    self.query(query);
46                } else {
47                    self.complete = false;
48                }
49            } else if !self.scopes.iter().rev().any(|schema| {
50                let reference = crate::type_resolution::field_selection::field_reference(part)
51                    .map_or(part, |(base, _)| base);
52                locally_resolved(reference, schema)
53            }) {
54                (self.visitor)(part);
55            }
56        });
57    }
58
59    pub fn is_complete(&self) -> bool {
60        self.complete
61    }
62
63    pub fn query(&mut self, query: &QueryPlan) {
64        for cte in &query.ctes {
65            if let Some(query) = cte.body.query() {
66                self.query(query);
67            } else {
68                self.complete = false;
69            }
70        }
71        match &query.root {
72            RelationalPlan::QueryBlock(block) => {
73                if let Some(input) = &block.from {
74                    self.complete &= query.analyzed_source.is_some();
75                    self.source(
76                        input,
77                        query.analyzed_source.as_deref(),
78                        &block.subqueries,
79                        &[],
80                        false,
81                    );
82                }
83                let length = self.scopes.len();
84                self.scopes.push(
85                    query
86                        .analyzed_source
87                        .as_ref()
88                        .map(|source| source.schema.clone())
89                        .unwrap_or_default(),
90                );
91                for expr in query_inputs(block) {
92                    self.expression(expr, &block.subqueries);
93                }
94                self.scopes.truncate(length);
95            }
96            RelationalPlan::SetOp {
97                left,
98                right,
99                order_by,
100                limit,
101                offset,
102                subqueries,
103                ..
104            } => {
105                self.query(left);
106                self.query(right);
107                self.complete &= query.analyzed_output.is_some();
108                let length = self.scopes.len();
109                self.scopes
110                    .push(query.analyzed_output.clone().unwrap_or_default());
111                for expr in order_by
112                    .iter()
113                    .map(|order| &order.expr)
114                    .chain(limit.as_deref())
115                    .chain(offset.as_deref())
116                {
117                    self.expression(expr, subqueries);
118                }
119                self.scopes.truncate(length);
120            }
121            RelationalPlan::Values { rows, subqueries } => {
122                for expr in rows.iter().flatten() {
123                    self.expression(expr, subqueries);
124                }
125            }
126        }
127    }
128
129    pub fn source(
130        &mut self,
131        source: &SourcePlan,
132        analysis: Option<&AnalyzedSource>,
133        subqueries: &[QueryPlan],
134        preceding: &[RowSchema],
135        inherited_lateral: bool,
136    ) {
137        let length = self.scopes.len();
138        if inherited_lateral
139            || source.is_explicitly_lateral()
140            || matches!(
141                source,
142                SourcePlan::Function { .. } | SourcePlan::FunctionGroup { .. }
143            )
144        {
145            self.scopes.extend_from_slice(preceding);
146        }
147        match source {
148            SourcePlan::Join {
149                left,
150                right,
151                on,
152                lateral,
153                ..
154            } => {
155                if let Some(children) = analysis.and_then(|source| source.children.as_deref()) {
156                    self.source(left, Some(&children.0), subqueries, preceding, false);
157                    let mut right_preceding = preceding.to_vec();
158                    right_preceding.push(children.0.schema.clone());
159                    self.source(
160                        right,
161                        Some(&children.1),
162                        subqueries,
163                        &right_preceding,
164                        *lateral,
165                    );
166                    if let Some(on) = on {
167                        self.scopes.push(children.0.schema.clone());
168                        self.scopes.push(children.1.schema.clone());
169                        self.expression(on, subqueries);
170                    }
171                } else {
172                    self.complete = false;
173                }
174            }
175            SourcePlan::Subquery { body, .. }
176            | SourcePlan::Table {
177                executable_query: Some(body),
178                ..
179            } => self.query(body),
180            SourcePlan::Values { rows, .. } => {
181                for expr in rows.iter().flatten() {
182                    self.expression(expr, subqueries);
183                }
184            }
185            SourcePlan::Function { args, .. } => {
186                for expr in args {
187                    self.expression(expr, subqueries);
188                }
189            }
190            SourcePlan::FunctionGroup { functions, .. } => {
191                for expr in functions.iter().flat_map(|function| &function.args) {
192                    self.expression(expr, subqueries);
193                }
194            }
195            SourcePlan::RetainedRows(_) | SourcePlan::Table { .. } => {}
196        }
197        self.scopes.truncate(length);
198    }
199}
200
201fn locally_resolved(expression: &ScalarExpr, schema: &RowSchema) -> bool {
202    match expression {
203        ScalarExpr::Column(name) => {
204            schema.resolves_local_column(None, name) || schema.has_qualifier(name)
205        }
206        ScalarExpr::QualifiedColumn { qualifier, .. } => schema.has_qualifier(qualifier),
207        ScalarExpr::QualifiedStar(qualifier) => schema.has_qualifier(qualifier),
208        ScalarExpr::InternalColumn(column) => schema.internal_slot(*column).is_some(),
209        ScalarExpr::Star | ScalarExpr::Position(_) => true,
210        _ => false,
211    }
212}
213
214/// SQL92 ORDER BY and DISTINCT ON names and positions observe an output already included in projection demand; expressions inside those clauses still resolve against the input namespace.
215pub fn query_inputs(block: &crate::plan::QueryBlockPlan) -> impl Iterator<Item = &ScalarExpr> {
216    block.query_expressions().filter(|expression| {
217        let ordering = block
218            .order_by
219            .iter()
220            .map(|order| &order.expr)
221            .chain(&block.distinct_on)
222            .any(|order| std::ptr::eq(order, *expression));
223        !ordering || !ordering_uses_output(expression, &block.projections)
224    })
225}
226
227/// SQL92 output names and ordinals bind to the selected output, while compound ordering expressions use the input namespace.
228pub fn ordering_uses_output(
229    expression: &ScalarExpr,
230    projections: &[crate::plan::ProjectionPlan],
231) -> bool {
232    match expression {
233        ScalarExpr::Position(_) | ScalarExpr::Literal(uqa_core::Value::Int(_)) => true,
234        ScalarExpr::Column(name) => projections
235            .iter()
236            .any(|projection| crate::semantics::projection_label_at(projection) == name.as_str()),
237        _ => false,
238    }
239}