Skip to main content

uqa_sql/plan/mutable/
scoped.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Consuming scoped visitation keeps constructor ownership and admitted lexical names through command and source rewrites.
8
9use super::{
10    CommandQuerySlot, MutableCommandPlan, MutableExecutablePlan, MutableQueryPlan,
11    MutableSourcePlan, QueryChildSlot, SourceChildSlot,
12};
13use crate::{
14    plan::{CommandPlan, CtePlan, RelationalPlan, SourcePlan},
15    SQLError,
16};
17use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
18
19pub trait OwnedScopedPlanVisitor {
20    fn command(
21        &mut self,
22        command: MutableCommandPlan,
23        _outer: &dyn Fn(&str) -> bool,
24    ) -> Result<(MutableCommandPlan, bool), SQLError> {
25        Ok((command, true))
26    }
27    fn source(
28        &mut self,
29        source: MutableSourcePlan,
30        _visible: &dyn Fn(&str) -> bool,
31    ) -> Result<(MutableSourcePlan, bool), SQLError> {
32        Ok((source, true))
33    }
34}
35
36impl MutableExecutablePlan {
37    pub fn visit_scoped(
38        self,
39        control: &ProductionControl<'_>,
40        visitor: &mut dyn OwnedScopedPlanVisitor,
41    ) -> Result<Self, SQLError> {
42        plan(self, &|_| false, visitor, control)
43    }
44}
45
46fn names(
47    ctes: &[CtePlan],
48    control: &ProductionControl<'_>,
49) -> Result<Produced<Vec<String>>, SQLError> {
50    let mut names = ProductionVec::new(*control);
51    for cte in ctes {
52        names.push_produced(control.copy_text(&cte.name)?)?;
53    }
54    Ok(names.finish()?)
55}
56fn plan(
57    input: MutableExecutablePlan,
58    outer: &dyn Fn(&str) -> bool,
59    visitor: &mut dyn OwnedScopedPlanVisitor,
60    control: &ProductionControl<'_>,
61) -> Result<MutableExecutablePlan, SQLError> {
62    control.check()?;
63    Ok(match input {
64        MutableExecutablePlan::Query(input) => {
65            MutableExecutablePlan::Query(query(input, outer, visitor, control)?)
66        }
67        MutableExecutablePlan::Command(input) => {
68            MutableExecutablePlan::Command(command(input, outer, visitor, control)?)
69        }
70    })
71}
72fn query(
73    mut input: MutableQueryPlan,
74    outer: &dyn Fn(&str) -> bool,
75    visitor: &mut dyn OwnedScopedPlanVisitor,
76    control: &ProductionControl<'_>,
77) -> Result<MutableQueryPlan, SQLError> {
78    control.check()?;
79    let names = names(&input.ctes, control)?;
80    let recursive = input.ctes.iter().any(|cte| cte.recursive);
81    for index in 0..names.len() {
82        let visible = |name: &str| {
83            names[..if recursive { names.len() } else { index }]
84                .iter()
85                .any(|candidate| candidate == name)
86                || outer(name)
87        };
88        input = input.map_cte(index, control, |body| {
89            plan(body, &visible, visitor, control)
90        })?;
91    }
92    let visible = |name: &str| names.iter().any(|candidate| candidate == name) || outer(name);
93    match &input.root {
94        RelationalPlan::QueryBlock(_) => {
95            input = input.map_source(control, |input| source(input, &visible, visitor, control))?;
96        }
97        RelationalPlan::SetOp { .. } => {
98            input = input.map_query_child(QueryChildSlot::Left, control, |input| {
99                query(input, &visible, visitor, control)
100            })?;
101            input = input.map_query_child(QueryChildSlot::Right, control, |input| {
102                query(input, &visible, visitor, control)
103            })?;
104        }
105        RelationalPlan::Values { .. } => {}
106    }
107    let count = match &input.root {
108        RelationalPlan::QueryBlock(block) => block.subqueries.len(),
109        RelationalPlan::SetOp { subqueries, .. } | RelationalPlan::Values { subqueries, .. } => {
110            subqueries.len()
111        }
112    };
113    for index in 0..count {
114        input = input.map_query_child(QueryChildSlot::Subquery(index), control, |input| {
115            query(input, &visible, visitor, control)
116        })?;
117    }
118    Ok(input)
119}
120fn source(
121    input: MutableSourcePlan,
122    visible: &dyn Fn(&str) -> bool,
123    visitor: &mut dyn OwnedScopedPlanVisitor,
124    control: &ProductionControl<'_>,
125) -> Result<MutableSourcePlan, SQLError> {
126    control.check()?;
127    let (mut input, descend) = visitor.source(input, visible)?;
128    if !descend {
129        return Ok(input);
130    }
131    match &*input {
132        SourcePlan::Subquery { .. } => {
133            input.map_query(control, |input| query(input, visible, visitor, control))
134        }
135        SourcePlan::Table {
136            name,
137            executable_query: Some(_),
138            ..
139        } => {
140            let cte = match uqa_core::RelationIdentity::borrowed_reference(name)
141                .filter(|reference| reference.schema.is_none())
142            {
143                Some(reference) => visible(&control.format(format_args!("{}", reference.name))?),
144                None => false,
145            };
146            input.map_query(control, |input| {
147                query(
148                    input,
149                    if cte { visible } else { &|_| false },
150                    visitor,
151                    control,
152                )
153            })
154        }
155        SourcePlan::Join { .. } => {
156            input = input.map_child(SourceChildSlot::Left, control, |input| {
157                source(input, visible, visitor, control)
158            })?;
159            input.map_child(SourceChildSlot::Right, control, |input| {
160                source(input, visible, visitor, control)
161            })
162        }
163        _ => Ok(input),
164    }
165}
166fn command(
167    input: MutableCommandPlan,
168    outer: &dyn Fn(&str) -> bool,
169    visitor: &mut dyn OwnedScopedPlanVisitor,
170    control: &ProductionControl<'_>,
171) -> Result<MutableCommandPlan, SQLError> {
172    control.check()?;
173    let (mut input, descend) = visitor.command(input, outer)?;
174    if !descend {
175        return Ok(input);
176    }
177    match &*input {
178        CommandPlan::CreateView { .. }
179        | CommandPlan::CreateTableAs { .. }
180        | CommandPlan::CreateMaterializedView { .. }
181        | CommandPlan::DeclareCursor { .. } => {
182            return input.map_query_body(control, |input| query(input, outer, visitor, control))
183        }
184        CommandPlan::Explain { .. } | CommandPlan::Prepare { .. } => {
185            return input.map_executable_body(control, |input| plan(input, outer, visitor, control))
186        }
187        CommandPlan::Call { args, .. } => {
188            let count = args.len();
189            for argument in 0..count {
190                let CommandPlan::Call { args, .. } = &*input else {
191                    unreachable!("retained CALL")
192                };
193                for index in 0..args[argument].subqueries.len() {
194                    input = input.map_query_child(
195                        CommandQuerySlot::CallArgumentSubquery {
196                            argument,
197                            query: index,
198                        },
199                        control,
200                        |input| query(input, outer, visitor, control),
201                    )?;
202                }
203            }
204            return Ok(input);
205        }
206        CommandPlan::Execute { params, .. } => {
207            let count = params.len();
208            for parameter in 0..count {
209                let CommandPlan::Execute { params, .. } = &*input else {
210                    unreachable!("retained EXECUTE")
211                };
212                for index in 0..params[parameter].subqueries.len() {
213                    input = input.map_query_child(
214                        CommandQuerySlot::ExecuteParameterSubquery {
215                            parameter,
216                            query: index,
217                        },
218                        control,
219                        |input| query(input, outer, visitor, control),
220                    )?;
221                }
222            }
223            return Ok(input);
224        }
225        CommandPlan::Insert(_)
226        | CommandPlan::Update(_)
227        | CommandPlan::Delete(_)
228        | CommandPlan::Merge(_) => {}
229        _ => return Ok(input),
230    }
231    let names = names(input.ctes(), control)?;
232    let recursive = input.ctes().iter().any(|cte| cte.recursive);
233    for index in 0..names.len() {
234        let visible = |name: &str| {
235            names[..if recursive { names.len() } else { index }]
236                .iter()
237                .any(|candidate| candidate == name)
238                || outer(name)
239        };
240        input = input.map_cte(index, control, |body| {
241            plan(body, &visible, visitor, control)
242        })?;
243    }
244    let visible = |name: &str| names.iter().any(|candidate| candidate == name) || outer(name);
245    input = input.map_source(control, |input| source(input, &visible, visitor, control))?;
246    if matches!(&*input,CommandPlan::Insert(insert) if insert.source.is_some()) {
247        input = input.map_query_child(CommandQuerySlot::InsertSource, control, |input| {
248            query(input, &visible, visitor, control)
249        })?;
250    }
251    let count = input.scalar_subqueries().len();
252    for index in 0..count {
253        input = input.map_query_child(CommandQuerySlot::Subquery(index), control, |input| {
254            query(input, &visible, visitor, control)
255        })?;
256    }
257    Ok(input)
258}