Skip to main content

uqa_sql/plan/mutable/
values.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! VALUES roots transfer existing row storage into projections or a correlated relational source.
8
9use super::{
10    Copying, MutableQueryPlan, MutableSourcePlan, OwnedProjection, OwnedScalarExpr, RelationalPlan,
11    RewriteMemory, ScalarQueryArena,
12};
13use crate::{ast::InternalRelationId, SQLError, ScalarExpr};
14use uqa_core::memory::ProductionControl;
15
16pub(in crate::plan) struct OwnedRows {
17    pub(in crate::plan) rows: Vec<Vec<ScalarExpr>>,
18    pub(in crate::plan) memory: Option<RewriteMemory>,
19}
20
21pub struct OwnedValueRow {
22    values: std::vec::IntoIter<ScalarExpr>,
23    memory: Option<RewriteMemory>,
24    position: usize,
25}
26
27impl Iterator for OwnedValueRow {
28    type Item = OwnedScalarExpr;
29    fn next(&mut self) -> Option<Self::Item> {
30        let expression = self.values.next()?;
31        let memory = self.memory.as_mut().map(|memory| {
32            memory
33                .scalar_item_mut(self.position)
34                .take()
35                .expect("VALUES scalar")
36        });
37        self.position += 1;
38        Some(OwnedScalarExpr::from_rewrite_parts(expression, memory))
39    }
40    fn size_hint(&self) -> (usize, Option<usize>) {
41        self.values.size_hint()
42    }
43}
44impl ExactSizeIterator for OwnedValueRow {}
45
46impl OwnedRows {
47    pub(in crate::plan) fn take_row(&mut self, index: usize) -> OwnedValueRow {
48        OwnedValueRow {
49            values: std::mem::take(&mut self.rows[index]).into_iter(),
50            memory: self
51                .memory
52                .as_mut()
53                .and_then(|memory| memory.item_mut(index).take()),
54            position: 0,
55        }
56    }
57}
58
59impl MutableQueryPlan {
60    /// Transform VALUES rows through independently owned scalars while keeping the query namespace and metadata unchanged.
61    pub fn map_value_rows<I: ExactSizeIterator<Item = OwnedScalarExpr>>(
62        mut self,
63        control: &ProductionControl<'_>,
64        mut map: impl FnMut(OwnedValueRow) -> Result<I, SQLError>,
65    ) -> Result<Self, SQLError> {
66        self.assert_owner(control);
67        control.check()?;
68        let RelationalPlan::Values { rows, .. } = &mut self.query.root else {
69            return Err(SQLError::Internal(
70                "VALUES row edit requires a VALUES root".into(),
71            ));
72        };
73        let mut input = OwnedRows {
74            rows: std::mem::take(rows),
75            memory: self.memory.as_mut().and_then(|memory| {
76                memory
77                    .field_mut("root")
78                    .as_mut()
79                    .expect("VALUES root")
80                    .field_mut("rows")
81                    .take()
82            }),
83        };
84        let (rows, memory) = if let Some(mut copying) = Copying::for_rewrite(*control) {
85            let rows = copying.map(0..input.rows.len(), |copying, index| {
86                copying.scalar_values(map(input.take_row(index))?.map(Ok))
87            })?;
88            (rows, Some(copying.into_rewrite_memory()))
89        } else {
90            let rows = (0..input.rows.len())
91                .map(|index| {
92                    map(input.take_row(index))?
93                        .map(|value| {
94                            Ok(value
95                                .finish(control)?
96                                .into_uncontrolled()
97                                .expect("ordinary VALUES scalar"))
98                        })
99                        .collect::<Result<Vec<_>, SQLError>>()
100                })
101                .collect::<Result<Vec<_>, SQLError>>()?;
102            (rows, None)
103        };
104        let RelationalPlan::Values { rows: output, .. } = &mut self.query.root else {
105            unreachable!()
106        };
107        *output = rows;
108        if let Some(owner) = &mut self.memory {
109            *owner
110                .field_mut("root")
111                .as_mut()
112                .expect("VALUES root")
113                .field_mut("rows") = memory;
114        }
115        control.check()?;
116        Ok(self)
117    }
118
119    /// Keep the original query scope and scalar arena while exposing VALUES as an ordinary projection block. A single row becomes the projection list; multiple rows retain their buffers in a lateral captured source.
120    pub fn project_values(mut self, control: &ProductionControl<'_>) -> Result<Self, SQLError> {
121        self.assert_owner(control);
122        control.check()?;
123        if !matches!(self.query.root, RelationalPlan::Values { .. }) {
124            return Ok(self);
125        }
126        let root = std::mem::replace(
127            &mut self.query.root,
128            RelationalPlan::Values {
129                rows: Vec::new(),
130                subqueries: Vec::new(),
131            },
132        );
133        let RelationalPlan::Values { rows, subqueries } = root else {
134            unreachable!()
135        };
136        let mut memory = self
137            .memory
138            .as_mut()
139            .and_then(|memory| memory.field_mut("root").take());
140        let mut rows = OwnedRows {
141            rows,
142            memory: memory
143                .as_mut()
144                .and_then(|memory| memory.field_mut("rows").take()),
145        };
146        let arena = ScalarQueryArena {
147            queries: subqueries,
148            memory: memory
149                .as_mut()
150                .and_then(|memory| memory.field_mut("subqueries").take()),
151        };
152        drop(memory);
153        let mut generated = if rows.rows.len() == 1 {
154            let row = rows.take_row(0);
155            drop(rows);
156            Self::projected(
157                row.map(|expression| OwnedProjection {
158                    expression,
159                    alias: None,
160                }),
161                control,
162            )?
163        } else {
164            let relation = InternalRelationId::allocate();
165            let width = rows.rows.first().map_or(0, Vec::len);
166            let mut projections = crate::production::Buffer::new(control);
167            for position in 0..width {
168                projections.push(
169                    OwnedProjection {
170                        expression: ScalarExpr::InternalColumn(relation.column(position))
171                            .copy_for_rewrite(control)?,
172                        alias: None,
173                    },
174                    control,
175                )?;
176            }
177            let query = Self::projected(projections.into_iter(), control)?;
178            let source = if let Some(mut copying) = Copying::for_rewrite(*control) {
179                let source = copying.captured_rows_source(rows, relation, width)?;
180                MutableSourcePlan {
181                    source,
182                    memory: Some(copying.into_rewrite_memory()),
183                }
184            } else {
185                MutableSourcePlan {
186                    source: crate::plan::SourcePlan::Values {
187                        lateral: true,
188                        rows: rows.rows,
189                        alias: None,
190                        column_aliases: Vec::new(),
191                        internal_relation: Some(relation),
192                        internal_column_types: vec![None; width],
193                        internal_column_collations: vec![None; width],
194                    },
195                    memory: None,
196                }
197            };
198            query.replace_source(Some(source), control)?
199        };
200        std::mem::swap(&mut self.query.root, &mut generated.query.root);
201        if let Some(memory) = &mut self.memory {
202            *memory.field_mut("root") = generated
203                .memory
204                .as_mut()
205                .expect("generated root owner")
206                .field_mut("root")
207                .take();
208        }
209        self.restore_arena(arena);
210        Ok(self)
211    }
212}