Skip to main content

mito_codec/
row_converter.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
15pub mod dense;
16pub mod sparse;
17
18use std::fmt::Debug;
19use std::sync::Arc;
20
21use common_recordbatch::filter::SimpleFilterEvaluator;
22use datatypes::value::{Value, ValueRef};
23pub use dense::{DensePrimaryKeyCodec, SortField};
24pub use sparse::{
25    COLUMN_ID_ENCODE_SIZE, SparseOffsetsCache, SparsePrimaryKeyCodec, SparseValues, TsidGenerator,
26};
27use store_api::codec::PrimaryKeyEncoding;
28use store_api::metadata::{RegionMetadata, RegionMetadataRef};
29use store_api::storage::ColumnId;
30
31use crate::error::Result;
32use crate::key_values::KeyValue;
33
34/// Row value encoder/decoder.
35pub trait PrimaryKeyCodecExt {
36    /// Encodes rows to bytes.
37    /// # Note
38    /// Ensure the length of row iterator matches the length of fields.
39    fn encode<'a, I>(&self, row: I) -> Result<Vec<u8>>
40    where
41        I: Iterator<Item = ValueRef<'a>>,
42    {
43        let mut buffer = Vec::new();
44        self.encode_to_vec(row, &mut buffer)?;
45        Ok(buffer)
46    }
47
48    /// Encodes rows to specific vec.
49    /// # Note
50    /// Ensure the length of row iterator matches the length of fields.
51    fn encode_to_vec<'a, I>(&self, row: I, buffer: &mut Vec<u8>) -> Result<()>
52    where
53        I: Iterator<Item = ValueRef<'a>>;
54}
55
56pub trait PrimaryKeyFilter: Send + Sync {
57    /// Returns true if the primary key matches the filter.
58    fn matches(&mut self, pk: &[u8]) -> Result<bool>;
59}
60
61/// Composite values decoded from primary key bytes.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum CompositeValues {
64    Dense(Vec<(ColumnId, Value)>),
65    Sparse(SparseValues),
66}
67
68impl CompositeValues {
69    /// Extends the composite values with the given values.
70    ///
71    /// Append-only: `values` must not contain a column id already present in
72    /// the composite; otherwise the existing entry would shadow the new one on
73    /// `SparseValues` lookup.
74    pub fn extend(&mut self, values: &[(ColumnId, Value)]) {
75        match self {
76            CompositeValues::Dense(dense_values) => {
77                for (column_id, value) in values {
78                    dense_values.push((*column_id, value.clone()));
79                }
80            }
81            CompositeValues::Sparse(sprase_value) => {
82                for (column_id, value) in values {
83                    sprase_value.insert(*column_id, value.clone());
84                }
85            }
86        }
87    }
88}
89
90#[cfg(any(test, feature = "testing"))]
91impl CompositeValues {
92    pub fn into_sparse(self) -> SparseValues {
93        match self {
94            CompositeValues::Sparse(v) => v,
95            _ => panic!("CompositeValues is not sparse"),
96        }
97    }
98
99    pub fn into_dense(self) -> Vec<Value> {
100        match self {
101            CompositeValues::Dense(v) => v.into_iter().map(|(_, v)| v).collect(),
102            _ => panic!("CompositeValues is not dense"),
103        }
104    }
105}
106
107pub trait PrimaryKeyCodec: Send + Sync + Debug {
108    /// Encodes a key value to bytes.
109    fn encode_key_value(&self, key_value: &KeyValue, buffer: &mut Vec<u8>) -> Result<()>;
110
111    /// Encodes values to bytes.
112    fn encode_values(&self, values: &[(ColumnId, Value)], buffer: &mut Vec<u8>) -> Result<()>;
113
114    /// Encodes values to bytes.
115    fn encode_value_refs(
116        &self,
117        values: &[(ColumnId, ValueRef)],
118        buffer: &mut Vec<u8>,
119    ) -> Result<()>;
120
121    /// Returns the number of fields in the primary key.
122    fn num_fields(&self) -> Option<usize>;
123
124    /// Returns a primary key filter factory.
125    fn primary_key_filter(
126        &self,
127        metadata: &RegionMetadataRef,
128        filters: Arc<Vec<SimpleFilterEvaluator>>,
129    ) -> Box<dyn PrimaryKeyFilter>;
130
131    /// Returns the estimated size of the primary key.
132    fn estimated_size(&self) -> Option<usize> {
133        None
134    }
135
136    /// Returns the encoding type of the primary key.
137    fn encoding(&self) -> PrimaryKeyEncoding;
138
139    /// Returns the dense codec for schema-aware positional access, if applicable.
140    fn as_dense(&self) -> Option<&DensePrimaryKeyCodec> {
141        None
142    }
143
144    /// Decodes the primary key from the given bytes.
145    ///
146    /// Returns a [`CompositeValues`] that follows the primary key ordering.
147    fn decode(&self, bytes: &[u8]) -> Result<CompositeValues>;
148
149    /// Decode the leftmost value from bytes.
150    fn decode_leftmost(&self, bytes: &[u8]) -> Result<Option<Value>>;
151}
152
153/// Builds a primary key codec from region metadata.
154pub fn build_primary_key_codec(region_metadata: &RegionMetadata) -> Arc<dyn PrimaryKeyCodec> {
155    let fields = region_metadata.primary_key_columns().map(|col| {
156        (
157            col.column_id,
158            SortField::new(col.column_schema.data_type.clone()),
159        )
160    });
161    build_primary_key_codec_with_fields(region_metadata.primary_key_encoding, fields)
162}
163
164/// Builds a primary key codec from region metadata.
165pub fn build_primary_key_codec_with_fields(
166    encoding: PrimaryKeyEncoding,
167    fields: impl Iterator<Item = (ColumnId, SortField)>,
168) -> Arc<dyn PrimaryKeyCodec> {
169    match encoding {
170        PrimaryKeyEncoding::Dense => Arc::new(DensePrimaryKeyCodec::with_fields(fields.collect())),
171        PrimaryKeyEncoding::Sparse => {
172            Arc::new(SparsePrimaryKeyCodec::with_fields(fields.collect()))
173        }
174    }
175}
176
177/// Finds the checked boundary of an Option<String>, shared by Dense and Sparse.
178/// This validates framing, not UTF-8; consumers decoding strings validate UTF-8.
179pub(crate) fn encoded_string_len(bytes: &[u8]) -> memcomparable::Result<usize> {
180    encoded_string_info::<false>(bytes).map(|(len, _)| len)
181}
182
183/// Checks string framing and optionally detects ASCII in the same pass.
184/// Framing-only readers compile out payload inspection and ignore the ASCII result.
185pub(crate) fn encoded_string_info<const CHECK_ASCII: bool>(
186    bytes: &[u8],
187) -> memcomparable::Result<(usize, bool)> {
188    match bytes.first().copied().ok_or(memcomparable::Error::Eof)? {
189        0 => return Ok((1, true)),
190        1 => {}
191        marker => return Err(memcomparable::Error::InvalidTagEncoding(marker as usize)),
192    }
193    match bytes.get(1).copied().ok_or(memcomparable::Error::Eof)? {
194        0 => return Ok((2, true)),
195        1 => {}
196        marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)),
197    }
198    let mut ascii_bits = 0_u64;
199    for (index, chunk) in bytes[2..].as_chunks::<9>().0.iter().enumerate() {
200        let [word @ .., marker] = *chunk;
201        if CHECK_ASCII {
202            ascii_bits |= u64::from_ne_bytes(word);
203        }
204        match marker {
205            1..=8 => return Ok((2 + (index + 1) * 9, ascii_bits & 0x8080_8080_8080_8080 == 0)),
206            9 => {}
207            marker => return Err(memcomparable::Error::InvalidBytesEncoding(marker)),
208        }
209    }
210    Err(memcomparable::Error::Eof)
211}