Skip to main content

uqa_sql/plan/mutable/
expression.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! A standalone scalar and its query namespace retain separate mutable constructor owners.
8
9use super::{OwnedScalarExpr, ScalarQueryArena};
10use crate::{plan::ExpressionPlan, SQLError};
11use uqa_core::memory::{Produced, ProductionControl};
12
13pub struct MutableExpressionPlan {
14    scalar: OwnedScalarExpr,
15    arena: ScalarQueryArena,
16}
17
18impl super::MutableQueryPlan {
19    /// Edit an optional WHERE clause together with its scalar-query namespace, including construction of a previously absent predicate.
20    pub fn map_where_input(
21        self,
22        control: &ProductionControl<'_>,
23        map: impl FnOnce(
24            Option<OwnedScalarExpr>,
25            &mut ScalarQueryArena,
26        ) -> Result<Option<OwnedScalarExpr>, SQLError>,
27    ) -> Result<Self, SQLError> {
28        let (mut query, predicate) = self.take_where(control)?;
29        let mut arena = query.take_arena();
30        let predicate = map(predicate, &mut arena)?;
31        query = query.replace_where(predicate, control)?;
32        query.restore_arena(arena);
33        Ok(query)
34    }
35
36    /// Detach a WHERE clause with its complete original query namespace. Unreferenced namespaces remain with a query that has no WHERE clause.
37    pub fn take_where_expression(
38        self,
39        control: &ProductionControl<'_>,
40    ) -> Result<(Self, Option<MutableExpressionPlan>), SQLError> {
41        let (mut query, predicate) = self.take_where(control)?;
42        let expression = predicate
43            .map(|scalar| MutableExpressionPlan::from_parts(scalar, query.take_arena(), control))
44            .transpose()?;
45        Ok((query, expression))
46    }
47
48    pub(crate) fn replace_where_expression(
49        self,
50        expression: MutableExpressionPlan,
51        control: &ProductionControl<'_>,
52    ) -> Result<Self, SQLError> {
53        let (scalar, arena) = expression.into_parts(control)?;
54        let mut query = self.replace_where(Some(scalar), control)?;
55        query.restore_arena(arena);
56        Ok(query)
57    }
58}
59
60impl ExpressionPlan {
61    pub fn copy_for_rewrite(
62        &self,
63        control: &ProductionControl<'_>,
64    ) -> Result<MutableExpressionPlan, SQLError> {
65        MutableExpressionPlan::copy_from(&self.scalar, &self.subqueries, control)
66    }
67}
68
69impl MutableExpressionPlan {
70    pub(crate) fn into_projection_query(
71        self,
72        control: &ProductionControl<'_>,
73    ) -> Result<super::MutableQueryPlan, SQLError> {
74        let (expression, arena) = self.into_parts(control)?;
75        let mut query = super::MutableQueryPlan::projected(
76            [super::projections::OwnedProjection {
77                expression,
78                alias: None,
79            }]
80            .into_iter(),
81            control,
82        )?;
83        query.restore_arena(arena);
84        Ok(query)
85    }
86
87    pub(crate) fn from_projection_query(
88        mut query: super::MutableQueryPlan,
89        control: &ProductionControl<'_>,
90    ) -> Result<Self, SQLError> {
91        let arena = query.take_arena();
92        let (_, mut projections) = query.take_projections(control)?;
93        assert_eq!(projections.len(), 1, "standalone expression projection");
94        Self::from_parts(
95            projections.next().expect("expression").expression,
96            arena,
97            control,
98        )
99    }
100
101    /// Compact scalar-query occurrences through the same namespace remapper used by immutable expressions, retiring removed child payloads before their leases.
102    pub fn prune_subqueries(self, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
103        struct Parts {
104            expression: ExpressionPlan,
105            scalar_memory: Option<crate::plan::scalar::ScalarMemory>,
106            arena_memory: Option<super::memory::RewriteMemory>,
107        }
108        let (scalar, arena) = self.into_parts(control)?;
109        let (scalar, scalar_memory) = scalar.into_rewrite_parts();
110        let mut parts = Parts {
111            expression: ExpressionPlan {
112                scalar,
113                subqueries: arena.queries,
114            },
115            scalar_memory,
116            arena_memory: arena.memory,
117        };
118        let mut fields = parts.arena_memory.as_mut().map(|owner| match owner {
119            super::memory::RewriteMemory::Fields { fields, .. } => fields,
120            super::memory::RewriteMemory::Scalar(_)
121            | super::memory::RewriteMemory::Scalars { .. } => {
122                unreachable!("query arena constructor")
123            }
124        });
125        crate::plan::subqueries::prune_expression_with_retention(
126            &mut parts.expression,
127            *control,
128            |arena, keep| {
129                let mut retained = 0;
130                for index in 0..arena.len() {
131                    if keep(index) {
132                        arena.swap(retained, index);
133                        if let Some(fields) = &mut fields {
134                            fields.swap(retained, index);
135                        }
136                        retained += 1;
137                    }
138                }
139                arena.truncate(retained);
140                if let Some(fields) = fields {
141                    fields.truncate(retained);
142                }
143            },
144        )?;
145        Ok(Self {
146            scalar: OwnedScalarExpr::from_rewrite_parts(
147                parts.expression.scalar,
148                parts.scalar_memory,
149            ),
150            arena: ScalarQueryArena {
151                queries: parts.expression.subqueries,
152                memory: parts.arena_memory,
153            },
154        })
155    }
156
157    pub fn copy_from(
158        scalar: &crate::ScalarExpr,
159        queries: &[crate::plan::QueryPlan],
160        control: &ProductionControl<'_>,
161    ) -> Result<Self, SQLError> {
162        Ok(Self {
163            scalar: scalar.copy_for_rewrite(control)?,
164            arena: ScalarQueryArena::copy_from(queries, control)?,
165        })
166    }
167
168    pub fn from_parts(
169        scalar: OwnedScalarExpr,
170        arena: ScalarQueryArena,
171        control: &ProductionControl<'_>,
172    ) -> Result<Self, SQLError> {
173        let scalar = scalar.rewrite(control, Ok::<_, SQLError>)?;
174        Ok(Self { scalar, arena })
175    }
176
177    pub fn into_parts(
178        self,
179        control: &ProductionControl<'_>,
180    ) -> Result<(OwnedScalarExpr, ScalarQueryArena), SQLError> {
181        let scalar = self.scalar.rewrite(control, Ok::<_, SQLError>)?;
182        Ok((scalar, self.arena))
183    }
184
185    pub fn scalar(&self) -> &crate::ScalarExpr {
186        &self.scalar
187    }
188    pub fn queries(&self) -> &[crate::plan::QueryPlan] {
189        self.arena.queries()
190    }
191
192    pub fn map_scalar(
193        mut self,
194        control: &ProductionControl<'_>,
195        map: impl FnOnce(OwnedScalarExpr, &mut ScalarQueryArena) -> Result<OwnedScalarExpr, SQLError>,
196    ) -> Result<Self, SQLError> {
197        self.scalar = self
198            .scalar
199            .rewrite(control, |scalar| map(scalar, &mut self.arena))?;
200        Ok(self)
201    }
202
203    pub fn map_query(
204        mut self,
205        index: usize,
206        control: &ProductionControl<'_>,
207        map: impl FnOnce(super::MutableQueryPlan) -> Result<super::MutableQueryPlan, SQLError>,
208    ) -> Result<Self, SQLError> {
209        self.arena.map_query(index, control, map)?;
210        Ok(self)
211    }
212
213    pub fn finish(
214        self,
215        control: &ProductionControl<'_>,
216    ) -> Result<Produced<ExpressionPlan>, SQLError> {
217        let scalar = self.scalar.finish(control)?;
218        let queries = self.arena.finish(control)?;
219        let (scalar, scalar_memory) = scalar.into_parts();
220        let (subqueries, queries_memory) = queries.into_parts();
221        Ok(control.finish(
222            ExpressionPlan { scalar, subqueries },
223            control.combine(scalar_memory, queries_memory),
224        )?)
225    }
226}