Skip to main content

uqa_sql/plan/mutable/
metadata.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Nonallocating plan decisions and independently replaceable projection metadata.
8
9use super::{
10    memory::RewriteMemory, MutableQueryPlan, OwnedScalarExpr, QueryScalarSlot, RelationalPlan,
11};
12use crate::{
13    plan::{AccessPathPlan, ComputePlan},
14    SQLError, ScalarExpr,
15};
16use uqa_core::{
17    memory::{BudgetedVec, OwnedSet, Produced, ProductionControl},
18    Value,
19};
20
21impl MutableQueryPlan {
22    /// Move DISTINCT slicing to its later execution boundary and retire only the removed LIMIT/OFFSET constructors.
23    pub(crate) fn clear_block_slice(
24        mut self,
25        control: &ProductionControl<'_>,
26    ) -> Result<Self, SQLError> {
27        self.assert_owner(control);
28        control.check()?;
29        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
30            return Err(SQLError::Internal(
31                "execution slice requires a query block".into(),
32            ));
33        };
34        block.limit = None;
35        block.offset = None;
36        if let Some(memory) = &mut self.memory {
37            let block = block_memory(memory);
38            *block.field_mut("limit") = None;
39            *block.field_mut("offset") = None;
40        }
41        control.check()?;
42        Ok(self)
43    }
44
45    /// Drop cached row and source analysis after a structural input rewrite; query syntax and its independently owned fields remain intact.
46    pub fn clear_row_analysis(mut self, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
47        self.assert_owner(control);
48        control.check()?;
49        self.query.analyzed_output = None;
50        self.query.analyzed_source = None;
51        Ok(self)
52    }
53
54    pub fn append_row_lock(
55        mut self,
56        strength: crate::ast::LockStrength,
57        wait: crate::ast::LockWait,
58        control: &ProductionControl<'_>,
59    ) -> Result<Self, SQLError> {
60        self.assert_owner(control);
61        control.check()?;
62        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
63            return Ok(self);
64        };
65        let clause = crate::ast::LockingClause {
66            strength,
67            wait,
68            relations: Vec::new(),
69        };
70        if let Some(mut copying) = super::Copying::for_rewrite(*control) {
71            let count = block.locking.len() + 1;
72            let locking = copying.map(0..count, |copying, index| {
73                let clause = block.locking.get(index).unwrap_or(&clause);
74                Ok(crate::ast::LockingClause {
75                    strength: clause.strength,
76                    wait: clause.wait,
77                    relations: copying.texts(&clause.relations)?,
78                })
79            })?;
80            block.locking = locking;
81            *block_memory(self.memory.as_mut().expect("controlled query")).field_mut("locking") =
82                Some(copying.into_rewrite_memory());
83        } else {
84            block.locking.push(clause);
85        }
86        Ok(self)
87    }
88
89    pub fn set_privilege_subject(
90        mut self,
91        subject: Option<Produced<crate::catalog::roles::RoleReference>>,
92        control: &ProductionControl<'_>,
93    ) -> Result<Self, SQLError> {
94        self.assert_owner(control);
95        control.check()?;
96        let (subject, owner) = if let Some(mut copying) = super::Copying::for_rewrite(*control) {
97            let subject = subject
98                .map(|subject| copying.take_privilege_subject(subject))
99                .transpose()?;
100            (subject, Some(copying.into_rewrite_memory()))
101        } else {
102            (
103                subject.map(|subject| {
104                    subject
105                        .into_uncontrolled()
106                        .expect("ordinary privilege subject")
107                }),
108                None,
109            )
110        };
111        self.query.relation_privilege_subject = subject;
112        if let Some(memory) = &mut self.memory {
113            *memory.field_mut("relation_privilege_subject") = owner;
114        }
115        Ok(self)
116    }
117
118    pub fn clear_privilege_columns(
119        mut self,
120        control: &ProductionControl<'_>,
121    ) -> Result<Self, SQLError> {
122        self.assert_owner(control);
123        control.check()?;
124        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
125            return Err(SQLError::Internal(
126                "privilege column reset requires a query block".into(),
127            ));
128        };
129        block.privilege_columns.clear();
130        if let Some(memory) = &mut self.memory {
131            let owner = memory
132                .field_mut("root")
133                .as_mut()
134                .expect("query root")
135                .field_mut("block")
136                .as_mut()
137                .expect("query block")
138                .field_mut("privilege_columns");
139            *owner = super::Copying::for_rewrite(*control).map(super::Copying::into_rewrite_memory);
140        }
141        Ok(self)
142    }
143
144    /// Retain one privilege dependency after admitting its tree node. Duplicate identities retain the original node and release the unused supplied identity.
145    pub fn include_privilege_column(
146        mut self,
147        identity: Produced<crate::ColumnIdentity>,
148        control: &ProductionControl<'_>,
149    ) -> Result<Self, SQLError> {
150        self.assert_owner(control);
151        control.check()?;
152        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
153            return Err(SQLError::Internal(
154                "column privilege dependency requires a query block".into(),
155            ));
156        };
157        if block.privilege_columns.contains(&*identity) {
158            return Ok(self);
159        }
160        let node = control.reserve(OwnedSet::<crate::ColumnIdentity>::entry_bytes())?;
161        let (identity, payload) = identity.into_parts();
162        let memory = control.combine(payload, node);
163        block.privilege_columns.insert(identity);
164        if let Some(owner) = &mut self.memory {
165            let RewriteMemory::Fields { direct, .. } = block_memory(owner)
166                .field_mut("privilege_columns")
167                .as_mut()
168                .expect("privilege column owner")
169            else {
170                unreachable!("query block field owner");
171            };
172            direct.absorb(memory.expect("controlled privilege dependency"));
173        }
174        Ok(self)
175    }
176
177    /// Change only the allocation-free compute decision chosen by the planner.
178    #[expect(
179        clippy::needless_match,
180        reason = "exhaustive inline reconstruction prevents future payload-bearing variants from bypassing admission"
181    )]
182    pub fn set_compute(
183        mut self,
184        compute: ComputePlan,
185        control: &ProductionControl<'_>,
186    ) -> Result<Self, SQLError> {
187        self.assert_owner(control);
188        control.check()?;
189        let compute = match compute {
190            ComputePlan::Project => ComputePlan::Project,
191            ComputePlan::Aggregate => ComputePlan::Aggregate,
192            ComputePlan::Window => ComputePlan::Window,
193        };
194        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
195            return Err(SQLError::Internal(
196                "compute decision requires a query block".into(),
197            ));
198        };
199        block.compute = compute;
200        Ok(self)
201    }
202
203    /// Change only the allocation-free access decision chosen by the planner.
204    pub fn set_access(
205        mut self,
206        access: AccessPathPlan,
207        control: &ProductionControl<'_>,
208    ) -> Result<Self, SQLError> {
209        self.assert_owner(control);
210        control.check()?;
211        let access = match access {
212            AccessPathPlan::Row => AccessPathPlan::Row,
213            AccessPathPlan::Hybrid => AccessPathPlan::Hybrid,
214            AccessPathPlan::OperatorTree {
215                score_limit_pushdown,
216            } => AccessPathPlan::OperatorTree {
217                score_limit_pushdown,
218            },
219        };
220        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
221            return Err(SQLError::Internal(
222                "access decision requires a query block".into(),
223            ));
224        };
225        block.access = access;
226        Ok(self)
227    }
228
229    /// Select one expression and destroy every other query allocation, including its former projection and parent containers. An absent optional field returns None.
230    pub fn select_scalar(
231        self,
232        slot: QueryScalarSlot,
233        control: &ProductionControl<'_>,
234    ) -> Result<Option<OwnedScalarExpr>, SQLError> {
235        let mut selected = None;
236        let query = self.map_scalar(slot, control, |expression| {
237            selected = Some(expression);
238            Ok(ScalarExpr::Literal(Value::Null).copy_for_rewrite(control)?)
239        })?;
240        drop(query);
241        control.check()?;
242        Ok(selected)
243    }
244
245    /// Replace a projection's name without changing its scalar or positional descriptor. The new text arrives from an admitted producer; removed text is freed before its lease.
246    pub fn replace_projection_alias(
247        mut self,
248        index: usize,
249        alias: Option<Produced<String>>,
250        control: &ProductionControl<'_>,
251    ) -> Result<Self, SQLError> {
252        self.assert_owner(control);
253        control.check()?;
254        let RelationalPlan::QueryBlock(block) = &mut self.query.root else {
255            return Err(SQLError::Internal(
256                "projection alias requires a query block".into(),
257            ));
258        };
259        let (alias, reservation) = match alias {
260            Some(alias) => {
261                let (alias, memory) = alias.into_parts();
262                (Some(alias), memory)
263            }
264            None => (None, control.empty_reservation()),
265        };
266        // Construct the replacement owner before replacing any old payload, including if a mismatched allowance panics.
267        let replacement = control.finish(alias, reservation)?;
268        let (alias, reservation) = replacement.into_parts();
269        let memory = reservation.map(|direct| RewriteMemory::Fields {
270            fields: BudgetedVec::new(direct.budget()),
271            direct,
272        });
273        block.projections[index].alias = alias;
274        if let Some(owner) = &mut self.memory {
275            *projection_memory(owner, index).field_mut("alias") = memory;
276        }
277        Ok(self)
278    }
279}
280
281fn projection_memory(memory: &mut RewriteMemory, index: usize) -> &mut RewriteMemory {
282    block_memory(memory)
283        .field_mut("projections")
284        .as_mut()
285        .expect("projection vector")
286        .item_mut(index)
287        .as_mut()
288        .expect("projection item")
289}
290
291fn block_memory(memory: &mut RewriteMemory) -> &mut RewriteMemory {
292    memory
293        .field_mut("root")
294        .as_mut()
295        .expect("query root")
296        .field_mut("block")
297        .as_mut()
298        .expect("query block")
299}