Skip to main content

rudb_vector/
chunk.rs

1//! A batch of columns, which is the unit every operator passes to the next one.
2//!
3//! A chunk is some vectors of the same length plus that length. It is not a table and it is not a
4//! result set: it is at most [`VECTOR_SIZE`] rows, because the whole point of the number in
5//! `spec/04-architecture.md` section 4.3 is that a batch of this width stays in L1 while an
6//! operator works on it, and a type that can hold ten times that many rows is a type that lets an
7//! operator quietly stop being vectorized.
8//!
9//! The row count is stored rather than derived, which matters for the one case that looks like a
10//! mistake and is not. `SELECT count(*) FROM t` scans no columns, so the chunk the scan produces
11//! has no vectors in it and still has to say how many rows went past, and a chunk that derived its
12//! length from its first column would say zero.
13
14use rudb_common::{Error, LogicalType, Result, Value};
15
16use crate::selection::Selection;
17use crate::vector::{VECTOR_SIZE, Vector};
18
19/// A batch of columns of equal length.
20#[derive(Debug, Clone, PartialEq)]
21pub struct Chunk {
22    columns: Vec<Vector>,
23    rows: usize,
24}
25
26impl Chunk {
27    /// A chunk of `columns`, taking the row count from the first of them.
28    ///
29    /// # Errors
30    ///
31    /// If the columns are not all the same length, or if there are more rows than [`VECTOR_SIZE`].
32    pub fn new(columns: Vec<Vector>) -> Result<Self> {
33        let rows = columns.first().map_or(0, Vector::len);
34        Self::with_rows(columns, rows)
35    }
36
37    /// A chunk of `columns` that is `rows` long, for the case where there are no columns to take
38    /// the count from.
39    ///
40    /// # Errors
41    ///
42    /// If any column is not `rows` long, or if `rows` is more than [`VECTOR_SIZE`].
43    pub fn with_rows(columns: Vec<Vector>, rows: usize) -> Result<Self> {
44        if rows > VECTOR_SIZE {
45            return Err(Error::internal(format!(
46                "a chunk of {rows} rows is longer than the {VECTOR_SIZE} row vector"
47            )));
48        }
49        for (index, column) in columns.iter().enumerate() {
50            if column.len() != rows {
51                return Err(Error::internal(format!(
52                    "column {index} of a chunk is {} rows and the chunk is {rows}",
53                    column.len()
54                )));
55            }
56        }
57        Ok(Self { columns, rows })
58    }
59
60    /// A chunk of the given types with no rows in it.
61    ///
62    /// What a scan of an empty table returns and what an operator returns when it is done. The
63    /// types are kept, because a consumer asks a chunk what its columns are before it asks whether
64    /// there are any.
65    #[must_use]
66    pub fn empty(types: &[LogicalType]) -> Self {
67        let columns =
68            types.iter().map(|ty| Vector::constant(ty.clone(), Value::Null, 0)).collect::<Vec<_>>();
69        Self { columns, rows: 0 }
70    }
71
72    /// The columns.
73    #[must_use]
74    pub fn columns(&self) -> &[Vector] {
75        &self.columns
76    }
77
78    /// One column.
79    ///
80    /// # Errors
81    ///
82    /// If there is no column at `index`.
83    pub fn column(&self, index: usize) -> Result<&Vector> {
84        self.columns.get(index).ok_or_else(|| {
85            Error::internal(format!(
86                "column {index} of a chunk that has {} columns",
87                self.columns.len()
88            ))
89        })
90    }
91
92    /// The columns, given up.
93    #[must_use]
94    pub fn into_columns(self) -> Vec<Vector> {
95        self.columns
96    }
97
98    /// How many columns.
99    #[must_use]
100    pub fn width(&self) -> usize {
101        self.columns.len()
102    }
103
104    /// How many rows.
105    #[must_use]
106    pub fn len(&self) -> usize {
107        self.rows
108    }
109
110    /// Whether there are no rows.
111    #[must_use]
112    pub fn is_empty(&self) -> bool {
113        self.rows == 0
114    }
115
116    /// The type of each column.
117    #[must_use]
118    pub fn types(&self) -> Vec<LogicalType> {
119        self.columns.iter().map(|column| column.logical_type().clone()).collect()
120    }
121
122    /// The value at a row and a column, or null if either is past the end.
123    ///
124    /// The slow path, same as [`Vector::value_at`]. It is what a result set is read out with and
125    /// what a test asserts on.
126    #[must_use]
127    pub fn value_at(&self, row: usize, column: usize) -> Value {
128        match self.columns.get(column) {
129            Some(held) => held.value_at(row),
130            None => Value::Null,
131        }
132    }
133
134    /// One row, left to right.
135    pub fn row(&self, row: usize) -> impl Iterator<Item = Value> + '_ {
136        self.columns.iter().map(move |column| column.value_at(row))
137    }
138
139    /// The rows a selection kept, without moving any of the values.
140    ///
141    /// Every column becomes a dictionary vector whose codes are the selection, which is the form
142    /// `spec/07-execution.md` section 7.1 asks a filter to produce rather than compacting. It takes
143    /// the chunk by value because that is what makes it free: the payload is moved into the new
144    /// vector rather than copied, so a filter that keeps one row in a thousand still costs the
145    /// selection and nothing else.
146    ///
147    /// # Errors
148    ///
149    /// If the selection points past the end of the chunk.
150    pub fn select(self, selection: &Selection) -> Result<Self> {
151        if let Some(bad) = selection.iter().find(|&index| index >= self.rows) {
152            return Err(Error::internal(format!(
153                "a selection keeps row {bad} of a chunk that has {} rows",
154                self.rows
155            )));
156        }
157        let rows = selection.len();
158        let codes = selection.indices();
159        let mut columns = Vec::with_capacity(self.columns.len());
160        for column in self.columns {
161            columns.push(Vector::dictionary(codes.to_vec(), column)?);
162        }
163        Self::with_rows(columns, rows)
164    }
165
166    /// The columns at the given positions, in that order.
167    ///
168    /// A position may appear twice, which is what `SELECT x, x FROM t` is, and the second one costs
169    /// a copy. Every other position is moved.
170    ///
171    /// # Errors
172    ///
173    /// If a position is past the end of the chunk.
174    pub fn project(self, positions: &[usize]) -> Result<Self> {
175        let width = self.columns.len();
176        if let Some(&bad) = positions.iter().find(|&&position| position >= width) {
177            return Err(Error::internal(format!(
178                "column {bad} of a chunk that has {width} columns"
179            )));
180        }
181        let rows = self.rows;
182        let mut sources: Vec<Option<Vector>> = self.columns.into_iter().map(Some).collect();
183        let mut columns = Vec::with_capacity(positions.len());
184        for (at, &position) in positions.iter().enumerate() {
185            let last_use = !positions[at + 1..].contains(&position);
186            let taken = if last_use { sources[position].take() } else { sources[position].clone() };
187            match taken {
188                Some(column) => columns.push(column),
189                // Only reachable if the last-use bookkeeping above is wrong, since a position is
190                // taken on its last appearance and cloned on every earlier one.
191                None => {
192                    return Err(Error::internal(format!("column {position} was taken twice")));
193                }
194            }
195        }
196        Self::with_rows(columns, rows)
197    }
198
199    /// The same rows with every column in flat form.
200    ///
201    /// Costs a copy per column that was not already flat. It is here for the result set at the top
202    /// of a query, where the dictionary vectors a filter left behind would otherwise be handed to a
203    /// caller who has to understand them.
204    ///
205    /// # Errors
206    ///
207    /// If a column has a type that cannot be stored flat yet, which today means the nested types.
208    pub fn flatten(&self) -> Result<Self> {
209        let mut columns = Vec::with_capacity(self.columns.len());
210        for column in &self.columns {
211            columns.push(column.flatten()?);
212        }
213        Self::with_rows(columns, self.rows)
214    }
215}
216
217#[cfg(test)]
218mod tests {
219    use rudb_common::LogicalType;
220
221    use super::*;
222    use crate::vector::{Data, Form};
223
224    fn integers(values: &[i32]) -> Vector {
225        Vector::flat(LogicalType::Integer, Data::Int32(values.to_vec()))
226            .expect("integers are an i32 layout")
227    }
228
229    #[test]
230    fn a_chunk_takes_its_length_from_its_columns() {
231        let chunk = Chunk::new(vec![integers(&[1, 2, 3]), integers(&[4, 5, 6])])
232            .expect("two columns of three");
233        assert_eq!(chunk.len(), 3);
234        assert_eq!(chunk.width(), 2);
235        assert_eq!(chunk.value_at(2, 1), Value::Integer(6));
236    }
237
238    #[test]
239    fn a_ragged_chunk_is_caught() {
240        let error = Chunk::new(vec![integers(&[1, 2, 3]), integers(&[4])])
241            .expect_err("a chunk is not ragged");
242        assert!(error.message().contains("column 1"), "{error}");
243    }
244
245    /// `SELECT count(*) FROM t` scans no columns and the row count still has to survive, which is
246    /// the reason the length is a field rather than the first column's length.
247    #[test]
248    fn a_chunk_with_no_columns_can_still_have_rows() {
249        let chunk = Chunk::with_rows(Vec::new(), 900).expect("no columns and nine hundred rows");
250        assert_eq!(chunk.len(), 900);
251        assert_eq!(chunk.width(), 0);
252        assert!(!chunk.is_empty(), "nine hundred rows is not empty");
253    }
254
255    #[test]
256    fn a_chunk_longer_than_a_vector_is_caught() {
257        let error = Chunk::with_rows(Vec::new(), VECTOR_SIZE + 1).expect_err("too long");
258        assert!(error.message().contains("longer than"), "{error}");
259    }
260
261    #[test]
262    fn an_empty_chunk_keeps_its_types() {
263        let chunk = Chunk::empty(&[LogicalType::Integer, LogicalType::Varchar]);
264        assert_eq!(chunk.len(), 0);
265        assert_eq!(chunk.types(), vec![LogicalType::Integer, LogicalType::Varchar]);
266    }
267
268    #[test]
269    fn selecting_keeps_the_rows_it_selected_and_no_others() {
270        let chunk = Chunk::new(vec![integers(&[10, 20, 30, 40]), integers(&[1, 2, 3, 4])])
271            .expect("four rows");
272        let kept = Selection::from_predicate(4, |index| index % 2 == 1);
273        let chunk = chunk.select(&kept).expect("rows one and three exist");
274        assert_eq!(chunk.len(), 2);
275        assert_eq!(chunk.row(0).collect::<Vec<_>>(), vec![Value::Integer(20), Value::Integer(2)]);
276        assert_eq!(chunk.row(1).collect::<Vec<_>>(), vec![Value::Integer(40), Value::Integer(4)]);
277    }
278
279    /// The reason `select` takes the chunk by value. If it copied the payload then a filter would
280    /// cost the same as a compaction and the selection would be a pure loss.
281    #[test]
282    fn selecting_leaves_the_values_where_they_were() {
283        let chunk = Chunk::new(vec![integers(&[10, 20, 30, 40])]).expect("four rows");
284        let kept = Selection::from_predicate(4, |index| index == 0);
285        let chunk = chunk.select(&kept).expect("row zero exists");
286        assert_eq!(chunk.column(0).expect("one column").form(), Form::Dictionary);
287    }
288
289    #[test]
290    fn a_selection_past_the_end_is_caught() {
291        let chunk = Chunk::new(vec![integers(&[1, 2])]).expect("two rows");
292        let mut kept = Selection::empty();
293        kept.push(7);
294        let error = chunk.select(&kept).expect_err("row seven does not exist");
295        assert!(error.message().contains("row 7"), "{error}");
296    }
297
298    #[test]
299    fn projecting_reorders_and_can_repeat_a_column() {
300        let chunk = Chunk::new(vec![integers(&[1, 2]), integers(&[3, 4])]).expect("two by two");
301        let chunk = chunk.project(&[1, 0, 1]).expect("both columns exist");
302        assert_eq!(chunk.width(), 3);
303        assert_eq!(
304            chunk.row(0).collect::<Vec<_>>(),
305            vec![Value::Integer(3), Value::Integer(1), Value::Integer(3)]
306        );
307    }
308
309    #[test]
310    fn projecting_a_column_that_is_not_there_is_caught() {
311        let chunk = Chunk::new(vec![integers(&[1, 2])]).expect("one column");
312        let error = chunk.project(&[0, 4]).expect_err("there is no column four");
313        assert!(error.message().contains("column 4"), "{error}");
314    }
315
316    #[test]
317    fn flattening_a_selected_chunk_gives_the_same_values() {
318        let chunk = Chunk::new(vec![integers(&[10, 20, 30])]).expect("three rows");
319        let kept = Selection::from_predicate(3, |index| index != 1);
320        let selected = chunk.select(&kept).expect("rows zero and two exist");
321        let flat = selected.flatten().expect("integers flatten");
322        assert_eq!(flat.column(0).expect("one column").form(), Form::Flat);
323        for row in 0..flat.len() {
324            assert_eq!(flat.value_at(row, 0), selected.value_at(row, 0), "row {row}");
325        }
326    }
327}