Skip to main content

liquid_cache_storage/liquid_array/
mod.rs

1//! LiquidArray is the core data structure of LiquidCache.
2//! You should not use this module directly.
3//! Instead, use `liquid_cache_server` or `liquid_cache_client` to interact with LiquidCache.
4mod byte_array;
5pub mod byte_view_array;
6mod fix_len_byte_array;
7mod float_array;
8mod hybrid_primitive_array;
9pub mod ipc;
10mod linear_integer_array;
11mod primitive_array;
12pub mod raw;
13mod squeezed_date32_array;
14#[cfg(test)]
15mod tests;
16pub(crate) mod utils;
17
18use std::{any::Any, ops::Range, sync::Arc};
19
20use arrow::{
21    array::{ArrayRef, BooleanArray},
22    buffer::BooleanBuffer,
23};
24use arrow_schema::DataType;
25pub use byte_array::{LiquidByteArray, get_string_needle};
26pub use byte_view_array::LiquidByteViewArray;
27use datafusion::logical_expr::Operator as DFOperator;
28use datafusion::physical_plan::PhysicalExpr;
29pub use fix_len_byte_array::LiquidFixedLenByteArray;
30use float_array::LiquidFloatType;
31pub use float_array::{LiquidFloat32Array, LiquidFloat64Array, LiquidFloatArray};
32pub use linear_integer_array::{
33    LiquidLinearArray, LiquidLinearDate32Array, LiquidLinearDate64Array, LiquidLinearI8Array,
34    LiquidLinearI16Array, LiquidLinearI32Array, LiquidLinearI64Array, LiquidLinearU8Array,
35    LiquidLinearU16Array, LiquidLinearU32Array, LiquidLinearU64Array,
36};
37pub use primitive_array::IntegerSqueezePolicy;
38pub use primitive_array::{
39    LiquidDate32Array, LiquidDate64Array, LiquidI8Array, LiquidI16Array, LiquidI32Array,
40    LiquidI64Array, LiquidPrimitiveArray, LiquidPrimitiveDeltaArray, LiquidPrimitiveType,
41    LiquidU8Array, LiquidU16Array, LiquidU32Array, LiquidU64Array,
42};
43pub use squeezed_date32_array::{Date32Field, SqueezedDate32Array};
44
45use crate::liquid_array::byte_view_array::MemoryBuffer;
46
47/// Liquid data type is only logical type
48#[derive(Debug, Clone, Copy)]
49#[repr(u16)]
50pub enum LiquidDataType {
51    /// A byte array.
52    ByteArray = 0,
53    /// A byte-view array (dictionary + FSST raw + views).
54    ByteViewArray = 4,
55    /// An integer.
56    Integer = 1,
57    /// A float.
58    Float = 2,
59    /// A fixed length byte array.
60    FixedLenByteArray = 3,
61    /// A linear-model based integer (signed residuals + model params).
62    LinearInteger = 5,
63}
64
65impl From<u16> for LiquidDataType {
66    fn from(value: u16) -> Self {
67        match value {
68            0 => LiquidDataType::ByteArray,
69            4 => LiquidDataType::ByteViewArray,
70            1 => LiquidDataType::Integer,
71            2 => LiquidDataType::Float,
72            3 => LiquidDataType::FixedLenByteArray,
73            5 => LiquidDataType::LinearInteger,
74            _ => panic!("Invalid liquid data type: {value}"),
75        }
76    }
77}
78
79/// A trait to access the underlying Liquid array.
80pub trait AsLiquidArray {
81    /// Get the underlying string array.
82    fn as_string_array_opt(&self) -> Option<&LiquidByteArray>;
83
84    /// Get the underlying string array.
85    fn as_string(&self) -> &LiquidByteArray {
86        self.as_string_array_opt().expect("liquid string array")
87    }
88
89    /// Get the underlying binary array.
90    fn as_binary_array_opt(&self) -> Option<&LiquidByteArray>;
91
92    /// Get the underlying binary array.
93    fn as_binary(&self) -> &LiquidByteArray {
94        self.as_binary_array_opt().expect("liquid binary array")
95    }
96
97    /// Get the underlying byte view array.
98    fn as_byte_view_array_opt(&self) -> Option<&LiquidByteViewArray<MemoryBuffer>>;
99
100    /// Get the underlying byte view array.
101    fn as_byte_view(&self) -> &LiquidByteViewArray<MemoryBuffer> {
102        self.as_byte_view_array_opt()
103            .expect("liquid byte view array")
104    }
105
106    /// Get the underlying primitive array.
107    fn as_primitive_array_opt<T: LiquidPrimitiveType>(&self) -> Option<&LiquidPrimitiveArray<T>>;
108
109    /// Get the underlying primitive array.
110    fn as_primitive<T: LiquidPrimitiveType>(&self) -> &LiquidPrimitiveArray<T> {
111        self.as_primitive_array_opt()
112            .expect("liquid primitive array")
113    }
114
115    /// Get the underlying float array.
116    fn as_float_array_opt<T: LiquidFloatType>(&self) -> Option<&LiquidFloatArray<T>>;
117
118    /// Get the underlying float array.
119    fn as_float<T: LiquidFloatType>(&self) -> &LiquidFloatArray<T> {
120        self.as_float_array_opt().expect("liquid float array")
121    }
122}
123
124impl AsLiquidArray for dyn LiquidArray + '_ {
125    fn as_string_array_opt(&self) -> Option<&LiquidByteArray> {
126        self.as_any().downcast_ref()
127    }
128
129    fn as_primitive_array_opt<T: LiquidPrimitiveType>(&self) -> Option<&LiquidPrimitiveArray<T>> {
130        self.as_any().downcast_ref()
131    }
132
133    fn as_binary_array_opt(&self) -> Option<&LiquidByteArray> {
134        self.as_any().downcast_ref()
135    }
136
137    fn as_byte_view_array_opt(&self) -> Option<&LiquidByteViewArray<MemoryBuffer>> {
138        self.as_any().downcast_ref()
139    }
140
141    fn as_float_array_opt<T: LiquidFloatType>(&self) -> Option<&LiquidFloatArray<T>> {
142        self.as_any().downcast_ref()
143    }
144}
145
146/// A Liquid array.
147pub trait LiquidArray: std::fmt::Debug + Send + Sync {
148    /// Get the underlying any type.
149    fn as_any(&self) -> &dyn Any;
150
151    /// Get the memory size of the Liquid array.
152    fn get_array_memory_size(&self) -> usize;
153
154    /// Get the length of the Liquid array.
155    fn len(&self) -> usize;
156
157    /// Check if the Liquid array is empty.
158    fn is_empty(&self) -> bool {
159        self.len() == 0
160    }
161
162    /// Convert the Liquid array to an Arrow array.
163    fn to_arrow_array(&self) -> ArrayRef;
164
165    /// Convert the Liquid array to an Arrow array.
166    /// Except that it will pick the best encoding for the arrow array.
167    /// Meaning that it may not obey the data type of the original arrow array.
168    fn to_best_arrow_array(&self) -> ArrayRef {
169        self.to_arrow_array()
170    }
171
172    /// Get the logical data type of the Liquid array.
173    fn data_type(&self) -> LiquidDataType;
174
175    /// Get the original arrow data type of the Liquid array.
176    fn original_arrow_data_type(&self) -> DataType;
177
178    /// Serialize the Liquid array to a byte array.
179    fn to_bytes(&self) -> Vec<u8>;
180
181    /// Filter the Liquid array with a boolean buffer.
182    fn filter(&self, selection: &BooleanBuffer) -> LiquidArrayRef;
183
184    /// Filter the Liquid array with a boolean array and return an **arrow array**.
185    fn filter_to_arrow(&self, selection: &BooleanBuffer) -> ArrayRef {
186        let filtered = self.filter(selection);
187        filtered.to_arrow_array()
188    }
189
190    /// Try to evaluate a predicate on the Liquid array with a filter.
191    /// Returns `None` if the predicate is not supported.
192    ///
193    /// Note that the filter is a boolean buffer, not a boolean array, i.e., filter can't be nullable.
194    /// The returned boolean mask is nullable if the the original array is nullable.
195    fn try_eval_predicate(
196        &self,
197        _predicate: &Arc<dyn PhysicalExpr>,
198        _filter: &BooleanBuffer,
199    ) -> Option<BooleanArray> {
200        None
201    }
202
203    /// Squeeze the Liquid array to a `LiquidHybridArrayRef` and a `bytes::Bytes`.
204    /// Return `None` if the Liquid array cannot be squeezed.
205    ///
206    /// This is the bridge from in-memory array to hybrid array.
207    /// Important: The returned `Bytes` is the data that is stored on disk, it is the same as to_bytes().
208    ///
209    /// If we `soak` the `LiquidHybridArrayRef` back with the bytes, we should get the same `LiquidArray`.
210    fn squeeze(&self) -> Option<(LiquidHybridArrayRef, bytes::Bytes)> {
211        None
212    }
213}
214
215/// A reference to a Liquid array.
216pub type LiquidArrayRef = Arc<dyn LiquidArray>;
217
218/// A reference to a Liquid hybrid array.
219pub type LiquidHybridArrayRef = Arc<dyn LiquidHybridArray>;
220
221/// A range of bytes on disk.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct IoRange {
224    range: Range<u64>,
225}
226
227impl IoRange {
228    /// Get the range of bytes on disk.
229    pub fn range(&self) -> &Range<u64> {
230        &self.range
231    }
232}
233
234enum Operator {
235    Eq,
236    NotEq,
237    Lt,
238    LtEq,
239    Gt,
240    GtEq,
241}
242
243impl Operator {
244    fn from_datafusion(op: &DFOperator) -> Option<Self> {
245        let op = match op {
246            DFOperator::Eq => Operator::Eq,
247            DFOperator::NotEq => Operator::NotEq,
248            DFOperator::Lt => Operator::Lt,
249            DFOperator::LtEq => Operator::LtEq,
250            DFOperator::Gt => Operator::Gt,
251            DFOperator::GtEq => Operator::GtEq,
252            _ => return None,
253        };
254        Some(op)
255    }
256}
257
258/// A Liquid hybrid array is a Liquid array that part of its data is stored on disk.
259/// `LiquidHybridArray` is more complex than in-memory `LiquidArray` because it needs to handle IO.
260pub trait LiquidHybridArray: std::fmt::Debug + Send + Sync {
261    /// Get the underlying any type.
262    fn as_any(&self) -> &dyn Any;
263
264    /// Get the memory size of the Liquid array.
265    fn get_array_memory_size(&self) -> usize;
266
267    /// Get the length of the Liquid array.
268    fn len(&self) -> usize;
269
270    /// Check if the Liquid array is empty.
271    fn is_empty(&self) -> bool {
272        self.len() == 0
273    }
274
275    /// Convert the Liquid array to an Arrow array.
276    fn to_arrow_array(&self) -> Result<ArrayRef, IoRange>;
277
278    /// Convert the Liquid array to an Arrow array.
279    /// Except that it will pick the best encoding for the arrow array.
280    /// Meaning that it may not obey the data type of the original arrow array.
281    fn to_best_arrow_array(&self) -> Result<ArrayRef, IoRange> {
282        self.to_arrow_array()
283    }
284
285    /// Get the logical data type of the Liquid array.
286    fn data_type(&self) -> LiquidDataType;
287
288    /// Get the original arrow data type of the Liquid hybrid array.
289    fn original_arrow_data_type(&self) -> DataType;
290
291    /// Serialize the Liquid array to a byte array.
292    fn to_bytes(&self) -> Result<Vec<u8>, IoRange>;
293
294    /// Filter the Liquid array with a boolean buffer.
295    fn filter(&self, selection: &BooleanBuffer) -> Result<LiquidHybridArrayRef, IoRange>;
296
297    /// Filter the Liquid array with a boolean array and return an **arrow array**.
298    fn filter_to_arrow(&self, selection: &BooleanBuffer) -> Result<ArrayRef, IoRange> {
299        let filtered = self.filter(selection)?;
300        filtered.to_best_arrow_array()
301    }
302
303    /// Try to evaluate a predicate on the Liquid array with a filter.
304    /// Returns `Ok(None)` if the predicate is not supported.
305    ///
306    /// Note that the filter is a boolean buffer, not a boolean array, i.e., filter can't be nullable.
307    /// The returned boolean mask is nullable if the the original array is nullable.
308    fn try_eval_predicate(
309        &self,
310        _predicate: &Arc<dyn PhysicalExpr>,
311        _filter: &BooleanBuffer,
312    ) -> Result<Option<BooleanArray>, IoRange> {
313        Ok(None)
314    }
315
316    /// Feed IO data to the `LiquidHybridArray` and return the in-memory `LiquidArray`.
317    /// For byte-view arrays, `data` should be the raw FSST buffer bytes.
318    fn soak(&self, data: bytes::Bytes) -> LiquidArrayRef;
319
320    /// Get the `IoRange` to convert the `LiquidHybridArray` to a `LiquidArray`.
321    fn to_liquid(&self) -> IoRange;
322}
323
324/// Compile-time info about primitive kind (signed vs unsigned) and bounds.
325/// Implemented for all Liquid-supported primitive integer and date types.
326pub trait PrimitiveKind {
327    /// Whether the logical type is unsigned (true for u8/u16/u32/u64).
328    const IS_UNSIGNED: bool;
329    /// Maximum representable value as u64 for unsigned types (unused for signed).
330    const MAX_U64: u64;
331    /// Minimum representable value as i64 for signed/date types (unused for unsigned).
332    const MIN_I64: i64;
333    /// Maximum representable value as i64 for signed/date types (unused for unsigned).
334    const MAX_I64: i64;
335}
336
337macro_rules! impl_unsigned_kind {
338    ($t:ty, $max:expr) => {
339        impl PrimitiveKind for $t {
340            const IS_UNSIGNED: bool = true;
341            const MAX_U64: u64 = $max as u64;
342            const MIN_I64: i64 = 0; // unused
343            const MAX_I64: i64 = 0; // unused
344        }
345    };
346}
347
348macro_rules! impl_signed_kind {
349    ($t:ty, $min:expr, $max:expr) => {
350        impl PrimitiveKind for $t {
351            const IS_UNSIGNED: bool = false;
352            const MAX_U64: u64 = 0; // unused
353            const MIN_I64: i64 = $min as i64;
354            const MAX_I64: i64 = $max as i64;
355        }
356    };
357}
358
359use arrow::datatypes::{
360    Date32Type, Date64Type, Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type, UInt16Type,
361    UInt32Type, UInt64Type,
362};
363
364impl_unsigned_kind!(UInt8Type, u8::MAX);
365impl_unsigned_kind!(UInt16Type, u16::MAX);
366impl_unsigned_kind!(UInt32Type, u32::MAX);
367impl_unsigned_kind!(UInt64Type, u64::MAX);
368
369impl_signed_kind!(Int8Type, i8::MIN, i8::MAX);
370impl_signed_kind!(Int16Type, i16::MIN, i16::MAX);
371impl_signed_kind!(Int32Type, i32::MIN, i32::MAX);
372impl_signed_kind!(Int64Type, i64::MIN, i64::MAX);
373
374// Dates are logically signed in Arrow (Date32: i32 days, Date64: i64 ms)
375impl_signed_kind!(Date32Type, i32::MIN, i32::MAX);
376impl_signed_kind!(Date64Type, i64::MIN, i64::MAX);