Skip to main content

uqa_sql/plan/mutable/
nodes.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar-root traversal keeps each syntax node beside its constructor owner during edits.
8
9use super::{
10    memory::RewriteMemory, sources::query_source_memory, MutableQueryPlan, OwnedScalarExpr,
11    QueryScalarSlot, RelationalPlan, SourceChildSlot, SourceScalarSlot,
12};
13use crate::{
14    plan::{QueryPlan, SourcePlan},
15    SQLError, ScalarExpr,
16};
17use uqa_core::memory::ProductionControl;
18
19pub(super) mod transformation;
20pub(super) use transformation::{transform_ctes, transform_query, transform_source};
21
22pub(in crate::plan::mutable) fn transform_local_source(
23    source: &mut SourcePlan,
24    memory: Option<&mut RewriteMemory>,
25    control: &ProductionControl<'_>,
26    transform: &mut crate::plan::ScalarNodeTransform<'_>,
27) -> Result<(), SQLError> {
28    local_source(
29        source,
30        memory,
31        control,
32        &mut |expression, memory, control| {
33            OwnedScalarExpr::transform_nodes_in_place(expression, memory, control, transform)
34        },
35    )
36}
37
38type Replacement<'a> = dyn FnMut(&ScalarExpr) -> Result<Option<OwnedScalarExpr>, SQLError> + 'a;
39pub(super) type ScalarMemory = super::super::scalar::ScalarMemory;
40pub(super) type Action<'a> = dyn FnMut(
41        &mut ScalarExpr,
42        Option<&mut ScalarMemory>,
43        &ProductionControl<'_>,
44    ) -> Result<(), SQLError>
45    + 'a;
46
47impl MutableQueryPlan {
48    /// Rewrite local scalar nodes in source-first order without moving their original addresses. The observer receives read-only syntax and returns an independently owned replacement; nested queries retain separate traversal boundaries.
49    pub fn rewrite_root_scalar_nodes(
50        mut self,
51        control: &ProductionControl<'_>,
52        replacement: &mut Replacement<'_>,
53    ) -> Result<Self, SQLError> {
54        self.assert_owner(control);
55        control.check()?;
56        let mut action = |expression: &mut ScalarExpr,
57                          memory: Option<&mut ScalarMemory>,
58                          control: &ProductionControl<'_>| {
59            OwnedScalarExpr::replace_nodes_in_place(expression, memory, control, replacement)
60        };
61        if let RelationalPlan::QueryBlock(block) = &mut self.query.root {
62            if let Some(source) = &mut block.from {
63                let memory = self
64                    .memory
65                    .as_mut()
66                    .map(|memory| query_source_memory(memory).as_mut().expect("source owner"));
67                local_source(source, memory, control, &mut action)?;
68            }
69        }
70        query_scalars(
71            &mut self.query,
72            self.memory.as_mut(),
73            false,
74            control,
75            &mut action,
76        )?;
77        Ok(self)
78    }
79}
80
81pub(super) fn query_scalars(
82    query: &mut QueryPlan,
83    mut memory: Option<&mut RewriteMemory>,
84    where_first: bool,
85    control: &ProductionControl<'_>,
86    action: &mut Action<'_>,
87) -> Result<(), SQLError> {
88    match &query.root {
89        RelationalPlan::QueryBlock(_) => {
90            query_block_scalars(query, memory, where_first, control, action)?;
91        }
92        RelationalPlan::SetOp { order_by, .. } => {
93            let count = order_by.len();
94            query_slots(
95                query,
96                memory.as_deref_mut(),
97                (0..count).map(QueryScalarSlot::OrderBy),
98                control,
99                action,
100            )?;
101            query_slots(
102                query,
103                memory,
104                [QueryScalarSlot::Limit, QueryScalarSlot::Offset],
105                control,
106                action,
107            )?;
108        }
109        RelationalPlan::Values { rows, .. } => {
110            for row in 0..rows.len() {
111                let RelationalPlan::Values { rows, .. } = &query.root else {
112                    unreachable!()
113                };
114                let count = rows[row].len();
115                query_slots(
116                    query,
117                    memory.as_deref_mut(),
118                    (0..count).map(|column| QueryScalarSlot::Value { row, column }),
119                    control,
120                    action,
121                )?;
122            }
123        }
124    }
125    Ok(())
126}
127
128fn query_block_scalars(
129    query: &mut QueryPlan,
130    mut memory: Option<&mut RewriteMemory>,
131    where_first: bool,
132    control: &ProductionControl<'_>,
133    action: &mut Action<'_>,
134) -> Result<(), SQLError> {
135    let RelationalPlan::QueryBlock(block) = &query.root else {
136        unreachable!("query block scalar scope");
137    };
138    let (projections, groups, sets, orders, distinct, windows) = (
139        block.projections.len(),
140        block.group_by.len(),
141        block.grouping_sets.len(),
142        block.order_by.len(),
143        block.distinct_on.len(),
144        block.windows.len(),
145    );
146    if where_first {
147        query_slot(
148            query,
149            memory.as_deref_mut(),
150            QueryScalarSlot::Where,
151            control,
152            action,
153        )?;
154    }
155    query_slots(
156        query,
157        memory.as_deref_mut(),
158        (0..projections).map(QueryScalarSlot::Projection),
159        control,
160        action,
161    )?;
162    if !where_first {
163        query_slot(
164            query,
165            memory.as_deref_mut(),
166            QueryScalarSlot::Where,
167            control,
168            action,
169        )?;
170    }
171    query_slots(
172        query,
173        memory.as_deref_mut(),
174        (0..groups).map(QueryScalarSlot::GroupBy),
175        control,
176        action,
177    )?;
178    for set in 0..sets {
179        let RelationalPlan::QueryBlock(block) = &query.root else {
180            unreachable!();
181        };
182        let count = block.grouping_sets[set].len();
183        query_slots(
184            query,
185            memory.as_deref_mut(),
186            (0..count).map(|expression| QueryScalarSlot::GroupingSet { set, expression }),
187            control,
188            action,
189        )?;
190    }
191    query_slot(
192        query,
193        memory.as_deref_mut(),
194        QueryScalarSlot::Having,
195        control,
196        action,
197    )?;
198    query_slots(
199        query,
200        memory.as_deref_mut(),
201        (0..orders).map(QueryScalarSlot::OrderBy),
202        control,
203        action,
204    )?;
205    query_slots(
206        query,
207        memory.as_deref_mut(),
208        [QueryScalarSlot::Limit, QueryScalarSlot::Offset],
209        control,
210        action,
211    )?;
212    query_slots(
213        query,
214        memory.as_deref_mut(),
215        (0..distinct).map(QueryScalarSlot::DistinctOn),
216        control,
217        action,
218    )?;
219    for window in 0..windows {
220        query_window_scalars(query, memory.as_deref_mut(), window, control, action)?;
221    }
222    Ok(())
223}
224
225fn query_window_scalars(
226    query: &mut QueryPlan,
227    mut memory: Option<&mut RewriteMemory>,
228    window: usize,
229    control: &ProductionControl<'_>,
230    action: &mut Action<'_>,
231) -> Result<(), SQLError> {
232    let RelationalPlan::QueryBlock(block) = &query.root else {
233        unreachable!("query window scalar scope");
234    };
235    let (partitions, orders) = (
236        block.windows[window].spec.partition_by.len(),
237        block.windows[window].spec.order_by.len(),
238    );
239    query_slots(
240        query,
241        memory.as_deref_mut(),
242        (0..partitions).map(|expression| QueryScalarSlot::WindowPartition { window, expression }),
243        control,
244        action,
245    )?;
246    query_slots(
247        query,
248        memory.as_deref_mut(),
249        (0..orders).map(|expression| QueryScalarSlot::WindowOrder { window, expression }),
250        control,
251        action,
252    )?;
253    query_slots(
254        query,
255        memory,
256        [
257            QueryScalarSlot::WindowFrameStart(window),
258            QueryScalarSlot::WindowFrameEnd(window),
259        ],
260        control,
261        action,
262    )
263}
264
265fn query_slots(
266    query: &mut QueryPlan,
267    mut memory: Option<&mut RewriteMemory>,
268    slots: impl IntoIterator<Item = QueryScalarSlot>,
269    control: &ProductionControl<'_>,
270    action: &mut Action<'_>,
271) -> Result<(), SQLError> {
272    for slot in slots {
273        query_slot(query, memory.as_deref_mut(), slot, control, action)?;
274    }
275    Ok(())
276}
277
278fn query_slot(
279    query: &mut QueryPlan,
280    memory: Option<&mut RewriteMemory>,
281    slot: QueryScalarSlot,
282    control: &ProductionControl<'_>,
283    action: &mut Action<'_>,
284) -> Result<(), SQLError> {
285    let Some(expression) = slot.expression_mut(query) else {
286        return Ok(());
287    };
288    let memory = memory.map(|memory| scalar_memory(slot.memory_mut(memory)));
289    action(expression, memory, control)
290}
291
292pub(super) fn scalar_memory(memory: &mut Option<ScalarMemory>) -> &mut ScalarMemory {
293    memory.as_mut().expect("scalar owner")
294}
295
296pub(super) fn local_source(
297    source: &mut SourcePlan,
298    mut memory: Option<&mut RewriteMemory>,
299    control: &ProductionControl<'_>,
300    action: &mut Action<'_>,
301) -> Result<(), SQLError> {
302    control.check()?;
303    if let SourcePlan::Join { left, right, .. } = source {
304        local_source(
305            left,
306            memory.as_mut().map(|memory| {
307                SourceChildSlot::Left
308                    .memory_mut(memory)
309                    .as_mut()
310                    .expect("left source")
311            }),
312            control,
313            action,
314        )?;
315        local_source(
316            right,
317            memory.as_mut().map(|memory| {
318                SourceChildSlot::Right
319                    .memory_mut(memory)
320                    .as_mut()
321                    .expect("right source")
322            }),
323            control,
324            action,
325        )?;
326    }
327    source_scalars(source, memory, control, action)
328}
329
330pub(super) fn source_scalars(
331    source: &mut SourcePlan,
332    mut memory: Option<&mut RewriteMemory>,
333    control: &ProductionControl<'_>,
334    action: &mut Action<'_>,
335) -> Result<(), SQLError> {
336    match source {
337        SourcePlan::Join { .. } => {
338            source_slot(source, memory, SourceScalarSlot::JoinOn, control, action)?;
339        }
340        SourcePlan::Values { rows, .. } => {
341            for row in 0..rows.len() {
342                let SourcePlan::Values { rows, .. } = source else {
343                    unreachable!()
344                };
345                for column in 0..rows[row].len() {
346                    source_slot(
347                        source,
348                        memory.as_deref_mut(),
349                        SourceScalarSlot::Value { row, column },
350                        control,
351                        action,
352                    )?;
353                }
354            }
355        }
356        SourcePlan::Function { args, .. } => {
357            for index in 0..args.len() {
358                source_slot(
359                    source,
360                    memory.as_deref_mut(),
361                    SourceScalarSlot::Argument(index),
362                    control,
363                    action,
364                )?;
365            }
366        }
367        SourcePlan::FunctionGroup { functions, .. } => {
368            for function in 0..functions.len() {
369                let SourcePlan::FunctionGroup { functions, .. } = source else {
370                    unreachable!()
371                };
372                for argument in 0..functions[function].args.len() {
373                    source_slot(
374                        source,
375                        memory.as_deref_mut(),
376                        SourceScalarSlot::GroupArgument { function, argument },
377                        control,
378                        action,
379                    )?;
380                }
381            }
382        }
383        SourcePlan::RetainedRows(_) | SourcePlan::Subquery { .. } | SourcePlan::Table { .. } => {}
384    }
385    Ok(())
386}
387
388fn source_slot(
389    source: &mut SourcePlan,
390    memory: Option<&mut RewriteMemory>,
391    slot: SourceScalarSlot,
392    control: &ProductionControl<'_>,
393    action: &mut Action<'_>,
394) -> Result<(), SQLError> {
395    let Some(expression) = slot.expression_mut(source) else {
396        return Ok(());
397    };
398    let memory = memory.map(|memory| scalar_memory(slot.memory_mut(memory)));
399    action(expression, memory, control)
400}