Skip to main content

mito2/sst/index/
primary_key.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use datatypes::arrow::array::{Array, BinaryArray};
16use datatypes::arrow::record_batch::RecordBatch;
17use snafu::{OptionExt, ensure};
18
19use crate::error::{InvalidRecordBatchSnafu, Result};
20use crate::sst::parquet::flat_format::primary_key_column_index;
21use crate::sst::parquet::format::PrimaryKeyArray;
22
23/// Iterates consecutive dictionary-key runs, preserving their row order without decoding.
24pub struct PrimaryKeyRuns<'a> {
25    keys: &'a [u32],
26    values: &'a BinaryArray,
27}
28
29impl<'a> PrimaryKeyRuns<'a> {
30    /// Borrows the encoded primary keys of a flat batch without decoding values.
31    pub fn try_new(batch: &'a RecordBatch) -> Result<Self> {
32        let pk = batch
33            .column(primary_key_column_index(batch.num_columns()))
34            .as_any()
35            .downcast_ref::<PrimaryKeyArray>()
36            .context(InvalidRecordBatchSnafu {
37                reason: "Primary key column is not a dictionary array",
38            })?;
39        let values = pk.values().as_any().downcast_ref::<BinaryArray>().context(
40            InvalidRecordBatchSnafu {
41                reason: "Primary key values are not binary array",
42            },
43        )?;
44        ensure!(
45            pk.null_count() == 0 && values.null_count() == 0,
46            InvalidRecordBatchSnafu {
47                reason: "Primary keys must not be null"
48            }
49        );
50        Ok(Self {
51            keys: pk.keys().values(),
52            values,
53        })
54    }
55}
56
57impl<'a> Iterator for PrimaryKeyRuns<'a> {
58    type Item = (&'a [u8], usize);
59
60    fn next(&mut self) -> Option<Self::Item> {
61        let &key = self.keys.first()?;
62        let count = self
63            .keys
64            .iter()
65            .take_while(|&&current| current == key)
66            .count();
67        self.keys = &self.keys[count..];
68        Some((self.values.value(key as usize), count))
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use std::sync::Arc;
75
76    use datatypes::arrow::array::{ArrayRef, BinaryDictionaryBuilder, UInt8Array};
77    use datatypes::arrow::datatypes::UInt32Type;
78
79    use super::*;
80
81    #[test]
82    fn sliced_runs_preserve_order_and_nonconsecutive_keys() {
83        let mut keys = BinaryDictionaryBuilder::<UInt32Type>::new();
84        for key in ["a", "a", "b", "b", "b", "a", "c"] {
85            keys.append(key).unwrap();
86        }
87        let batch = RecordBatch::try_from_iter([
88            ("pk", Arc::new(keys.finish()) as ArrayRef),
89            ("seq", Arc::new(UInt8Array::from(vec![0; 7])) as ArrayRef),
90            ("op", Arc::new(UInt8Array::from(vec![0; 7])) as ArrayRef),
91        ])
92        .unwrap();
93        let slice = batch.slice(1, 5);
94        assert_eq!(
95            PrimaryKeyRuns::try_new(&slice).unwrap().collect::<Vec<_>>(),
96            vec![
97                (b"a".as_slice(), 1),
98                (b"b".as_slice(), 3),
99                (b"a".as_slice(), 1)
100            ]
101        );
102        assert!(
103            PrimaryKeyRuns::try_new(&batch.slice(0, 0))
104                .unwrap()
105                .next()
106                .is_none()
107        );
108    }
109}