Skip to main content

crisol_core/data/
query_v2.rs

1//! Joins, window functions, and the pushdown planner.
2
3use std::collections::HashMap;
4
5use super::column::{CellValue, Column};
6use super::dataset::Dataset;
7use super::query::Query;
8use super::source::DataError;
9
10/// How a join treats rows without a match.
11///
12/// # Example
13///
14/// ```
15/// use crisol_core::data::JoinKind;
16///
17/// assert_eq!(JoinKind::default(), JoinKind::Inner);
18/// ```
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum JoinKind {
22    /// Keep only matching pairs.
23    #[default]
24    Inner,
25    /// Keep every left row, with nulls on the right when unmatched.
26    Left,
27}
28
29/// Join two datasets on two columns. Right columns that collide with a left name get a
30/// `_right` suffix.
31///
32/// # Example
33///
34/// ```
35/// use crisol_core::data::{Column, Dataset, JoinKind, join};
36///
37/// let left = Dataset::from_columns([Column::ints("id", vec![1])]);
38/// let right = Dataset::from_columns([Column::ints("id", vec![1])]);
39/// let joined = join(&left, &right, "id", "id", JoinKind::Inner).expect("join");
40/// assert_eq!(joined.row_count(), 1);
41/// ```
42pub 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/// A computed column over one value series.
101///
102/// # Example
103///
104/// ```
105/// use crisol_core::data::WindowFunction;
106///
107/// assert_eq!(WindowFunction::RowNumber, WindowFunction::RowNumber);
108/// ```
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum WindowFunction {
112    /// 1-based position in the series.
113    RowNumber,
114    /// Competition rank: ties share a rank.
115    Rank,
116    /// The value `n` rows earlier, or NaN at the start.
117    Lag(usize),
118    /// The value `n` rows later, or NaN at the end.
119    Lead(usize),
120    /// Centered mean over `n` rows.
121    RollingMean(usize),
122}
123
124/// Compute a window function over `values`.
125///
126/// # Example
127///
128/// ```
129/// use crisol_core::data::{WindowFunction, window};
130///
131/// assert_eq!(window(&[4.0, 5.0], WindowFunction::RowNumber), [1.0, 2.0]);
132/// ```
133pub 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
171/// A window result as a column.
172///
173/// # Example
174///
175/// ```
176/// use crisol_core::data::{Column, Dataset, WindowFunction, window_column};
177///
178/// let data = Dataset::from_columns([Column::floats("v", vec![1.0, 2.0])]);
179/// assert!(window_column(&data, "v", WindowFunction::RowNumber).is_ok());
180/// ```
181/// # Errors
182/// When the source column is missing.
183pub 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/// A filter expression plus the columns a backend should read for it.
198///
199/// # Example
200///
201/// ```
202/// use crisol_core::data::QueryPlan;
203///
204/// # use crisol_core::data::{Dataset, Query, plan};
205/// let plan = plan(&Query::parse("x > 1").expect("query"), &Dataset::new());
206/// assert_eq!(plan.columns, ["x"]);
207/// ```
208#[non_exhaustive]
209#[derive(Clone, Debug, PartialEq, Eq)]
210pub struct QueryPlan {
211    /// Columns referenced by the filter.
212    pub columns: Vec<String>,
213    /// Rows that pass the filter.
214    pub rows: Vec<usize>,
215}
216
217/// Build a pushdown plan: the backend reads only `columns`, then applies the filter.
218///
219/// # Example
220///
221/// ```
222/// use crisol_core::data::{Dataset, Query, plan};
223///
224/// let data = Dataset::new();
225/// let query = Query::parse("x > 1").expect("query");
226/// assert_eq!(plan(&query, &data).columns, ["x"]);
227/// ```
228pub 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}