Skip to main content

uqa_sql/plan/mutable/
ctes.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Query and mutation CTE bodies move independently of their declaration metadata.
8
9use super::{memory::RewriteMemory, MutableCommandPlan, MutableExecutablePlan, MutableQueryPlan};
10use crate::{
11    plan::{CommandPlan, CtePlanBody},
12    SQLError,
13};
14use uqa_core::memory::ProductionControl;
15
16impl MutableQueryPlan {
17    /// Rewrite one CTE body while preserving its query/command kind and original declaration box. Its name, columns and scheduling metadata stay with the parent query.
18    pub fn map_cte(
19        mut self,
20        index: usize,
21        control: &ProductionControl<'_>,
22        map: impl FnOnce(MutableExecutablePlan) -> Result<MutableExecutablePlan, SQLError>,
23    ) -> Result<Self, SQLError> {
24        self.assert_owner(control);
25        control.check()?;
26        let memory = self.memory.as_mut().map(|memory| cte_memory(memory, index));
27        rewrite_body(&mut self.query.ctes[index].body, memory, control, map)?;
28        Ok(self)
29    }
30}
31
32impl MutableCommandPlan {
33    /// Rewrite a data-modifying command's CTE without copying its declaration or enclosing box.
34    pub fn map_cte(
35        mut self,
36        index: usize,
37        control: &ProductionControl<'_>,
38        map: impl FnOnce(MutableExecutablePlan) -> Result<MutableExecutablePlan, SQLError>,
39    ) -> Result<Self, SQLError> {
40        self.assert_owner(control);
41        control.check()?;
42        let memory = self.memory.as_mut().map(|memory| {
43            cte_memory(
44                memory.field_mut("value0").as_mut().expect("mutation body"),
45                index,
46            )
47        });
48        let ctes = self.command.ctes_mut().expect("command owns CTEs");
49        rewrite_body(&mut ctes[index].body, memory, control, map)?;
50        Ok(self)
51    }
52}
53
54fn cte_memory(memory: &mut RewriteMemory, index: usize) -> &mut RewriteMemory {
55    memory
56        .field_mut("ctes")
57        .as_mut()
58        .expect("CTE vector")
59        .item_mut(index)
60        .as_mut()
61        .expect("CTE entry")
62        .field_mut("body")
63        .as_mut()
64        .expect("CTE body box")
65}
66
67fn rewrite_body(
68    body: &mut CtePlanBody,
69    mut memory: Option<&mut RewriteMemory>,
70    control: &ProductionControl<'_>,
71    map: impl FnOnce(MutableExecutablePlan) -> Result<MutableExecutablePlan, SQLError>,
72) -> Result<(), SQLError> {
73    match body {
74        CtePlanBody::Query(query) => {
75            let input = MutableQueryPlan {
76                query: std::mem::replace(query.as_mut(), super::queries::empty_query()),
77                memory: memory
78                    .as_mut()
79                    .and_then(|memory| memory.field_mut("query").take()),
80            };
81            let MutableExecutablePlan::Query(output) = map(MutableExecutablePlan::Query(input))?
82            else {
83                return Err(SQLError::Internal(
84                    "CTE rewrite changed a query body into a command".into(),
85                ));
86            };
87            output.assert_owner(control);
88            control.check()?;
89            **query = output.query;
90            if let Some(memory) = memory {
91                *memory.field_mut("query") = output.memory;
92            }
93        }
94        CtePlanBody::Command(command) => {
95            let input = MutableCommandPlan {
96                command: std::mem::replace(command.as_mut(), CommandPlan::Empty),
97                memory: memory
98                    .as_mut()
99                    .and_then(|memory| memory.field_mut("command").take()),
100            };
101            let MutableExecutablePlan::Command(output) =
102                map(MutableExecutablePlan::Command(input))?
103            else {
104                return Err(SQLError::Internal(
105                    "CTE rewrite changed a command body into a query".into(),
106                ));
107            };
108            output.assert_owner(control);
109            control.check()?;
110            **command = output.command;
111            if let Some(memory) = memory {
112                *memory.field_mut("command") = output.memory;
113            }
114        }
115    }
116    Ok(())
117}