Skip to main content

uqa_sql/plan/mutable/commands/
transformation.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Command scalar transformation retains original analysis addresses and transfers each constructor's independent owner.
8
9use super::super::nodes::{scalar_memory, transform_ctes, transform_query, transform_source};
10use super::{CommandPlan, MutableCommandPlan, RewriteMemory, SQLError};
11use crate::plan::ScalarNodeTransform;
12use crate::{
13    ast::{AssignmentStep, AssignmentTarget, AssignmentTargets},
14    plan::{
15        AssignmentPlan, ConflictActionPlan, ExpressionPlan, MergeWhenPlan, MutableExecutablePlan,
16        OwnedScalarExpr, ProjectionPlan, QueryPlan, UnifiedPlan, ViewCheckPlan,
17    },
18    ScalarExpr,
19};
20use uqa_core::memory::ProductionControl;
21
22impl MutableExecutablePlan {
23    /// Transform scalar nodes at their original analysis identities, with children before parents and the same query/command order as immutable plan inspection.
24    pub fn transform_scalar_nodes(
25        self,
26        control: &ProductionControl<'_>,
27        transform: &mut ScalarNodeTransform<'_>,
28    ) -> Result<Self, SQLError> {
29        let mut plan = self;
30        plan.transform_scalar_nodes_in_place(control, transform)?;
31        Ok(plan)
32    }
33}
34
35impl MutableExecutablePlan {
36    /// Complete identity-indexed analysis before moving the inline query or command root.
37    pub(crate) fn transform_scalar_nodes_in_place(
38        &mut self,
39        control: &ProductionControl<'_>,
40        transform: &mut ScalarNodeTransform<'_>,
41    ) -> Result<(), SQLError> {
42        match self {
43            Self::Query(query) => {
44                query.assert_owner(control);
45                super::super::nodes::transform_query(
46                    &mut query.query,
47                    query.memory.as_mut(),
48                    control,
49                    transform,
50                )
51            }
52            Self::Command(command) => {
53                command.assert_owner(control);
54                transform_command(
55                    &mut command.command,
56                    command.memory.as_mut(),
57                    control,
58                    transform,
59                )
60            }
61        }
62    }
63}
64
65impl MutableCommandPlan {
66    pub fn transform_scalar_nodes(
67        mut self,
68        control: &ProductionControl<'_>,
69        transform: &mut ScalarNodeTransform<'_>,
70    ) -> Result<Self, SQLError> {
71        self.assert_owner(control);
72        transform_command(&mut self.command, self.memory.as_mut(), control, transform)?;
73        Ok(self)
74    }
75}
76
77fn field<'a>(memory: Option<&'a mut RewriteMemory>, name: &str) -> Option<&'a mut RewriteMemory> {
78    memory.map(|memory| {
79        memory
80            .field_mut(name)
81            .as_mut()
82            .expect("command constructor field")
83    })
84}
85
86fn item(memory: Option<&mut RewriteMemory>, index: usize) -> Option<&mut RewriteMemory> {
87    memory.map(|memory| {
88        memory
89            .item_mut(index)
90            .as_mut()
91            .expect("command constructor item")
92    })
93}
94
95fn scalar(
96    expression: &mut ScalarExpr,
97    memory: Option<&mut RewriteMemory>,
98    control: &ProductionControl<'_>,
99    transform: &mut ScalarNodeTransform<'_>,
100) -> Result<(), SQLError> {
101    let memory = memory.map(|memory| scalar_memory(memory.scalar_mut()));
102    OwnedScalarExpr::transform_nodes_in_place(expression, memory, control, transform)
103}
104
105fn optional(
106    expression: Option<&mut ScalarExpr>,
107    memory: Option<&mut RewriteMemory>,
108    control: &ProductionControl<'_>,
109    transform: &mut ScalarNodeTransform<'_>,
110) -> Result<(), SQLError> {
111    if let Some(expression) = expression {
112        scalar(expression, memory, control, transform)?;
113    }
114    Ok(())
115}
116
117fn projections(
118    values: &mut [ProjectionPlan],
119    mut memory: Option<&mut RewriteMemory>,
120    control: &ProductionControl<'_>,
121    transform: &mut ScalarNodeTransform<'_>,
122) -> Result<(), SQLError> {
123    for (index, value) in values.iter_mut().enumerate() {
124        scalar(
125            &mut value.expr,
126            item(memory.as_deref_mut(), index),
127            control,
128            transform,
129        )?;
130    }
131    Ok(())
132}
133
134fn queries(
135    values: &mut [QueryPlan],
136    mut memory: Option<&mut RewriteMemory>,
137    control: &ProductionControl<'_>,
138    transform: &mut ScalarNodeTransform<'_>,
139) -> Result<(), SQLError> {
140    for (index, value) in values.iter_mut().enumerate() {
141        transform_query(
142            value,
143            field(item(memory.as_deref_mut(), index), "query"),
144            control,
145            transform,
146        )?;
147    }
148    Ok(())
149}
150
151fn checks(
152    values: &mut [ViewCheckPlan],
153    mut memory: Option<&mut RewriteMemory>,
154    control: &ProductionControl<'_>,
155    transform: &mut ScalarNodeTransform<'_>,
156) -> Result<(), SQLError> {
157    for (index, value) in values.iter_mut().enumerate() {
158        scalar(
159            &mut value.predicate,
160            field(item(memory.as_deref_mut(), index), "predicate"),
161            control,
162            transform,
163        )?;
164    }
165    Ok(())
166}
167
168fn target(
169    value: &mut AssignmentTarget<ScalarExpr>,
170    mut memory: Option<&mut RewriteMemory>,
171    control: &ProductionControl<'_>,
172    transform: &mut ScalarNodeTransform<'_>,
173) -> Result<(), SQLError> {
174    for (index, step) in value.indirection.iter_mut().enumerate() {
175        let mut memory = item(field(memory.as_deref_mut(), "indirection"), index);
176        match step {
177            AssignmentStep::Field(_) => {}
178            AssignmentStep::Index(expression) => {
179                scalar(expression, field(memory, "index"), control, transform)?;
180            }
181            AssignmentStep::Slice { lower, upper } => {
182                optional(
183                    lower.as_deref_mut(),
184                    field(memory.as_deref_mut(), "lower"),
185                    control,
186                    transform,
187                )?;
188                optional(
189                    upper.as_deref_mut(),
190                    field(memory, "upper"),
191                    control,
192                    transform,
193                )?;
194            }
195        }
196    }
197    Ok(())
198}
199
200fn targets(
201    values: &mut [AssignmentTarget<ScalarExpr>],
202    mut memory: Option<&mut RewriteMemory>,
203    control: &ProductionControl<'_>,
204    transform: &mut ScalarNodeTransform<'_>,
205) -> Result<(), SQLError> {
206    for (index, value) in values.iter_mut().enumerate() {
207        target(
208            value,
209            item(memory.as_deref_mut(), index),
210            control,
211            transform,
212        )?;
213    }
214    Ok(())
215}
216
217fn assignments(
218    values: &mut [AssignmentPlan],
219    mut memory: Option<&mut RewriteMemory>,
220    control: &ProductionControl<'_>,
221    transform: &mut ScalarNodeTransform<'_>,
222) -> Result<(), SQLError> {
223    for (index, value) in values.iter_mut().enumerate() {
224        let mut memory = item(memory.as_deref_mut(), index);
225        let target_memory = field(memory.as_deref_mut(), "target");
226        match &mut value.target {
227            AssignmentTargets::Single(value) => target(value, target_memory, control, transform)?,
228            AssignmentTargets::Multiple(group) => targets(
229                &mut group.targets,
230                field(target_memory, "targets"),
231                control,
232                transform,
233            )?,
234        }
235        scalar(&mut value.value, field(memory, "value"), control, transform)?;
236    }
237    Ok(())
238}
239
240fn expressions(
241    values: &mut [ExpressionPlan],
242    mut memory: Option<&mut RewriteMemory>,
243    control: &ProductionControl<'_>,
244    transform: &mut ScalarNodeTransform<'_>,
245) -> Result<(), SQLError> {
246    for (index, value) in values.iter_mut().enumerate() {
247        let mut memory = item(memory.as_deref_mut(), index);
248        scalar(&mut value.scalar, memory.as_deref_mut(), control, transform)?;
249        queries(
250            &mut value.subqueries,
251            field(memory, "subqueries"),
252            control,
253            transform,
254        )?;
255    }
256    Ok(())
257}
258
259fn executable(
260    value: &mut UnifiedPlan,
261    memory: Option<&mut RewriteMemory>,
262    control: &ProductionControl<'_>,
263    transform: &mut ScalarNodeTransform<'_>,
264) -> Result<(), SQLError> {
265    match value {
266        UnifiedPlan::Query(query) => {
267            transform_query(query, field(memory, "query"), control, transform)
268        }
269        UnifiedPlan::Command(command) => {
270            transform_command(command, field(memory, "command"), control, transform)
271        }
272    }
273}
274
275pub(in crate::plan::mutable) fn transform_command(
276    command: &mut CommandPlan,
277    memory: Option<&mut RewriteMemory>,
278    control: &ProductionControl<'_>,
279    transform: &mut ScalarNodeTransform<'_>,
280) -> Result<(), SQLError> {
281    transform_command_scope(command, memory, control, transform, true)
282}
283
284/// The caller owns nested arenas and local source ordering; visit only this command's direct mutation roots.
285pub(in crate::plan::mutable) fn transform_local_command(
286    command: &mut CommandPlan,
287    memory: Option<&mut RewriteMemory>,
288    control: &ProductionControl<'_>,
289    transform: &mut ScalarNodeTransform<'_>,
290) -> Result<(), SQLError> {
291    transform_command_scope(command, memory, control, transform, false)
292}
293
294fn cte_children(
295    values: &mut [crate::plan::CtePlan],
296    memory: Option<&mut RewriteMemory>,
297    control: &ProductionControl<'_>,
298    transform: &mut ScalarNodeTransform<'_>,
299    recursive: bool,
300) -> Result<(), SQLError> {
301    if recursive {
302        transform_ctes(values, memory, control, transform)?;
303    }
304    Ok(())
305}
306
307fn query_children(
308    values: &mut [QueryPlan],
309    memory: Option<&mut RewriteMemory>,
310    control: &ProductionControl<'_>,
311    transform: &mut ScalarNodeTransform<'_>,
312    recursive: bool,
313) -> Result<(), SQLError> {
314    if recursive {
315        queries(values, field(memory, "subqueries"), control, transform)?;
316    }
317    Ok(())
318}
319
320fn query_child(
321    value: &mut QueryPlan,
322    memory: Option<&mut RewriteMemory>,
323    control: &ProductionControl<'_>,
324    transform: &mut ScalarNodeTransform<'_>,
325    recursive: bool,
326) -> Result<(), SQLError> {
327    if recursive {
328        transform_query(value, memory, control, transform)?;
329    }
330    Ok(())
331}
332
333fn source_scope(
334    value: &mut crate::plan::SourcePlan,
335    memory: Option<&mut RewriteMemory>,
336    control: &ProductionControl<'_>,
337    transform: &mut ScalarNodeTransform<'_>,
338    recursive: bool,
339) -> Result<(), SQLError> {
340    if recursive {
341        transform_source(value, memory, control, transform)
342    } else {
343        Ok(())
344    }
345}
346
347#[expect(
348    clippy::too_many_lines,
349    reason = "one exhaustive command dispatch preserves analysis rewrite order and utility exclusions"
350)]
351fn transform_command_scope(
352    command: &mut CommandPlan,
353    memory: Option<&mut RewriteMemory>,
354    control: &ProductionControl<'_>,
355    transform: &mut ScalarNodeTransform<'_>,
356    recursive: bool,
357) -> Result<(), SQLError> {
358    control.check()?;
359    if !recursive
360        && !matches!(
361            command,
362            CommandPlan::Insert(_)
363                | CommandPlan::Update(_)
364                | CommandPlan::Delete(_)
365                | CommandPlan::Merge(_)
366        )
367    {
368        return Ok(());
369    }
370    match command {
371        CommandPlan::Insert(plan) => {
372            let mut memory = field(memory, "value0");
373            targets(
374                &mut plan.columns,
375                field(memory.as_deref_mut(), "columns"),
376                control,
377                transform,
378            )?;
379            cte_children(
380                &mut plan.ctes,
381                field(memory.as_deref_mut(), "ctes"),
382                control,
383                transform,
384                recursive,
385            )?;
386            for (row, values) in plan.rows.iter_mut().enumerate() {
387                for (column, value) in values.iter_mut().enumerate() {
388                    let memory = item(field(memory.as_deref_mut(), "rows"), row)
389                        .map(|memory| scalar_memory(memory.scalar_item_mut(column)));
390                    OwnedScalarExpr::transform_nodes_in_place(value, memory, control, transform)?;
391                }
392            }
393            if let Some(source) = &mut plan.source {
394                query_child(
395                    source,
396                    field(field(memory.as_deref_mut(), "source"), "query"),
397                    control,
398                    transform,
399                    recursive,
400                )?;
401            }
402            if let Some(conflict) = &mut plan.on_conflict {
403                let mut conflict_memory = field(memory.as_deref_mut(), "on_conflict");
404                for (index, expression) in conflict.expressions.iter_mut().enumerate() {
405                    scalar(
406                        expression,
407                        item(field(conflict_memory.as_deref_mut(), "expressions"), index),
408                        control,
409                        transform,
410                    )?;
411                }
412                optional(
413                    conflict.predicate.as_deref_mut(),
414                    field(conflict_memory.as_deref_mut(), "predicate"),
415                    control,
416                    transform,
417                )?;
418                if let ConflictActionPlan::Update {
419                    assignments: values,
420                    predicate,
421                } = &mut conflict.action
422                {
423                    let mut action_memory = field(conflict_memory, "action");
424                    assignments(
425                        values,
426                        field(action_memory.as_deref_mut(), "assignments"),
427                        control,
428                        transform,
429                    )?;
430                    optional(
431                        predicate.as_deref_mut(),
432                        field(action_memory, "predicate"),
433                        control,
434                        transform,
435                    )?;
436                }
437            }
438            projections(
439                &mut plan.returning,
440                field(memory.as_deref_mut(), "returning"),
441                control,
442                transform,
443            )?;
444            checks(
445                &mut plan.view_checks,
446                field(memory.as_deref_mut(), "view_checks"),
447                control,
448                transform,
449            )?;
450            query_children(&mut plan.subqueries, memory, control, transform, recursive)?;
451        }
452        CommandPlan::Update(plan) => {
453            let mut memory = field(memory, "value0");
454            cte_children(
455                &mut plan.ctes,
456                field(memory.as_deref_mut(), "ctes"),
457                control,
458                transform,
459                recursive,
460            )?;
461            if let Some(source) = &mut plan.source {
462                source_scope(
463                    source,
464                    field(field(memory.as_deref_mut(), "source"), "source"),
465                    control,
466                    transform,
467                    recursive,
468                )?;
469            }
470            assignments(
471                &mut plan.assignments,
472                field(memory.as_deref_mut(), "assignments"),
473                control,
474                transform,
475            )?;
476            optional(
477                plan.predicate.as_mut(),
478                field(memory.as_deref_mut(), "predicate"),
479                control,
480                transform,
481            )?;
482            projections(
483                &mut plan.returning,
484                field(memory.as_deref_mut(), "returning"),
485                control,
486                transform,
487            )?;
488            checks(
489                &mut plan.view_checks,
490                field(memory.as_deref_mut(), "view_checks"),
491                control,
492                transform,
493            )?;
494            query_children(&mut plan.subqueries, memory, control, transform, recursive)?;
495        }
496        CommandPlan::Delete(plan) => {
497            let mut memory = field(memory, "value0");
498            cte_children(
499                &mut plan.ctes,
500                field(memory.as_deref_mut(), "ctes"),
501                control,
502                transform,
503                recursive,
504            )?;
505            if let Some(source) = &mut plan.source {
506                source_scope(
507                    source,
508                    field(field(memory.as_deref_mut(), "source"), "source"),
509                    control,
510                    transform,
511                    recursive,
512                )?;
513            }
514            optional(
515                plan.predicate.as_mut(),
516                field(memory.as_deref_mut(), "predicate"),
517                control,
518                transform,
519            )?;
520            projections(
521                &mut plan.returning,
522                field(memory.as_deref_mut(), "returning"),
523                control,
524                transform,
525            )?;
526            query_children(&mut plan.subqueries, memory, control, transform, recursive)?;
527        }
528        CommandPlan::Merge(plan) => {
529            let mut memory = field(memory, "value0");
530            cte_children(
531                &mut plan.ctes,
532                field(memory.as_deref_mut(), "ctes"),
533                control,
534                transform,
535                recursive,
536            )?;
537            source_scope(
538                &mut plan.source,
539                field(field(memory.as_deref_mut(), "source"), "source"),
540                control,
541                transform,
542                recursive,
543            )?;
544            optional(
545                plan.target_predicate.as_mut(),
546                field(memory.as_deref_mut(), "target_predicate"),
547                control,
548                transform,
549            )?;
550            scalar(
551                &mut plan.join_condition,
552                field(memory.as_deref_mut(), "join_condition"),
553                control,
554                transform,
555            )?;
556            for (index, clause) in plan.when_clauses.iter_mut().enumerate() {
557                let mut memory = item(field(memory.as_deref_mut(), "when_clauses"), index);
558                match clause {
559                    MergeWhenPlan::UpdateMatched {
560                        condition,
561                        assignments: values,
562                    }
563                    | MergeWhenPlan::UpdateNotMatchedBySource {
564                        condition,
565                        assignments: values,
566                    } => {
567                        optional(
568                            condition.as_mut(),
569                            field(memory.as_deref_mut(), "condition"),
570                            control,
571                            transform,
572                        )?;
573                        assignments(values, field(memory, "assignments"), control, transform)?;
574                    }
575                    MergeWhenPlan::InsertNotMatched {
576                        condition,
577                        columns,
578                        values,
579                        ..
580                    } => {
581                        optional(
582                            condition.as_mut(),
583                            field(memory.as_deref_mut(), "condition"),
584                            control,
585                            transform,
586                        )?;
587                        targets(
588                            columns,
589                            field(memory.as_deref_mut(), "columns"),
590                            control,
591                            transform,
592                        )?;
593                        for (index, value) in values.iter_mut().enumerate() {
594                            scalar(
595                                value,
596                                item(field(memory.as_deref_mut(), "values"), index),
597                                control,
598                                transform,
599                            )?;
600                        }
601                    }
602                    MergeWhenPlan::DeleteMatched { condition }
603                    | MergeWhenPlan::DeleteNotMatchedBySource { condition }
604                    | MergeWhenPlan::NothingMatched { condition }
605                    | MergeWhenPlan::NothingNotMatched { condition }
606                    | MergeWhenPlan::NothingNotMatchedBySource { condition } => optional(
607                        condition.as_mut(),
608                        field(memory, "condition"),
609                        control,
610                        transform,
611                    )?,
612                }
613            }
614            projections(
615                &mut plan.returning,
616                field(memory.as_deref_mut(), "returning"),
617                control,
618                transform,
619            )?;
620            checks(
621                &mut plan.view_checks,
622                field(memory.as_deref_mut(), "view_checks"),
623                control,
624                transform,
625            )?;
626            query_children(&mut plan.subqueries, memory, control, transform, recursive)?;
627        }
628        CommandPlan::CreateView { query, .. }
629        | CommandPlan::CreateMaterializedView { query, .. }
630        | CommandPlan::CreateTableAs { query, .. }
631        | CommandPlan::DeclareCursor { query, .. } => query_child(
632            query,
633            field(field(memory, "query"), "query"),
634            control,
635            transform,
636            recursive,
637        )?,
638        CommandPlan::Explain { body, .. } | CommandPlan::Prepare { body, .. } => {
639            executable(body, field(memory, "body"), control, transform)?;
640        }
641        CommandPlan::Execute { params, .. } => {
642            expressions(params, field(memory, "params"), control, transform)?;
643        }
644        CommandPlan::Call { args, .. } => {
645            expressions(args, field(memory, "args"), control, transform)?;
646        }
647        CommandPlan::CreateTable(_)
648        | CommandPlan::CreateTableIfNotExists(_)
649        | CommandPlan::CreateIndex(_)
650        | CommandPlan::RenameIndex(_)
651        | CommandPlan::Drop(_)
652        | CommandPlan::AlterTable(_)
653        | CommandPlan::AlterForeignTable(_)
654        | CommandPlan::AlterView(_)
655        | CommandPlan::RefreshMaterializedView { .. }
656        | CommandPlan::CreateSchema { .. }
657        | CommandPlan::AlterSchemaOwner { .. }
658        | CommandPlan::RenameSchema { .. }
659        | CommandPlan::Notify { .. }
660        | CommandPlan::Listen { .. }
661        | CommandPlan::Unlisten { .. }
662        | CommandPlan::SetVariable { .. }
663        | CommandPlan::ResetVariable { .. }
664        | CommandPlan::ResetAllVariables
665        | CommandPlan::SetConstraints { .. }
666        | CommandPlan::ShowVariable { .. }
667        | CommandPlan::Discard { .. }
668        | CommandPlan::Load { .. }
669        | CommandPlan::Analyze { .. }
670        | CommandPlan::Vacuum(_)
671        | CommandPlan::LockTable(_)
672        | CommandPlan::Truncate { .. }
673        | CommandPlan::Transaction(_)
674        | CommandPlan::FetchCursor(_)
675        | CommandPlan::CloseCursor { .. }
676        | CommandPlan::CreateSequence(_)
677        | CommandPlan::CreateDomain(_)
678        | CommandPlan::AlterDomain(_)
679        | CommandPlan::CommentType(_)
680        | CommandPlan::CreateShellType(_)
681        | CommandPlan::CreateEnum(_)
682        | CommandPlan::CreateCompositeType(_)
683        | CommandPlan::AlterEnum(_)
684        | CommandPlan::AlterTypeObject(_)
685        | CommandPlan::GrantType(_)
686        | CommandPlan::AlterSequence(_)
687        | CommandPlan::Deallocate { .. }
688        | CommandPlan::CreateForeignWrapper(_)
689        | CommandPlan::CreateForeignServer(_)
690        | CommandPlan::CreateForeignTable(_)
691        | CommandPlan::CreateForeignTableDefinition(_)
692        | CommandPlan::CreateFunction(_)
693        | CommandPlan::DropFunction(_)
694        | CommandPlan::AlterRoutine(_)
695        | CommandPlan::AlterRoutineOwner(_)
696        | CommandPlan::RenameRoutine(_)
697        | CommandPlan::GrantRoutine(_)
698        | CommandPlan::GrantTable(_)
699        | CommandPlan::GrantSequence(_)
700        | CommandPlan::GrantDatabase(_)
701        | CommandPlan::GrantSchema(_)
702        | CommandPlan::GrantRole(_)
703        | CommandPlan::CreateRole(_)
704        | CommandPlan::AlterRole(_)
705        | CommandPlan::RenameRole(_)
706        | CommandPlan::DropRole(_)
707        | CommandPlan::CreateTrigger(_)
708        | CommandPlan::DropTrigger(_)
709        | CommandPlan::CreateRule(_)
710        | CommandPlan::DropRule(_)
711        | CommandPlan::DoBlock { .. }
712        | CommandPlan::Empty => {}
713    }
714    control.check()?;
715    Ok(())
716}