uqa_sql/plan/mutable/arenas/
transfer.rs1use super::super::{Copying, MutableQueryPlan, OwnedScalarExpr, QueryChildSlot, RewriteMemory};
10use crate::{
11 plan::{QueryPlan, RelationalPlan},
12 SQLError, ScalarExpr,
13};
14use uqa_core::memory::{ProductionControl, ProductionMap};
15
16impl MutableQueryPlan {
17 pub fn transfer_expression_to(
19 mut self,
20 mut destination: Self,
21 expression: OwnedScalarExpr,
22 control: &ProductionControl<'_>,
23 ) -> Result<(Self, Self, OwnedScalarExpr, bool), SQLError> {
24 self.assert_owner(control);
25 destination.assert_owner(control);
26 control.check()?;
27 let expression = expression.rewrite(control, Ok::<_, SQLError>)?;
28 let mut selected = ProductionMap::new(*control);
29 expression.try_visit(&mut |node| {
30 control.check()?;
31 if let Some(id) = query_id(node) {
32 selected.insert_copy(id, ())?;
33 }
34 Ok::<_, SQLError>(true)
35 })?;
36 if selected.is_empty() {
37 return Ok((self, destination, expression, true));
38 }
39 let width = arena(&mut self.query.root).len();
40 if selected.iter().any(|(id, ())| *id >= width) {
41 return Ok((self, destination, expression, false));
42 }
43 let mut exclusive = true;
44 let mut checked = Ok(());
45 crate::plan::subqueries::visit_root(&mut self.query.root, &mut |node| {
46 if checked.is_ok() {
47 checked = control.check();
48 if let Some(id) = query_id(node) {
49 exclusive &= id < width && selected.get(&id).is_none();
50 }
51 }
52 });
53 checked?;
54 if !exclusive {
55 return Ok((self, destination, expression, false));
56 }
57 let previous = arena(&mut destination.query.root).len();
58 let mut moved = ProductionMap::new(*control);
59 let mut retained = ProductionMap::new(*control);
60 for id in 0..width {
61 if selected.get(&id).is_some() {
62 moved.insert_copy(id, previous + moved.len())?;
63 } else {
64 retained.insert_copy(id, retained.len())?;
65 }
66 }
67 let mut selected_ids = selected.iter();
68 let mut take = |index| {
69 if index < previous {
70 take_query(&mut destination, index)
71 } else {
72 let (id, ()) = selected_ids.next().expect("selected child count");
73 take_query(&mut self, *id)
74 }
75 };
76 let count = previous + selected.len();
77 let (children, memory) = match Copying::for_rewrite(*control) {
78 Some(mut copying) => {
79 let children =
80 copying.map(0..count, |copying, index| copying.take_query(take(index)))?;
81 (children, Some(copying.into_rewrite_memory()))
82 }
83 None => ((0..count).map(|index| take(index).query).collect(), None),
84 };
85 *arena(&mut destination.query.root) = children;
86 if let Some(owner) = &mut destination.memory {
87 *arena_memory(owner) = memory;
88 }
89 compact(&mut self, &selected);
90 let expression = expression.remap_subquery_ids(control, &mut |id| {
91 *moved.get(&id).expect("selected expression query")
92 })?;
93 let mut checked = Ok(());
94 crate::plan::subqueries::visit_root(&mut self.query.root, &mut |node| {
95 if checked.is_ok() {
96 checked = control.check();
97 if let Some(id) = query_id_mut(node) {
98 *id = *retained.get(id).expect("retained expression query");
99 }
100 }
101 });
102 checked?;
103 Ok((self, destination, expression, true))
104 }
105}
106
107fn take_query(query: &mut MutableQueryPlan, index: usize) -> MutableQueryPlan {
108 let slot = QueryChildSlot::Subquery(index);
109 MutableQueryPlan {
110 query: std::mem::replace(
111 slot.query_mut(&mut query.query),
112 super::super::queries::empty_query(),
113 ),
114 memory: query
115 .memory
116 .as_mut()
117 .and_then(|memory| slot.memory_mut(memory).take()),
118 }
119}
120
121fn compact(query: &mut MutableQueryPlan, selected: &ProductionMap<'_, usize, ()>) {
122 let arena = arena(&mut query.query.root);
123 let mut fields = query.memory.as_mut().map(|memory| {
124 let RewriteMemory::Fields { fields, .. } =
125 arena_memory(memory).as_mut().expect("query arena")
126 else {
127 unreachable!("query arena fields")
128 };
129 fields
130 });
131 let mut retained = 0;
132 for index in 0..arena.len() {
133 if selected.get(&index).is_none() {
134 arena.swap(retained, index);
135 if let Some(fields) = &mut fields {
136 fields.swap(retained, index);
137 }
138 retained += 1;
139 }
140 }
141 arena.truncate(retained);
142 if let Some(fields) = fields {
143 fields.truncate(retained);
144 }
145}
146
147fn arena(root: &mut RelationalPlan) -> &mut Vec<QueryPlan> {
148 match root {
149 RelationalPlan::QueryBlock(block) => &mut block.subqueries,
150 RelationalPlan::Values { subqueries, .. } | RelationalPlan::SetOp { subqueries, .. } => {
151 subqueries
152 }
153 }
154}
155
156fn arena_memory(memory: &mut RewriteMemory) -> &mut Option<RewriteMemory> {
157 let root = memory.field_mut("root").as_mut().expect("query root");
158 let RewriteMemory::Fields { fields, .. } = root else {
159 unreachable!("query root fields")
160 };
161 let has_block = fields.iter().any(|field| field.name == "block");
162 let root = if has_block {
163 root.field_mut("block").as_mut().expect("query block")
164 } else {
165 root
166 };
167 root.field_mut("subqueries")
168}
169
170fn query_id(node: &ScalarExpr) -> Option<usize> {
171 match node {
172 ScalarExpr::ScalarSubquery(id)
173 | ScalarExpr::Exists { subquery: id, .. }
174 | ScalarExpr::InSubquery { subquery: id, .. } => Some(*id),
175 _ => None,
176 }
177}
178
179fn query_id_mut(node: &mut ScalarExpr) -> Option<&mut usize> {
180 match node {
181 ScalarExpr::ScalarSubquery(id)
182 | ScalarExpr::Exists { subquery: id, .. }
183 | ScalarExpr::InSubquery { subquery: id, .. } => Some(id),
184 _ => None,
185 }
186}