feldera_types/variant.rs
1//! [`VariantValue`]: an owned, engine-neutral representation of SQL `VARIANT`.
2//!
3//! * Structurally equivalent to the Parquet variant type.
4//! * Straightforward mapping to both sqllib representations of the Feldera SQL VARIANT.
5//! * Mutable: new attributes can be added without reencoding the entire binary value.
6//!
7//! ```
8//! use std::collections::BTreeMap;
9//! use feldera_types::variant::{VariantDecimal8, VariantValue};
10//!
11//! let attributes = VariantValue::Object(BTreeMap::from([
12//! ("kafka_topic".to_string(), VariantValue::String("events".into())),
13//! ("kafka_offset".to_string(), VariantValue::Int64(17)),
14//! ("price".to_string(), VariantValue::Decimal8(VariantDecimal8::try_new(12345, 2)?)),
15//! ]));
16//! let VariantValue::Object(fields) = &attributes else {
17//! unreachable!()
18//! };
19//! assert_eq!(fields["kafka_offset"], VariantValue::Int64(17));
20//! # Ok::<(), feldera_types::variant::VariantDecimalError>(())
21//! ```
22
23use std::collections::BTreeMap;
24
25use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, Utc};
26use thiserror::Error as ThisError;
27use uuid::Uuid;
28
29/// An owned `VARIANT` value whose types mirror the Parquet variant encoding.
30///
31/// The arms match the encoding's type set one for one.
32#[derive(Clone, Debug, PartialEq)]
33pub enum VariantValue {
34 /// The null variant, which is a present value, not a SQL NULL.
35 Null,
36 Boolean(bool),
37 Int8(i8),
38 Int16(i16),
39 Int32(i32),
40 Int64(i64),
41 Float(f32),
42 Double(f64),
43 Decimal4(VariantDecimal4),
44 Decimal8(VariantDecimal8),
45 Decimal16(VariantDecimal16),
46 String(String),
47 Binary(Vec<u8>),
48 Date(NaiveDate),
49 Time(NaiveTime),
50 /// A zoned timestamp, microsecond precision.
51 TimestampMicros(DateTime<Utc>),
52 /// An unzoned timestamp, microsecond precision.
53 TimestampNtzMicros(NaiveDateTime),
54 /// A zoned timestamp, nanosecond precision.
55 TimestampNanos(DateTime<Utc>),
56 /// An unzoned timestamp, nanosecond precision.
57 TimestampNtzNanos(NaiveDateTime),
58 Uuid(Uuid),
59 List(Vec<VariantValue>),
60 /// Object field names are strings: that is what the encoding permits.
61 Object(BTreeMap<String, VariantValue>),
62}
63
64/// Error creating a decimal value.
65#[derive(Clone, Debug, PartialEq, Eq, ThisError)]
66pub enum VariantDecimalError {
67 #[error("the scale {scale} is larger than the maximum precision {max_precision}")]
68 ScaleTooLarge { scale: u8, max_precision: u8 },
69 #[error("{integer} has more digits than the maximum precision {max_precision}")]
70 TooManyDigits { integer: i128, max_precision: u8 },
71}
72
73/// Defines one of the three decimal types of the Parquet variant encoding: `decimal4`,
74/// `decimal8`, or `decimal16`. The encoding stores the value as a one-byte scale, then
75/// the unscaled integer in 4, 8, or 16 little-endian bytes. The struct holds the same
76/// two fields, with `$native` (`i32`, `i64`, or `i128`) as the integer type.
77///
78/// `$max_precision` is the maximum number of digits for the width: 9, 18, or 38. `try_new`
79/// applies the same limits as `parquet_variant::VariantDecimal4::try_new` and the other two
80/// widths: the scale is at most `$max_precision`, and the integer has at most that many
81/// digits. Thus a value converts to the Parquet decimal of the same width, and back, without
82/// an error. As in the Parquet types, there is no lower limit: a value that fits a narrower
83/// width is also valid in a wider one.
84macro_rules! variant_decimal {
85 ($(#[$doc:meta])* $name:ident, $native:ty, $max_precision:expr) => {
86 $(#[$doc])*
87 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
88 pub struct $name {
89 integer: $native,
90 scale: u8,
91 }
92
93 impl $name {
94 /// The most digits the unscaled integer can have.
95 pub const MAX_PRECISION: u8 = $max_precision;
96
97 /// The decimal `integer * 10^-scale`. Fails if `integer` has more than
98 /// [`Self::MAX_PRECISION`] digits or `scale` is larger than it: the bounds the
99 /// Parquet variant encoding sets, so the decimal always encodes.
100 pub fn try_new(integer: $native, scale: u8) -> Result<Self, VariantDecimalError> {
101 let max_precision = Self::MAX_PRECISION;
102 if scale > max_precision {
103 return Err(VariantDecimalError::ScaleTooLarge {
104 scale,
105 max_precision,
106 });
107 }
108 let max_integer = <$native>::pow(10, max_precision as u32) - 1;
109 if !(-max_integer..=max_integer).contains(&integer) {
110 return Err(VariantDecimalError::TooManyDigits {
111 integer: integer as i128,
112 max_precision,
113 });
114 }
115 Ok(Self { integer, scale })
116 }
117
118 /// The unscaled integer: `12345` for `123.45`.
119 pub fn integer(&self) -> $native {
120 self.integer
121 }
122
123 /// The number of digits after the decimal point: `2` for `123.45`.
124 pub fn scale(&self) -> u8 {
125 self.scale
126 }
127 }
128 };
129}
130
131variant_decimal!(
132 /// A decimal of at most 9 digits, the Parquet variant's 4-byte decimal.
133 ///
134 /// ```
135 /// use feldera_types::variant::VariantDecimal4;
136 ///
137 /// let price = VariantDecimal4::try_new(12345, 2)?;
138 /// assert_eq!((price.integer(), price.scale()), (12345, 2));
139 /// assert!(VariantDecimal4::try_new(1_000_000_000, 0).is_err());
140 /// assert!(VariantDecimal4::try_new(1, 10).is_err());
141 /// # Ok::<(), feldera_types::variant::VariantDecimalError>(())
142 /// ```
143 VariantDecimal4,
144 i32,
145 9
146);
147
148variant_decimal!(
149 /// A decimal of at most 18 digits, the Parquet variant's 8-byte decimal.
150 ///
151 /// ```
152 /// use feldera_types::variant::VariantDecimal8;
153 ///
154 /// let price = VariantDecimal8::try_new(123_456_789_012, 6)?;
155 /// assert_eq!((price.integer(), price.scale()), (123_456_789_012, 6));
156 /// assert!(VariantDecimal8::try_new(1_000_000_000_000_000_000, 0).is_err());
157 /// # Ok::<(), feldera_types::variant::VariantDecimalError>(())
158 /// ```
159 VariantDecimal8,
160 i64,
161 18
162);
163
164variant_decimal!(
165 /// A decimal of at most 38 digits, the Parquet variant's 16-byte decimal.
166 ///
167 /// ```
168 /// use feldera_types::variant::VariantDecimal16;
169 ///
170 /// let price = VariantDecimal16::try_new(12_345_678_901_234_567_890, 8)?;
171 /// assert_eq!(price.scale(), 8);
172 /// assert!(VariantDecimal16::try_new(i128::MAX, 0).is_err());
173 /// # Ok::<(), feldera_types::variant::VariantDecimalError>(())
174 /// ```
175 VariantDecimal16,
176 i128,
177 38
178);
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 /// Each decimal width accepts exactly the integers and scales its precision allows.
185 #[test]
186 fn decimals_keep_the_parquet_bounds() {
187 assert!(VariantDecimal4::try_new(999_999_999, 9).is_ok());
188 assert!(VariantDecimal4::try_new(-999_999_999, 0).is_ok());
189 assert_eq!(
190 VariantDecimal4::try_new(1_000_000_000, 0),
191 Err(VariantDecimalError::TooManyDigits {
192 integer: 1_000_000_000,
193 max_precision: 9
194 })
195 );
196 assert_eq!(
197 VariantDecimal4::try_new(-1_000_000_000, 0),
198 Err(VariantDecimalError::TooManyDigits {
199 integer: -1_000_000_000,
200 max_precision: 9
201 })
202 );
203 assert_eq!(
204 VariantDecimal4::try_new(1, 10),
205 Err(VariantDecimalError::ScaleTooLarge {
206 scale: 10,
207 max_precision: 9
208 })
209 );
210
211 assert!(VariantDecimal8::try_new(999_999_999_999_999_999, 18).is_ok());
212 assert!(VariantDecimal8::try_new(1_000_000_000_000_000_000, 0).is_err());
213 assert!(VariantDecimal8::try_new(1, 19).is_err());
214
215 let max16 = 10i128.pow(38) - 1;
216 assert!(VariantDecimal16::try_new(max16, 38).is_ok());
217 assert!(VariantDecimal16::try_new(-max16, 0).is_ok());
218 assert!(VariantDecimal16::try_new(max16 + 1, 0).is_err());
219 assert!(VariantDecimal16::try_new(i128::MIN, 0).is_err());
220 assert!(VariantDecimal16::try_new(1, 39).is_err());
221 }
222
223 /// The errors name the bound the decimal broke.
224 #[test]
225 fn decimal_errors_name_the_bound() {
226 assert_eq!(
227 VariantDecimal4::try_new(1, 10).unwrap_err().to_string(),
228 "the scale 10 is larger than the maximum precision 9"
229 );
230 assert_eq!(
231 VariantDecimal8::try_new(-1_000_000_000_000_000_000, 0)
232 .unwrap_err()
233 .to_string(),
234 "-1000000000000000000 has more digits than the maximum precision 18"
235 );
236 }
237}