Skip to main content

uqa_sql/plan/mutable/arenas/
owner.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Scalar-query occurrence copies retain independent child plans and admit the replacement arena before moving any existing child.
8
9use super::super::{Copying, MutableQueryPlan, OwnedScalarExpr, RewriteMemory};
10use crate::{plan::QueryPlan, SQLError};
11use uqa_core::memory::{Produced, ProductionControl, ProductionVec};
12
13/// A private scalar-query namespace. Its syntax and constructor records move together; observers can borrow children while only owning operations can add them.
14pub struct ScalarQueryArena {
15    pub(in crate::plan::mutable) queries: Vec<QueryPlan>,
16    pub(in crate::plan::mutable) memory: Option<RewriteMemory>,
17}
18
19impl ScalarQueryArena {
20    pub(in crate::plan) fn from_rewrite_parts(
21        queries: Vec<QueryPlan>,
22        memory: Option<RewriteMemory>,
23    ) -> Self {
24        Self { queries, memory }
25    }
26
27    pub(crate) fn copy_from(
28        queries: &[QueryPlan],
29        control: &ProductionControl<'_>,
30    ) -> Result<Self, SQLError> {
31        control.check()?;
32        let Some(mut copying) = Copying::for_rewrite(*control) else {
33            return Ok(Self {
34                queries: queries.to_vec(),
35                memory: None,
36            });
37        };
38        let queries = copying.map(queries.iter(), |copying, query| copying.query(query))?;
39        Ok(Self {
40            queries,
41            memory: Some(copying.into_rewrite_memory()),
42        })
43    }
44
45    pub(crate) fn finish(
46        self,
47        control: &ProductionControl<'_>,
48    ) -> Result<Produced<Vec<QueryPlan>>, SQLError> {
49        control.check()?;
50        Ok(control.finish(
51            self.queries,
52            self.memory.and_then(RewriteMemory::into_reservation),
53        )?)
54    }
55
56    pub fn map_query(
57        &mut self,
58        index: usize,
59        control: &ProductionControl<'_>,
60        map: impl FnOnce(MutableQueryPlan) -> Result<MutableQueryPlan, SQLError>,
61    ) -> Result<(), SQLError> {
62        control.check()?;
63        let query = self.take(index);
64        let (query, owner) = map(query)?.into_rewrite_parts(control)?;
65        self.queries[index] = query;
66        if let Some(memory) = &mut self.memory {
67            *memory
68                .item_mut(index)
69                .as_mut()
70                .expect("arena query item")
71                .field_mut("query") = owner;
72        }
73        Ok(())
74    }
75
76    pub(crate) fn append_arena(
77        &mut self,
78        mut other: Self,
79        control: &ProductionControl<'_>,
80    ) -> Result<usize, SQLError> {
81        control.check()?;
82        let previous = self.queries.len();
83        if other.queries.is_empty() {
84            return Ok(previous);
85        }
86        let total = previous + other.queries.len();
87        let mut take = |index| {
88            if index < previous {
89                self.take(index)
90            } else {
91                other.take(index - previous)
92            }
93        };
94        let (queries, memory) = if let Some(mut copying) = Copying::for_rewrite(*control) {
95            let queries =
96                copying.map(0..total, |copying, index| copying.take_query(take(index)))?;
97            (queries, Some(copying.into_rewrite_memory()))
98        } else {
99            let mut queries = Vec::with_capacity(total);
100            for index in 0..total {
101                control.check()?;
102                queries.push(take(index).into_rewrite_parts(control)?.0);
103            }
104            (queries, None)
105        };
106        self.queries = queries;
107        self.memory = memory;
108        Ok(previous)
109    }
110
111    /// Add an owning expression to this namespace, moving its query children exactly once and preserving their private nested arenas.
112    pub fn append_expression(
113        &mut self,
114        expression: super::super::MutableExpressionPlan,
115        control: &ProductionControl<'_>,
116    ) -> Result<OwnedScalarExpr, SQLError> {
117        let (scalar, arena) = expression.into_parts(control)?;
118        let offset = self.append_arena(arena, control)?;
119        scalar.remap_subquery_ids(control, &mut |id| id + offset)
120    }
121
122    pub fn queries(&self) -> &[QueryPlan] {
123        &self.queries
124    }
125
126    /// Give every scalar-query occurrence a new result-cache identity. Even repeated references to one source slot are copied independently, in the existing child-before-parent scalar order.
127    pub fn copy_subquery_occurrences(
128        &mut self,
129        expression: OwnedScalarExpr,
130        control: &ProductionControl<'_>,
131    ) -> Result<OwnedScalarExpr, SQLError> {
132        control.check()?;
133        let mut copies = ProductionVec::new(*control);
134        let original_len = self.queries.len();
135        let expression = expression.remap_query_occurrences(control, &mut |id| {
136            let query = self.queries.get(id).ok_or_else(|| {
137                SQLError::Internal("copied scalar subquery is outside its owning arena".into())
138            })?;
139            let query = query.copy_for_rewrite(control)?;
140            let next = original_len + copies.len();
141            copies.push_produced(control.finish(query, control.empty_reservation())?)?;
142            Ok(next)
143        })?;
144        if !copies.is_empty() {
145            self.append(copies.finish()?, control)?;
146        }
147        Ok(expression)
148    }
149
150    /// Append independently owned query children, retaining their original nested namespaces. The produced outer vector owns only the staging buffer; every child owns its own payload.
151    pub(crate) fn append(
152        &mut self,
153        queries: Produced<Vec<MutableQueryPlan>>,
154        control: &ProductionControl<'_>,
155    ) -> Result<usize, SQLError> {
156        control.check()?;
157        let original_len = self.queries.len();
158        let count = original_len + queries.len();
159        let (queries, buffer) = queries.into_parts();
160        let mut pending = Pending {
161            queries: queries.into_iter(),
162            _buffer: buffer,
163        };
164        let mut next = |index| {
165            if index < original_len {
166                self.take(index)
167            } else {
168                pending.queries.next().expect("appended arena child")
169            }
170        };
171        let (queries, memory) = if let Some(mut copying) = Copying::for_rewrite(*control) {
172            let queries =
173                copying.map(0..count, |copying, index| copying.take_query(next(index)))?;
174            (queries, Some(copying.into_rewrite_memory()))
175        } else {
176            let mut queries = Vec::with_capacity(count);
177            for index in 0..count {
178                control.check()?;
179                queries.push(next(index).into_rewrite_parts(control)?.0);
180            }
181            (queries, None)
182        };
183        self.queries = queries;
184        self.memory = memory;
185        control.check()?;
186        Ok(original_len)
187    }
188
189    fn take(&mut self, index: usize) -> MutableQueryPlan {
190        let query = std::mem::replace(
191            &mut self.queries[index],
192            super::super::queries::empty_query(),
193        );
194        let memory = self.memory.as_mut().and_then(|memory| {
195            memory
196                .item_mut(index)
197                .as_mut()
198                .expect("arena query item")
199                .field_mut("query")
200                .take()
201        });
202        MutableQueryPlan::from_rewrite_parts(query, memory)
203    }
204}
205
206struct Pending {
207    queries: std::vec::IntoIter<MutableQueryPlan>,
208    _buffer: Option<uqa_core::memory::MemoryReservation>,
209}