1use super::{identity_lookup::ColumnKey, RowSchema, NULL_SLOT};
10use crate::{ast::InternalColumnRef, SQLError, ScalarExpr};
11use uqa_core::memory::{ProductionControl, ProductionMap};
12
13#[derive(Clone, Copy)]
14enum Binding {
15 Unique(Option<usize>),
16 Ambiguous,
17}
18
19enum Layout<'s, 'c> {
20 Row(&'s RowSchema),
21 Join {
22 left: &'s RowSchema,
23 right: &'s RowSchema,
24 visible: ProductionMap<'c, (Option<&'s str>, &'s str), Binding>,
25 },
26}
27
28pub struct InputSlots<'s, 'c> {
30 layout: Layout<'s, 'c>,
31 control: ProductionControl<'c>,
32}
33
34impl<'s, 'c> InputSlots<'s, 'c> {
35 pub fn borrow(schema: &'s RowSchema, control: ProductionControl<'c>) -> Self {
36 Self {
37 layout: Layout::Row(schema),
38 control,
39 }
40 }
41
42 pub fn join(
44 left: &'s RowSchema,
45 right: &'s RowSchema,
46 control: ProductionControl<'c>,
47 ) -> Result<Self, SQLError> {
48 control.check()?;
49 let mut visible = ProductionMap::new(control);
50 for (schema, base) in [(left, 0), (right, left.physical_width())] {
51 for (position, identity) in schema.identities().iter().enumerate() {
52 control.check()?;
53 let slot = schema.slot(position).map(|slot| base + slot);
54 let keys = [
55 Some((None, identity.column())),
56 identity.qualifier().map(|q| (Some(q), identity.column())),
57 ];
58 for key in keys.into_iter().flatten() {
59 let binding = if visible.get(&key).is_some() {
60 Binding::Ambiguous
61 } else {
62 Binding::Unique(slot)
63 };
64 visible.insert_copy(key, binding)?;
65 }
66 }
67 }
68 for column in right.index.executor_attributes.keys() {
69 control.check()?;
70 assert!(
71 !left.index.executor_attributes.contains_key(column),
72 "duplicate internal relation attribute in joined row"
73 );
74 }
75 for column in right.index.cold.executor_attribute_types.keys() {
76 control.check()?;
77 assert!(
78 !left
79 .index
80 .cold
81 .executor_attribute_types
82 .contains_key(column),
83 "duplicate internal relation attribute type in joined row"
84 );
85 }
86 Ok(Self {
87 layout: Layout::Join {
88 left,
89 right,
90 visible,
91 },
92 control,
93 })
94 }
95
96 pub fn physical_width(&self) -> usize {
97 match &self.layout {
98 Layout::Row(schema) => schema.physical_width(),
99 Layout::Join { left, right, .. } => left.physical_width() + right.physical_width(),
100 }
101 }
102
103 pub fn visit_reference(
105 &self,
106 expression: &ScalarExpr,
107 visitor: &mut impl FnMut(usize) -> Result<(), SQLError>,
108 ) -> Result<(), SQLError> {
109 self.control.check()?;
110 let slot = match expression {
111 ScalarExpr::Column(name) => match self.named_slot(None, name) {
112 Some(slot) => Some(slot),
113 None => return self.qualified_star(name, visitor),
114 },
115 ScalarExpr::QualifiedColumn { qualifier, column } => {
116 self.named_slot(Some(qualifier), column)
117 }
118 ScalarExpr::InternalColumn(column) => self.internal_slot(*column),
119 ScalarExpr::QualifiedStar(qualifier) => {
120 return self.qualified_star(qualifier, visitor);
121 }
122 ScalarExpr::Star => {
123 for (schema, base) in self.schemas().into_iter().flatten() {
124 for position in 0..schema.len() {
125 self.control.check()?;
126 if schema.wildcard_position_visible(position) {
127 if let Some(slot) = schema.slot(position) {
128 visitor(base + slot)?;
129 }
130 }
131 }
132 }
133 None
134 }
135 ScalarExpr::Position(position) => self.slot(*position),
136 _ => None,
137 };
138 if let Some(slot) = slot {
139 visitor(slot)?;
140 }
141 Ok(())
142 }
143
144 fn schemas(&self) -> [Option<(&RowSchema, usize)>; 2] {
145 match &self.layout {
146 Layout::Row(schema) => [Some((schema, 0)), None],
147 Layout::Join { left, right, .. } => {
148 [Some((left, 0)), Some((right, left.physical_width()))]
149 }
150 }
151 }
152
153 fn named_slot(&self, qualifier: Option<&str>, column: &str) -> Option<usize> {
154 match &self.layout {
155 Layout::Row(schema) => qualifier.map_or_else(
156 || schema.column_slot(column),
157 |q| schema.qualified_slot(q, column),
158 ),
159 Layout::Join {
160 left,
161 right,
162 visible,
163 } => {
164 let key = (qualifier, column);
165 match visible.get(&key) {
166 Some(Binding::Ambiguous) => return None,
167 Some(Binding::Unique(Some(slot))) => return Some(*slot),
168 Some(Binding::Unique(None)) | None => {}
169 }
170 let key = &key as &dyn ColumnKey;
171 let slot = right
172 .index
173 .aliases
174 .get(key)
175 .map(|slot| shift(*slot, left.physical_width()))
176 .or_else(|| left.index.aliases.get(key).copied());
177 slot.filter(|slot| *slot != NULL_SLOT)
178 }
179 }
180 }
181
182 fn slot(&self, position: usize) -> Option<usize> {
183 match &self.layout {
184 Layout::Row(schema) => schema.slot(position),
185 Layout::Join { left, right, .. } => {
186 if position < left.len() {
187 left.slot(position)
188 } else {
189 right
190 .slot(position - left.len())
191 .map(|slot| left.physical_width() + slot)
192 }
193 }
194 }
195 }
196
197 fn internal_slot(&self, column: InternalColumnRef) -> Option<usize> {
198 match &self.layout {
199 Layout::Row(schema) => schema.internal_slot(column),
200 Layout::Join { left, right, .. } => left.internal_slot(column).or_else(|| {
201 right
202 .internal_slot(column)
203 .map(|slot| left.physical_width() + slot)
204 }),
205 }
206 }
207
208 fn qualified_star(
209 &self,
210 qualifier: &str,
211 visitor: &mut impl FnMut(usize) -> Result<(), SQLError>,
212 ) -> Result<(), SQLError> {
213 let schemas = self.schemas();
214 for (index, item) in schemas.iter().enumerate() {
215 let Some((schema, base)) = item else {
216 continue;
217 };
218 for (position, identity) in schema.identities().iter().enumerate() {
219 self.control.check()?;
220 if identity.qualifier() == Some(qualifier) {
221 visitor(shift(schema.slot(position).unwrap_or(NULL_SLOT), *base))?;
222 }
223 }
224 for (identity, slot) in &schema.index.aliases {
225 self.control.check()?;
226 let replaced = index == 0
227 && schemas[1]
228 .is_some_and(|(right, _)| right.index.aliases.contains_key(identity));
229 if !replaced && identity.qualifier() == Some(qualifier) {
230 visitor(shift(*slot, *base))?;
231 }
232 }
233 }
234 Ok(())
235 }
236}
237
238fn shift(slot: usize, base: usize) -> usize {
239 if slot == NULL_SLOT {
240 NULL_SLOT
241 } else {
242 base + slot
243 }
244}
245
246#[cfg(test)]
247mod tests;