Skip to main content

uqa_sql/semantics/rules/returning/
inspection.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! RETURNING image selection borrows expressions and lexical qualifiers without copying payloads or building name indexes.
8
9use super::{RuleReturningImages, RuleReturningRequest};
10use crate::{
11    ast::ReturningAliases,
12    plan::{CtePlanBody, ProjectionPlan, QueryPlan, RelationalPlan, SourcePlan},
13    SQLError, ScalarExpr,
14};
15use uqa_core::memory::ProductionControl;
16
17impl RuleReturningRequest {
18    pub fn from_plan(
19        returning: &[ProjectionPlan],
20        aliases: &ReturningAliases,
21        subqueries: &[QueryPlan],
22    ) -> Self {
23        Self::from_plan_with_control(
24            returning,
25            aliases,
26            subqueries,
27            &ProductionControl::uncontrolled(),
28        )
29        .expect("ordinary image inspection cannot fail")
30    }
31
32    pub fn from_plan_with_control(
33        returning: &[ProjectionPlan],
34        aliases: &ReturningAliases,
35        subqueries: &[QueryPlan],
36        control: &ProductionControl<'_>,
37    ) -> Result<Self, SQLError> {
38        control.check()?;
39        let mut inspection = Inspection {
40            request: Self {
41                capture: !returning.is_empty(),
42                ..Self::default()
43            },
44            aliases,
45            control: *control,
46        };
47        let scope = Scope::default();
48        for projection in returning {
49            inspection.expression(&projection.expr, &scope)?;
50            // Follow the same selected IDs after visiting the complete projection; other query blocks own and visit their full subquery list separately.
51            projection.expr.try_visit(&mut |node| {
52                if let ScalarExpr::ScalarSubquery(id)
53                | ScalarExpr::Exists { subquery: id, .. }
54                | ScalarExpr::InSubquery { subquery: id, .. } = node
55                {
56                    if let Some(query) = subqueries.get(*id) {
57                        inspection.query(query, &scope)?;
58                    }
59                }
60                control.check()?;
61                Ok::<_, SQLError>(true)
62            })?;
63        }
64        Ok(inspection.request)
65    }
66
67    pub const fn captures(self) -> bool {
68        self.capture
69    }
70}
71
72#[derive(Default)]
73struct Scope<'a> {
74    parent: Option<&'a Scope<'a>>,
75    source: Option<&'a SourcePlan>,
76    target: Option<&'a str>,
77    aliases: Option<&'a ReturningAliases>,
78}
79impl Scope<'_> {
80    fn contains(&self, name: &str, control: &ProductionControl<'_>) -> Result<bool, SQLError> {
81        control.check()?;
82        if self
83            .target
84            .is_some_and(|target| target.eq_ignore_ascii_case(name))
85            || self.aliases.is_some_and(|aliases| {
86                aliases.old.eq_ignore_ascii_case(name) || aliases.new.eq_ignore_ascii_case(name)
87            })
88        {
89            return Ok(true);
90        }
91        if let Some(source) = self.source {
92            if source_exports(source, name, control)? {
93                return Ok(true);
94            }
95        }
96        self.parent
97            .map_or(Ok(false), |parent| parent.contains(name, control))
98    }
99}
100
101fn source_exports(
102    source: &SourcePlan,
103    name: &str,
104    control: &ProductionControl<'_>,
105) -> Result<bool, SQLError> {
106    control.check()?;
107    match source {
108        SourcePlan::Join {
109            left, right, alias, ..
110        } => {
111            if let Some(alias) = alias {
112                Ok(alias.eq_ignore_ascii_case(name))
113            } else {
114                Ok(source_exports(left, name, control)? || source_exports(right, name, control)?)
115            }
116        }
117        _ => Ok(source
118            .visible_qualifier()
119            .is_some_and(|qualifier| qualifier.eq_ignore_ascii_case(name))),
120    }
121}
122
123struct Inspection<'a> {
124    request: RuleReturningRequest,
125    aliases: &'a ReturningAliases,
126    control: ProductionControl<'a>,
127}
128impl Inspection<'_> {
129    fn expression(&mut self, expression: &ScalarExpr, scope: &Scope<'_>) -> Result<(), SQLError> {
130        expression.try_visit(&mut |node| {
131            self.control.check()?;
132            match node {
133                ScalarExpr::Star | ScalarExpr::Column(_) | ScalarExpr::Position(_) => {
134                    self.request.images.insert(RuleReturningImages::CURRENT);
135                }
136                ScalarExpr::QualifiedStar(_) | ScalarExpr::QualifiedColumn { .. } => {
137                    let qualifier = node.reference_qualifier().expect("qualified reference");
138                    if !scope.contains(qualifier, &self.control)? {
139                        self.request.images.insert(
140                            if qualifier.eq_ignore_ascii_case(&self.aliases.old) {
141                                RuleReturningImages::OLD
142                            } else if qualifier.eq_ignore_ascii_case(&self.aliases.new) {
143                                RuleReturningImages::NEW
144                            } else {
145                                RuleReturningImages::CURRENT
146                            },
147                        );
148                    }
149                }
150                _ => {}
151            }
152            Ok(true)
153        })
154    }
155
156    fn cte_body(&mut self, body: &CtePlanBody, inherited: &Scope<'_>) -> Result<(), SQLError> {
157        self.control.check()?;
158        match body {
159            CtePlanBody::Query(query) => self.query(query, inherited),
160            CtePlanBody::Command(command) => {
161                let scope = Scope {
162                    parent: Some(inherited),
163                    source: command.source_input(),
164                    target: command.target_qualifier(),
165                    aliases: command.returning_aliases(),
166                };
167                if let Some(source) = command.source_input() {
168                    self.source(source, inherited)?;
169                }
170                for cte in command.ctes() {
171                    self.cte_body(&cte.body, &scope)?;
172                }
173                for query in command.query_inputs() {
174                    self.query(query, &scope)?;
175                }
176                for expression in command.expressions() {
177                    self.expression(expression, &scope)?;
178                }
179                Ok(())
180            }
181        }
182    }
183
184    fn query(&mut self, query: &QueryPlan, inherited: &Scope<'_>) -> Result<(), SQLError> {
185        self.control.check()?;
186        for cte in &query.ctes {
187            self.cte_body(&cte.body, inherited)?;
188        }
189        match &query.root {
190            RelationalPlan::QueryBlock(block) => {
191                let scope = Scope {
192                    parent: Some(inherited),
193                    source: block.from.as_ref(),
194                    ..Scope::default()
195                };
196                if let Some(source) = &block.from {
197                    self.source(source, inherited)?;
198                }
199                for expression in block
200                    .projections
201                    .iter()
202                    .map(|projection| &projection.expr)
203                    .chain(block.r#where.iter())
204                    .chain(&block.group_by)
205                    .chain(block.grouping_sets.iter().flatten())
206                    .chain(block.having.iter())
207                    .chain(block.order_by.iter().map(|order| &order.expr))
208                    .chain(block.limit.iter())
209                    .chain(block.offset.iter())
210                    .chain(&block.distinct_on)
211                {
212                    self.expression(expression, &scope)?;
213                }
214                for subquery in &block.subqueries {
215                    self.query(subquery, &scope)?;
216                }
217            }
218            RelationalPlan::SetOp {
219                left,
220                right,
221                order_by,
222                limit,
223                offset,
224                subqueries,
225                ..
226            } => {
227                self.query(left, inherited)?;
228                self.query(right, inherited)?;
229                for expression in order_by
230                    .iter()
231                    .map(|order| &order.expr)
232                    .chain(limit.as_deref())
233                    .chain(offset.as_deref())
234                {
235                    self.expression(expression, inherited)?;
236                }
237                for subquery in subqueries {
238                    self.query(subquery, inherited)?;
239                }
240            }
241            RelationalPlan::Values { rows, subqueries } => {
242                for expression in rows.iter().flatten() {
243                    self.expression(expression, inherited)?;
244                }
245                for subquery in subqueries {
246                    self.query(subquery, inherited)?;
247                }
248            }
249        }
250        Ok(())
251    }
252
253    fn source(&mut self, source: &SourcePlan, inherited: &Scope<'_>) -> Result<(), SQLError> {
254        self.control.check()?;
255        match source {
256            SourcePlan::RetainedRows(_) | SourcePlan::Table { .. } => {}
257            SourcePlan::Join {
258                left,
259                right,
260                on,
261                lateral,
262                ..
263            } => {
264                self.source(left, inherited)?;
265                let right_scope = Scope {
266                    parent: Some(inherited),
267                    source: lateral.then_some(left),
268                    ..Scope::default()
269                };
270                self.source(right, &right_scope)?;
271                if let Some(on) = on {
272                    let left_scope = Scope {
273                        parent: Some(inherited),
274                        source: Some(left),
275                        ..Scope::default()
276                    };
277                    let scope = Scope {
278                        parent: Some(&left_scope),
279                        source: Some(right),
280                        ..Scope::default()
281                    };
282                    self.expression(on, &scope)?;
283                }
284            }
285            SourcePlan::Values { rows, .. } => {
286                for expression in rows.iter().flatten() {
287                    self.expression(expression, inherited)?;
288                }
289            }
290            SourcePlan::Function { args, .. } => {
291                for expression in args {
292                    self.expression(expression, inherited)?;
293                }
294            }
295            SourcePlan::FunctionGroup { functions, .. } => {
296                for expression in functions.iter().flat_map(|function| &function.args) {
297                    self.expression(expression, inherited)?;
298                }
299            }
300            SourcePlan::Subquery { body, .. } => self.query(body, inherited)?,
301        }
302        Ok(())
303    }
304}