Skip to main content

uqa_sql/plan/mutable/commands/
executable.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Utility statement bodies keep their existing wrapper and statement boxes while moving the executable owner.
8
9use super::super::MutableExecutablePlan;
10use super::{CommandPlan, MutableCommandPlan, MutableQueryPlan, RewriteMemory, SQLError};
11use crate::plan::UnifiedPlan;
12use uqa_core::memory::ProductionControl;
13
14impl MutableCommandPlan {
15    /// Replace only EXPLAIN's inferred parameter owner after its body analysis succeeds.
16    pub fn set_explain_parameters(
17        mut self,
18        parameters: Option<uqa_core::memory::Produced<Vec<crate::SQLParam>>>,
19        control: &ProductionControl<'_>,
20    ) -> Result<Self, SQLError> {
21        self.assert_owner(control);
22        control.check()?;
23        let CommandPlan::Explain {
24            unbound_parameters, ..
25        } = &mut self.command
26        else {
27            return Err(SQLError::Internal(
28                "inferred parameters require EXPLAIN".into(),
29            ));
30        };
31        let (parameters, memory) = match parameters {
32            Some(parameters) => {
33                let (parameters, memory) = parameters.into_parts();
34                (Some(parameters), memory)
35            }
36            None => (None, control.empty_reservation()),
37        };
38        let (parameters, memory) = control.finish(parameters, memory)?.into_parts();
39        let replacement = memory.map(|direct| RewriteMemory::Fields {
40            fields: uqa_core::memory::BudgetedVec::new(direct.budget()),
41            direct,
42        });
43        *unbound_parameters = parameters;
44        if let Some(memory) = &mut self.memory {
45            *memory.field_mut("unbound_parameters") = replacement;
46        }
47        Ok(self)
48    }
49    /// Rewrite EXPLAIN or PREPARE's complete nested statement without moving its wrapper metadata or changing the query/command variant.
50    pub fn map_executable_body(
51        mut self,
52        control: &ProductionControl<'_>,
53        map: impl FnOnce(MutableExecutablePlan) -> Result<MutableExecutablePlan, SQLError>,
54    ) -> Result<Self, SQLError> {
55        self.assert_owner(control);
56        control.check()?;
57        let body = match &mut self.command {
58            CommandPlan::Explain { body, .. } | CommandPlan::Prepare { body, .. } => body,
59            _ => {
60                return Err(SQLError::Internal(
61                    "executable body requires EXPLAIN or PREPARE".into(),
62                ))
63            }
64        };
65        let memory = self.memory.as_mut().map(|memory| {
66            memory
67                .field_mut("body")
68                .as_mut()
69                .expect("utility body owner")
70        });
71        rewrite(body, memory, control, map)?;
72        Ok(self)
73    }
74}
75
76fn rewrite(
77    body: &mut UnifiedPlan,
78    mut memory: Option<&mut RewriteMemory>,
79    control: &ProductionControl<'_>,
80    map: impl FnOnce(MutableExecutablePlan) -> Result<MutableExecutablePlan, SQLError>,
81) -> Result<(), SQLError> {
82    match body {
83        UnifiedPlan::Query(query) => {
84            let input = MutableQueryPlan {
85                query: std::mem::replace(query.as_mut(), super::super::queries::empty_query()),
86                memory: memory
87                    .as_mut()
88                    .and_then(|memory| memory.field_mut("query").take()),
89            };
90            let MutableExecutablePlan::Query(output) = map(MutableExecutablePlan::Query(input))?
91            else {
92                return Err(SQLError::Internal(
93                    "utility rewrite changed a query body into a command".into(),
94                ));
95            };
96            output.assert_owner(control);
97            control.check()?;
98            **query = output.query;
99            if let Some(memory) = memory {
100                *memory.field_mut("query") = output.memory;
101            }
102        }
103        UnifiedPlan::Command(command) => {
104            let input = MutableCommandPlan {
105                command: std::mem::replace(command.as_mut(), CommandPlan::Empty),
106                memory: memory
107                    .as_mut()
108                    .and_then(|memory| memory.field_mut("command").take()),
109            };
110            let MutableExecutablePlan::Command(output) =
111                map(MutableExecutablePlan::Command(input))?
112            else {
113                return Err(SQLError::Internal(
114                    "utility rewrite changed a command body into a query".into(),
115                ));
116            };
117            output.assert_owner(control);
118            control.check()?;
119            **command = output.command;
120            if let Some(memory) = memory {
121                *memory.field_mut("command") = output.memory;
122            }
123        }
124    }
125    Ok(())
126}