1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::cmp::Ordering;
use std::fmt;
use num_traits::ToPrimitive as NumToPrimitive;
use vortex_dtype::DType;
use vortex_dtype::DecimalDType;
use vortex_dtype::PType;
use vortex_dtype::match_each_decimal_value;
use vortex_error::VortexError;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_err;
use vortex_error::vortex_panic;
use crate::DecimalValue;
use crate::InnerScalarValue;
use crate::NumericOperator;
use crate::Scalar;
use crate::ScalarValue;
/// A scalar value representing a decimal number with fixed precision and scale.
#[derive(Debug, Clone, Copy, Hash)]
pub struct DecimalScalar<'a> {
pub(super) dtype: &'a DType,
pub(super) decimal_type: DecimalDType,
pub(super) value: Option<DecimalValue>,
}
impl<'a> DecimalScalar<'a> {
/// Creates a new decimal scalar from a data type and scalar value.
///
/// # Errors
///
/// Returns an error if the data type is not a decimal type.
pub fn try_new(dtype: &'a DType, value: &ScalarValue) -> VortexResult<Self> {
let decimal_type = DecimalDType::try_from(dtype)?;
let value = value.as_decimal()?;
Ok(Self {
dtype,
decimal_type,
value,
})
}
/// Returns the data type of this decimal scalar.
#[inline]
pub fn dtype(&self) -> &'a DType {
self.dtype
}
/// Returns the decimal value, or None if null.
pub fn decimal_value(&self) -> Option<DecimalValue> {
self.value
}
/// Cast decimal scalar to another data type.
pub(crate) fn cast(&self, dtype: &DType) -> VortexResult<Scalar> {
match dtype {
DType::Decimal(target_dtype, target_nullability) => {
// Cast between decimal types
if self.decimal_type == *target_dtype {
// Same decimal type, just change nullability if needed
return Ok(Scalar::new(
dtype.clone(),
ScalarValue(InnerScalarValue::Decimal(
self.value.unwrap_or(DecimalValue::I128(0)),
)),
));
}
// Different precision/scale - need to implement scaling logic
// For now, we'll do a simple value preservation without scaling
// TODO: Implement proper decimal scaling logic
if let Some(value) = &self.value {
Ok(Scalar::decimal(*value, *target_dtype, *target_nullability))
} else {
Ok(Scalar::null(dtype.clone()))
}
}
DType::Primitive(ptype, nullability) => {
// Cast decimal to primitive type
if let Some(decimal_value) = &self.value {
// Convert decimal value to primitive, accounting for scale
let scale_factor = 10_i128.pow(self.decimal_type.scale() as u32);
// Convert to i128 for calculation
let scaled_value = match_each_decimal_value!(decimal_value, |v| {
NumToPrimitive::to_i128(v).ok_or_else(|| {
vortex_err!("Decimal value too large to cast to primitive")
})
})?;
// Apply scale to get the actual value.
let actual_value = scaled_value as f64 / scale_factor as f64;
// Cast to target primitive type. Note that the `as` keyword does **MORE** than
// a simple bitcast / memory transmuation.
#[expect(
clippy::cast_possible_truncation,
reason = "truncation is intentional - range checks happen after"
)]
let primitive_scalar = match ptype {
PType::U8 => {
let v = actual_value as u8;
if actual_value < 0.0 || actual_value > u8::MAX as f64 {
vortex_bail!("Decimal value {} out of range for u8", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::U16 => {
let v = actual_value as u16;
if actual_value < 0.0 || actual_value > u16::MAX as f64 {
vortex_bail!("Decimal value {} out of range for u16", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::U32 => {
let v = actual_value as u32;
if actual_value < 0.0 || actual_value > u32::MAX as f64 {
vortex_bail!("Decimal value {} out of range for u32", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::U64 => {
let v = actual_value as u64;
if actual_value < 0.0 || actual_value > u64::MAX as f64 {
vortex_bail!("Decimal value {} out of range for u64", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::I8 => {
let v = actual_value as i8;
if actual_value < i8::MIN as f64 || actual_value > i8::MAX as f64 {
vortex_bail!("Decimal value {} out of range for i8", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::I16 => {
let v = actual_value as i16;
if actual_value < i16::MIN as f64 || actual_value > i16::MAX as f64 {
vortex_bail!("Decimal value {} out of range for i16", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::I32 => {
let v = actual_value as i32;
if actual_value < i32::MIN as f64 || actual_value > i32::MAX as f64 {
vortex_bail!("Decimal value {} out of range for i32", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::I64 => {
let v = actual_value as i64;
if actual_value < i64::MIN as f64 || actual_value > i64::MAX as f64 {
vortex_bail!("Decimal value {} out of range for i64", actual_value);
}
Scalar::primitive(v, *nullability)
}
PType::F16 => {
use vortex_dtype::half::f16;
Scalar::primitive(f16::from_f64(actual_value), *nullability)
}
PType::F32 => Scalar::primitive(actual_value as f32, *nullability),
PType::F64 => Scalar::primitive(actual_value, *nullability),
};
Ok(primitive_scalar)
} else {
// Null decimal to primitive
Ok(Scalar::null(dtype.clone()))
}
}
_ => vortex_bail!(
"Cannot cast decimal to {dtype}: decimal scalars can only be cast to decimal or primitive numeric types"
),
}
}
/// Apply the (checked) operator to self and other using SQL-style null semantics.
///
/// If the operation overflows, None is returned.
///
/// If the types are incompatible (ignoring nullability and precision/scale), an error is returned.
///
/// If either value is null, the result is null.
///
/// The result will have the same decimal type (precision/scale) as `self`, and the result
/// is checked to ensure it fits within the precision constraints.
pub fn checked_binary_numeric(
&self,
other: &DecimalScalar<'a>,
op: NumericOperator,
) -> Option<DecimalScalar<'a>> {
// We could have ops between different types but need to add rules for type inference.
if self.decimal_type != other.decimal_type {
vortex_panic!(
"decimal types must match: {} vs {}",
self.decimal_type,
other.decimal_type
);
}
// Use the more nullable dtype as the result type
let result_dtype = if self.dtype.is_nullable() {
self.dtype
} else {
other.dtype
};
// Handle null cases using SQL semantics
let result_value = match (self.value, other.value) {
(None, _) | (_, None) => None,
(Some(lhs), Some(rhs)) => {
// Perform the operation
let operation_result = match op {
NumericOperator::Add => lhs.checked_add(&rhs),
NumericOperator::Sub => lhs.checked_sub(&rhs),
NumericOperator::RSub => rhs.checked_sub(&lhs),
NumericOperator::Mul => lhs.checked_mul(&rhs),
NumericOperator::Div => lhs.checked_div(&rhs),
NumericOperator::RDiv => rhs.checked_div(&lhs),
}?;
// Check if the result fits within the precision constraints
if operation_result.fits_in_precision(self.decimal_type)? {
Some(operation_result)
} else {
// Result exceeds precision, return None (overflow)
return None;
}
}
};
Some(DecimalScalar {
dtype: result_dtype,
decimal_type: self.decimal_type,
value: result_value,
})
}
}
impl<'a> TryFrom<&'a Scalar> for DecimalScalar<'a> {
type Error = VortexError;
fn try_from(scalar: &'a Scalar) -> Result<Self, Self::Error> {
DecimalScalar::try_new(scalar.dtype(), scalar.value())
}
}
impl PartialEq for DecimalScalar<'_> {
fn eq(&self, other: &Self) -> bool {
self.dtype.eq_ignore_nullability(other.dtype) && self.value == other.value
}
}
impl Eq for DecimalScalar<'_> {}
/// Ord is not implemented since it's undefined for different PTypes
impl PartialOrd for DecimalScalar<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if !self.dtype.eq_ignore_nullability(other.dtype) {
return None;
}
self.value.partial_cmp(&other.value)
}
}
impl fmt::Display for DecimalScalar<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Some(&decimal_value) = self.value.as_ref() else {
return write!(f, "null");
};
// Introduce some of the scale factors instead.
match decimal_value {
DecimalValue::I8(v) => write!(
f,
"decimal8({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
DecimalValue::I16(v) => write!(
f,
"decimal16({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
DecimalValue::I32(v) => write!(
f,
"decimal32({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
DecimalValue::I64(v) => write!(
f,
"decimal64({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
DecimalValue::I128(v) => write!(
f,
"decimal128({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
DecimalValue::I256(v) => write!(
f,
"decimal256({}, precision={}, scale={})",
v,
self.decimal_type.precision(),
self.decimal_type.scale()
),
}
}
}