1use std::collections::HashMap;
4
5use super::column::{CellValue, Column};
6use super::dataset::Dataset;
7use super::query::Query;
8use super::source::DataError;
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum JoinKind {
22 #[default]
24 Inner,
25 Left,
27}
28
29pub fn join(
43 left: &Dataset,
44 right: &Dataset,
45 on_left: &str,
46 on_right: &str,
47 kind: JoinKind,
48) -> Result<Dataset, DataError> {
49 let left_key = left
50 .column_named(on_left)
51 .ok_or_else(|| DataError::Unsupported(format!("missing join column `{on_left}`")))?;
52 let right_key = right
53 .column_named(on_right)
54 .ok_or_else(|| DataError::Unsupported(format!("missing join column `{on_right}`")))?;
55 let mut index: HashMap<String, Vec<usize>> = HashMap::new();
56 for row in 0..right.row_count() {
57 let key = right_key.cell(row);
58 if key.is_null() {
59 continue;
60 }
61 index.entry(key.to_text()).or_default().push(row);
62 }
63 let mut left_rows = Vec::new();
64 let mut right_rows = Vec::new();
65 for row in 0..left.row_count() {
66 let key = left_key.cell(row);
67 if key.is_null() {
68 if kind == JoinKind::Left {
69 left_rows.push(row);
70 right_rows.push(usize::MAX);
71 }
72 continue;
73 }
74 match index.get(&key.to_text()) {
75 Some(matches) => {
76 for match_row in matches {
77 left_rows.push(row);
78 right_rows.push(*match_row);
79 }
80 }
81 None if kind == JoinKind::Left => {
82 left_rows.push(row);
83 right_rows.push(usize::MAX);
84 }
85 None => {}
86 }
87 }
88 let mut joined = left.take(&left_rows);
89 let right_taken = right.take(&right_rows);
90 for column in right_taken.columns() {
91 let mut column = column.clone();
92 if joined.column_named(&column.name).is_some() {
93 column.name = format!("{}_right", column.name);
94 }
95 joined.push_column(column);
96 }
97 Ok(joined)
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum WindowFunction {
112 RowNumber,
114 Rank,
116 Lag(usize),
118 Lead(usize),
120 RollingMean(usize),
122}
123
124pub fn window(values: &[f64], function: WindowFunction) -> Vec<f64> {
134 match function {
135 WindowFunction::RowNumber => (1..=values.len()).map(|index| index as f64).collect(),
136 WindowFunction::Rank => values
137 .iter()
138 .map(|value| values.iter().filter(|other| *other < value).count() as f64 + 1.0)
139 .collect(),
140 WindowFunction::Lag(distance) => (0..values.len())
141 .map(|index| {
142 index
143 .checked_sub(distance)
144 .and_then(|index| values.get(index))
145 .copied()
146 .unwrap_or(f64::NAN)
147 })
148 .collect(),
149 WindowFunction::Lead(distance) => (0..values.len())
150 .map(|index| values.get(index + distance).copied().unwrap_or(f64::NAN))
151 .collect(),
152 WindowFunction::RollingMean(width) => {
153 let width = width.max(1);
154 let half = width / 2;
155 (0..values.len())
156 .map(|index| {
157 let start = index.saturating_sub(half);
158 let end = (index + width - half).min(values.len());
159 let slice = values.get(start..end).unwrap_or_default();
160 if slice.is_empty() {
161 f64::NAN
162 } else {
163 slice.iter().sum::<f64>() / slice.len() as f64
164 }
165 })
166 .collect()
167 }
168 }
169}
170
171pub fn window_column(data: &Dataset, column: &str, function: WindowFunction) -> Result<Column, DataError> {
184 let source = data
185 .column_named(column)
186 .ok_or_else(|| DataError::Unsupported(format!("missing window column `{column}`")))?;
187 let values: Vec<f64> = (0..data.row_count())
188 .map(|row| match source.cell(row) {
189 CellValue::Float(value) => value,
190 CellValue::Int(value) => value as f64,
191 _ => f64::NAN,
192 })
193 .collect();
194 Ok(Column::floats(format!("{column}_window"), window(&values, function)))
195}
196
197#[non_exhaustive]
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub struct QueryPlan {
211 pub columns: Vec<String>,
213 pub rows: Vec<usize>,
215}
216
217pub fn plan(query: &Query, data: &Dataset) -> QueryPlan {
229 QueryPlan {
230 columns: query.columns(),
231 rows: query.matching_rows(data),
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 fn left() -> Dataset {
240 Dataset::from_columns([Column::ints("id", vec![1, 2, 3]), Column::text("name", ["a", "b", "c"])])
241 }
242
243 fn right() -> Dataset {
244 Dataset::from_columns([
245 Column::ints("id", vec![1, 1, 3]),
246 Column::ints("value", vec![10, 11, 30]),
247 ])
248 }
249
250 #[test]
251 fn an_inner_join_repeats_matching_left_rows() {
252 let joined = join(&left(), &right(), "id", "id", JoinKind::Inner).expect("join");
253 assert_eq!(joined.row_count(), 3);
254 assert_eq!(joined.cell(0, 3), CellValue::Int(10));
255 assert_eq!(joined.cell(1, 3), CellValue::Int(11));
256 assert_eq!(joined.cell(2, 3), CellValue::Int(30));
257 }
258
259 #[test]
260 fn a_left_join_keeps_unmatched_rows() {
261 let joined = join(&left(), &right(), "id", "id", JoinKind::Left).expect("join");
262 assert_eq!(joined.row_count(), 4);
263 assert_eq!(joined.cell(2, 3), CellValue::Null);
264 }
265
266 #[test]
267 fn windows_compute_ranks_lags_and_means() {
268 let values = [1.0, 3.0, 3.0, 5.0];
269 assert_eq!(window(&values, WindowFunction::RowNumber), [1.0, 2.0, 3.0, 4.0]);
270 assert_eq!(window(&values, WindowFunction::Rank), [1.0, 2.0, 2.0, 4.0]);
271 assert!(window(&values, WindowFunction::Lag(1))[0].is_nan());
272 assert_eq!(window(&values, WindowFunction::Lag(1))[1], 1.0);
273 assert_eq!(window(&values, WindowFunction::RollingMean(3))[0], 2.0);
274 }
275
276 #[test]
277 fn a_plan_lists_the_filter_columns_and_rows() {
278 let query = Query::parse("id > 1 && name == \"b\"").expect("query");
279 let plan = plan(&query, &left());
280 assert_eq!(plan.columns, ["id", "name"]);
281 assert_eq!(plan.rows, [1]);
282 }
283}