1use std::cmp::Ordering;
16use std::fmt::{Display, Formatter};
17use std::sync::Arc;
18
19use arrow_array::{Array, StructArray};
20use common_base::bytes::{Bytes, StringBytes};
21use common_decimal::Decimal128;
22use common_telemetry::error;
23use common_time::date::Date;
24use common_time::interval::IntervalUnit;
25use common_time::time::Time;
26use common_time::timestamp::{TimeUnit, Timestamp};
27use common_time::{Duration, IntervalDayTime, IntervalMonthDayNano, IntervalYearMonth, Timezone};
28use datafusion_common::ScalarValue;
29use datafusion_common::scalar::ScalarStructBuilder;
30pub use ordered_float::OrderedFloat;
31use serde::{Deserialize, Serialize, Serializer};
32use serde_json::Map;
33use snafu::{ResultExt, ensure};
34
35use crate::error::{
36 self, ConvertArrowArrayToScalarsSnafu, ConvertScalarToArrowArraySnafu, Error,
37 InconsistentStructFieldsAndItemsSnafu, Result, TryFromValueSnafu,
38};
39use crate::prelude::*;
40use crate::type_id::LogicalTypeId;
41use crate::types::{IntervalType, ListType, StructType};
42use crate::vectors::{ListVector, StructVector};
43
44pub type OrderedF32 = OrderedFloat<f32>;
45pub type OrderedF64 = OrderedFloat<f64>;
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
51pub enum Value {
52 Null,
53
54 Boolean(bool),
56 UInt8(u8),
57 UInt16(u16),
58 UInt32(u32),
59 UInt64(u64),
60 Int8(i8),
61 Int16(i16),
62 Int32(i32),
63 Int64(i64),
64 Float32(OrderedF32),
65 Float64(OrderedF64),
66
67 Decimal128(Decimal128),
69
70 String(StringBytes),
72 Binary(Bytes),
73
74 Date(Date),
76 Timestamp(Timestamp),
77 Time(Time),
78 Duration(Duration),
79 IntervalYearMonth(IntervalYearMonth),
81 IntervalDayTime(IntervalDayTime),
82 IntervalMonthDayNano(IntervalMonthDayNano),
83
84 List(ListValue),
86 Struct(StructValue),
87
88 Json(Box<Value>),
90}
91
92impl Display for Value {
93 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
94 match self {
95 Value::Null => write!(f, "{}", self.data_type().name()),
96 Value::Boolean(v) => write!(f, "{v}"),
97 Value::UInt8(v) => write!(f, "{v}"),
98 Value::UInt16(v) => write!(f, "{v}"),
99 Value::UInt32(v) => write!(f, "{v}"),
100 Value::UInt64(v) => write!(f, "{v}"),
101 Value::Int8(v) => write!(f, "{v}"),
102 Value::Int16(v) => write!(f, "{v}"),
103 Value::Int32(v) => write!(f, "{v}"),
104 Value::Int64(v) => write!(f, "{v}"),
105 Value::Float32(v) => write!(f, "{v}"),
106 Value::Float64(v) => write!(f, "{v}"),
107 Value::String(v) => write!(f, "{}", v.as_utf8()),
108 Value::Binary(v) => {
109 let hex = v
110 .iter()
111 .map(|b| format!("{b:02x}"))
112 .collect::<Vec<String>>()
113 .join("");
114 write!(f, "{hex}")
115 }
116 Value::Date(v) => write!(f, "{v}"),
117 Value::Timestamp(v) => write!(f, "{}", v.to_iso8601_string()),
118 Value::Time(t) => write!(f, "{}", t.to_iso8601_string()),
119 Value::IntervalYearMonth(v) => {
120 write!(f, "{}", v.to_iso8601_string())
121 }
122 Value::IntervalDayTime(v) => {
123 write!(f, "{}", v.to_iso8601_string())
124 }
125 Value::IntervalMonthDayNano(v) => {
126 write!(f, "{}", v.to_iso8601_string())
127 }
128 Value::Duration(d) => write!(f, "{d}"),
129 Value::List(v) => {
130 let items = v
131 .items()
132 .iter()
133 .map(|i| i.to_string())
134 .collect::<Vec<String>>()
135 .join(", ");
136 write!(f, "{}[{}]", v.datatype.name(), items)
137 }
138 Value::Decimal128(v) => write!(f, "{}", v),
139 Value::Struct(s) => {
140 let items = s
141 .fields
142 .fields()
143 .iter()
144 .map(|f| f.name())
145 .zip(s.items().iter())
146 .map(|(k, v)| format!("{k}: {v}"))
147 .collect::<Vec<String>>()
148 .join(", ");
149 write!(f, "{{ {items} }}")
150 }
151 Value::Json(json_data) => {
152 write!(f, "Json({})", json_data)
153 }
154 }
155 }
156}
157
158macro_rules! define_data_type_func {
159 ($struct: ident) => {
160 pub fn data_type(&self) -> ConcreteDataType {
165 match self {
166 $struct::Null => ConcreteDataType::null_datatype(),
167 $struct::Boolean(_) => ConcreteDataType::boolean_datatype(),
168 $struct::UInt8(_) => ConcreteDataType::uint8_datatype(),
169 $struct::UInt16(_) => ConcreteDataType::uint16_datatype(),
170 $struct::UInt32(_) => ConcreteDataType::uint32_datatype(),
171 $struct::UInt64(_) => ConcreteDataType::uint64_datatype(),
172 $struct::Int8(_) => ConcreteDataType::int8_datatype(),
173 $struct::Int16(_) => ConcreteDataType::int16_datatype(),
174 $struct::Int32(_) => ConcreteDataType::int32_datatype(),
175 $struct::Int64(_) => ConcreteDataType::int64_datatype(),
176 $struct::Float32(_) => ConcreteDataType::float32_datatype(),
177 $struct::Float64(_) => ConcreteDataType::float64_datatype(),
178 $struct::String(_) => ConcreteDataType::string_datatype(),
179 $struct::Binary(_) => ConcreteDataType::binary_datatype(),
180 $struct::Date(_) => ConcreteDataType::date_datatype(),
181 $struct::Time(t) => ConcreteDataType::time_datatype(*t.unit()),
182 $struct::Timestamp(v) => ConcreteDataType::timestamp_datatype(v.unit()),
183 $struct::IntervalYearMonth(_) => {
184 ConcreteDataType::interval_datatype(IntervalUnit::YearMonth)
185 }
186 $struct::IntervalDayTime(_) => {
187 ConcreteDataType::interval_datatype(IntervalUnit::DayTime)
188 }
189 $struct::IntervalMonthDayNano(_) => {
190 ConcreteDataType::interval_datatype(IntervalUnit::MonthDayNano)
191 }
192 $struct::List(list) => ConcreteDataType::list_datatype(list.datatype().clone()),
193 $struct::Duration(d) => ConcreteDataType::duration_datatype(d.unit()),
194 $struct::Decimal128(d) => {
195 ConcreteDataType::decimal128_datatype(d.precision(), d.scale())
196 }
197 $struct::Struct(struct_value) => {
198 ConcreteDataType::struct_datatype(struct_value.struct_type().clone())
199 }
200 $struct::Json(v) => ConcreteDataType::json_native_datatype(v.data_type()),
201 }
202 }
203 };
204}
205
206impl Value {
207 define_data_type_func!(Value);
208
209 pub fn is_null(&self) -> bool {
211 match self {
212 Value::Null => true,
213 Value::Json(inner) => inner.is_null(),
214 _ => false,
215 }
216 }
217
218 pub fn as_list(&self) -> Result<Option<&ListValue>> {
220 match self {
221 Value::Null => Ok(None),
222 Value::List(v) => Ok(Some(v)),
223 Value::Json(inner) => inner.as_list(),
224 other => error::CastTypeSnafu {
225 msg: format!("Failed to cast {other:?} to list value"),
226 }
227 .fail(),
228 }
229 }
230
231 pub fn as_struct(&self) -> Result<Option<&StructValue>> {
232 match self {
233 Value::Null => Ok(None),
234 Value::Struct(v) => Ok(Some(v)),
235 Value::Json(inner) => inner.as_struct(),
236 other => error::CastTypeSnafu {
237 msg: format!("Failed to cast {other:?} to struct value"),
238 }
239 .fail(),
240 }
241 }
242
243 pub fn as_value_ref(&self) -> ValueRef<'_> {
245 match self {
246 Value::Null => ValueRef::Null,
247 Value::Boolean(v) => ValueRef::Boolean(*v),
248 Value::UInt8(v) => ValueRef::UInt8(*v),
249 Value::UInt16(v) => ValueRef::UInt16(*v),
250 Value::UInt32(v) => ValueRef::UInt32(*v),
251 Value::UInt64(v) => ValueRef::UInt64(*v),
252 Value::Int8(v) => ValueRef::Int8(*v),
253 Value::Int16(v) => ValueRef::Int16(*v),
254 Value::Int32(v) => ValueRef::Int32(*v),
255 Value::Int64(v) => ValueRef::Int64(*v),
256 Value::Float32(v) => ValueRef::Float32(*v),
257 Value::Float64(v) => ValueRef::Float64(*v),
258 Value::String(v) => ValueRef::String(v.as_utf8()),
259 Value::Binary(v) => ValueRef::Binary(v),
260 Value::Date(v) => ValueRef::Date(*v),
261 Value::List(v) => ValueRef::List(ListValueRef::Ref { val: v }),
262 Value::Timestamp(v) => ValueRef::Timestamp(*v),
263 Value::Time(v) => ValueRef::Time(*v),
264 Value::IntervalYearMonth(v) => ValueRef::IntervalYearMonth(*v),
265 Value::IntervalDayTime(v) => ValueRef::IntervalDayTime(*v),
266 Value::IntervalMonthDayNano(v) => ValueRef::IntervalMonthDayNano(*v),
267 Value::Duration(v) => ValueRef::Duration(*v),
268 Value::Decimal128(v) => ValueRef::Decimal128(*v),
269 Value::Struct(v) => ValueRef::Struct(StructValueRef::Ref(v)),
270 Value::Json(v) => ValueRef::Json(Box::new(v.as_value_ref())),
271 }
272 }
273
274 pub fn as_timestamp(&self) -> Option<Timestamp> {
276 match self {
277 Value::Timestamp(t) => Some(*t),
278 _ => None,
279 }
280 }
281
282 pub fn as_string(&self) -> Option<String> {
284 match self {
285 Value::String(bytes) => Some(bytes.as_utf8().to_string()),
286 _ => None,
287 }
288 }
289
290 pub fn as_date(&self) -> Option<Date> {
292 match self {
293 Value::Date(t) => Some(*t),
294 _ => None,
295 }
296 }
297
298 pub fn as_time(&self) -> Option<Time> {
300 match self {
301 Value::Time(t) => Some(*t),
302 _ => None,
303 }
304 }
305
306 pub fn as_interval_year_month(&self) -> Option<IntervalYearMonth> {
308 match self {
309 Value::IntervalYearMonth(v) => Some(*v),
310 _ => None,
311 }
312 }
313
314 pub fn as_interval_day_time(&self) -> Option<IntervalDayTime> {
316 match self {
317 Value::IntervalDayTime(v) => Some(*v),
318 _ => None,
319 }
320 }
321
322 pub fn as_interval_month_day_nano(&self) -> Option<IntervalMonthDayNano> {
324 match self {
325 Value::IntervalMonthDayNano(v) => Some(*v),
326 _ => None,
327 }
328 }
329
330 pub fn as_i64(&self) -> Option<i64> {
332 match self {
333 Value::Int8(v) => Some(*v as _),
334 Value::Int16(v) => Some(*v as _),
335 Value::Int32(v) => Some(*v as _),
336 Value::Int64(v) => Some(*v),
337 Value::UInt8(v) => Some(*v as _),
338 Value::UInt16(v) => Some(*v as _),
339 Value::UInt32(v) => Some(*v as _),
340 Value::Json(inner) => inner.as_i64(),
341 _ => None,
342 }
343 }
344
345 pub fn as_u64(&self) -> Option<u64> {
347 match self {
348 Value::UInt8(v) => Some(*v as _),
349 Value::UInt16(v) => Some(*v as _),
350 Value::UInt32(v) => Some(*v as _),
351 Value::UInt64(v) => Some(*v),
352 Value::Json(inner) => inner.as_u64(),
353 _ => None,
354 }
355 }
356 pub fn as_f64_lossy(&self) -> Option<f64> {
358 match self {
359 Value::Float32(v) => Some(v.0 as _),
360 Value::Float64(v) => Some(v.0),
361 Value::Int8(v) => Some(*v as _),
362 Value::Int16(v) => Some(*v as _),
363 Value::Int32(v) => Some(*v as _),
364 Value::Int64(v) => Some(*v as _),
365 Value::UInt8(v) => Some(*v as _),
366 Value::UInt16(v) => Some(*v as _),
367 Value::UInt32(v) => Some(*v as _),
368 Value::UInt64(v) => Some(*v as _),
369 Value::Json(inner) => inner.as_f64_lossy(),
370 _ => None,
371 }
372 }
373
374 pub fn as_duration(&self) -> Option<Duration> {
376 match self {
377 Value::Duration(d) => Some(*d),
378 _ => None,
379 }
380 }
381
382 pub fn as_bool(&self) -> Option<bool> {
384 match self {
385 Value::Boolean(b) => Some(*b),
386 Value::Json(inner) => inner.as_bool(),
387 _ => None,
388 }
389 }
390
391 pub fn into_json_inner(self) -> Option<Value> {
393 match self {
394 Value::Json(v) => Some(*v),
395 _ => None,
396 }
397 }
398
399 pub fn logical_type_id(&self) -> LogicalTypeId {
401 match self {
402 Value::Null => LogicalTypeId::Null,
403 Value::Boolean(_) => LogicalTypeId::Boolean,
404 Value::UInt8(_) => LogicalTypeId::UInt8,
405 Value::UInt16(_) => LogicalTypeId::UInt16,
406 Value::UInt32(_) => LogicalTypeId::UInt32,
407 Value::UInt64(_) => LogicalTypeId::UInt64,
408 Value::Int8(_) => LogicalTypeId::Int8,
409 Value::Int16(_) => LogicalTypeId::Int16,
410 Value::Int32(_) => LogicalTypeId::Int32,
411 Value::Int64(_) => LogicalTypeId::Int64,
412 Value::Float32(_) => LogicalTypeId::Float32,
413 Value::Float64(_) => LogicalTypeId::Float64,
414 Value::String(_) => LogicalTypeId::String,
415 Value::Binary(_) => LogicalTypeId::Binary,
416 Value::List(_) => LogicalTypeId::List,
417 Value::Date(_) => LogicalTypeId::Date,
418 Value::Timestamp(t) => match t.unit() {
419 TimeUnit::Second => LogicalTypeId::TimestampSecond,
420 TimeUnit::Millisecond => LogicalTypeId::TimestampMillisecond,
421 TimeUnit::Microsecond => LogicalTypeId::TimestampMicrosecond,
422 TimeUnit::Nanosecond => LogicalTypeId::TimestampNanosecond,
423 },
424 Value::Time(t) => match t.unit() {
425 TimeUnit::Second => LogicalTypeId::TimeSecond,
426 TimeUnit::Millisecond => LogicalTypeId::TimeMillisecond,
427 TimeUnit::Microsecond => LogicalTypeId::TimeMicrosecond,
428 TimeUnit::Nanosecond => LogicalTypeId::TimeNanosecond,
429 },
430 Value::IntervalYearMonth(_) => LogicalTypeId::IntervalYearMonth,
431 Value::IntervalDayTime(_) => LogicalTypeId::IntervalDayTime,
432 Value::IntervalMonthDayNano(_) => LogicalTypeId::IntervalMonthDayNano,
433 Value::Duration(d) => match d.unit() {
434 TimeUnit::Second => LogicalTypeId::DurationSecond,
435 TimeUnit::Millisecond => LogicalTypeId::DurationMillisecond,
436 TimeUnit::Microsecond => LogicalTypeId::DurationMicrosecond,
437 TimeUnit::Nanosecond => LogicalTypeId::DurationNanosecond,
438 },
439 Value::Decimal128(_) => LogicalTypeId::Decimal128,
440 Value::Struct(_) => LogicalTypeId::Struct,
441 Value::Json(_) => LogicalTypeId::Json,
442 }
443 }
444
445 pub fn try_to_scalar_value(&self, output_type: &ConcreteDataType) -> Result<ScalarValue> {
447 let value_type_id = self.logical_type_id();
449 let output_type_id = output_type.logical_type_id();
450 ensure!(
451 output_type_id == value_type_id
452 || self.is_null()
453 || (output_type_id == LogicalTypeId::Json
454 && (value_type_id == LogicalTypeId::Binary
455 || value_type_id == LogicalTypeId::Json)),
456 error::ToScalarValueSnafu {
457 reason: format!(
458 "expect value to return output_type {output_type_id:?}, actual: {value_type_id:?}",
459 ),
460 }
461 );
462
463 let scalar_value = match self {
464 Value::Boolean(v) => ScalarValue::Boolean(Some(*v)),
465 Value::UInt8(v) => ScalarValue::UInt8(Some(*v)),
466 Value::UInt16(v) => ScalarValue::UInt16(Some(*v)),
467 Value::UInt32(v) => ScalarValue::UInt32(Some(*v)),
468 Value::UInt64(v) => ScalarValue::UInt64(Some(*v)),
469 Value::Int8(v) => ScalarValue::Int8(Some(*v)),
470 Value::Int16(v) => ScalarValue::Int16(Some(*v)),
471 Value::Int32(v) => ScalarValue::Int32(Some(*v)),
472 Value::Int64(v) => ScalarValue::Int64(Some(*v)),
473 Value::Float32(v) => ScalarValue::Float32(Some(v.0)),
474 Value::Float64(v) => ScalarValue::Float64(Some(v.0)),
475 Value::String(v) => {
476 let s = v.as_utf8().to_string();
477 match output_type {
478 ConcreteDataType::String(t) if t.is_large() => ScalarValue::LargeUtf8(Some(s)),
479 _ => ScalarValue::Utf8(Some(s)),
480 }
481 }
482 Value::Binary(v) => ScalarValue::Binary(Some(v.to_vec())),
483 Value::Date(v) => ScalarValue::Date32(Some(v.val())),
484 Value::Null => to_null_scalar_value(output_type)?,
485 Value::List(list) => {
486 let list_type = output_type.as_list().unwrap();
488 list.try_to_scalar_value(list_type)?
489 }
490 Value::Timestamp(t) => timestamp_to_scalar_value(t.unit(), Some(t.value())),
491 Value::Time(t) => time_to_scalar_value(*t.unit(), Some(t.value()))?,
492 Value::IntervalYearMonth(v) => ScalarValue::IntervalYearMonth(Some(v.to_i32())),
493 Value::IntervalDayTime(v) => ScalarValue::IntervalDayTime(Some((*v).into())),
494 Value::IntervalMonthDayNano(v) => ScalarValue::IntervalMonthDayNano(Some((*v).into())),
495 Value::Duration(d) => duration_to_scalar_value(d.unit(), Some(d.value())),
496 Value::Decimal128(d) => {
497 let (v, p, s) = d.to_scalar_value();
498 ScalarValue::Decimal128(v, p, s)
499 }
500 Value::Struct(struct_value) => {
501 let struct_type = output_type.as_struct().unwrap();
502 struct_value.try_to_scalar_value(struct_type)?
503 }
504 Value::Json(v) => v.try_to_scalar_value(output_type)?,
505 };
506
507 Ok(scalar_value)
508 }
509
510 pub fn try_negative(&self) -> Option<Self> {
512 match self {
513 Value::Null => Some(Value::Null),
514 Value::UInt8(x) => {
515 if *x == 0 {
516 Some(Value::UInt8(*x))
517 } else {
518 None
519 }
520 }
521 Value::UInt16(x) => {
522 if *x == 0 {
523 Some(Value::UInt16(*x))
524 } else {
525 None
526 }
527 }
528 Value::UInt32(x) => {
529 if *x == 0 {
530 Some(Value::UInt32(*x))
531 } else {
532 None
533 }
534 }
535 Value::UInt64(x) => {
536 if *x == 0 {
537 Some(Value::UInt64(*x))
538 } else {
539 None
540 }
541 }
542 Value::Int8(x) => Some(Value::Int8(-*x)),
543 Value::Int16(x) => Some(Value::Int16(-*x)),
544 Value::Int32(x) => Some(Value::Int32(-*x)),
545 Value::Int64(x) => Some(Value::Int64(-*x)),
546 Value::Float32(x) => Some(Value::Float32(-*x)),
547 Value::Float64(x) => Some(Value::Float64(-*x)),
548 Value::Decimal128(x) => Some(Value::Decimal128(x.negative())),
549 Value::Date(x) => Some(Value::Date(x.negative())),
550 Value::Timestamp(x) => Some(Value::Timestamp(x.negative())),
551 Value::Time(x) => Some(Value::Time(x.negative())),
552 Value::Duration(x) => Some(Value::Duration(x.negative())),
553 Value::IntervalYearMonth(x) => Some(Value::IntervalYearMonth(x.negative())),
554 Value::IntervalDayTime(x) => Some(Value::IntervalDayTime(x.negative())),
555 Value::IntervalMonthDayNano(x) => Some(Value::IntervalMonthDayNano(x.negative())),
556
557 Value::Json(v) => v.try_negative().map(|neg| Value::Json(Box::new(neg))),
558
559 Value::Binary(_)
560 | Value::String(_)
561 | Value::Boolean(_)
562 | Value::List(_)
563 | Value::Struct(_) => None,
564 }
565 }
566}
567
568pub trait TryAsPrimitive<T: LogicalPrimitiveType> {
569 fn try_as_primitive(&self) -> Option<T::Native>;
570}
571
572macro_rules! impl_try_as_primitive {
573 ($Type: ident, $Variant: ident) => {
574 impl TryAsPrimitive<crate::types::$Type> for Value {
575 fn try_as_primitive(
576 &self,
577 ) -> Option<<crate::types::$Type as crate::types::LogicalPrimitiveType>::Native> {
578 match self {
579 Value::$Variant(v) => Some((*v).into()),
580 _ => None,
581 }
582 }
583 }
584 };
585}
586
587impl_try_as_primitive!(Int8Type, Int8);
588impl_try_as_primitive!(Int16Type, Int16);
589impl_try_as_primitive!(Int32Type, Int32);
590impl_try_as_primitive!(Int64Type, Int64);
591impl_try_as_primitive!(UInt8Type, UInt8);
592impl_try_as_primitive!(UInt16Type, UInt16);
593impl_try_as_primitive!(UInt32Type, UInt32);
594impl_try_as_primitive!(UInt64Type, UInt64);
595impl_try_as_primitive!(Float32Type, Float32);
596impl_try_as_primitive!(Float64Type, Float64);
597
598pub fn to_null_scalar_value(output_type: &ConcreteDataType) -> Result<ScalarValue> {
599 Ok(match output_type {
600 ConcreteDataType::Null(_) => ScalarValue::Null,
601 ConcreteDataType::Boolean(_) => ScalarValue::Boolean(None),
602 ConcreteDataType::Int8(_) => ScalarValue::Int8(None),
603 ConcreteDataType::Int16(_) => ScalarValue::Int16(None),
604 ConcreteDataType::Int32(_) => ScalarValue::Int32(None),
605 ConcreteDataType::Int64(_) => ScalarValue::Int64(None),
606 ConcreteDataType::UInt8(_) => ScalarValue::UInt8(None),
607 ConcreteDataType::UInt16(_) => ScalarValue::UInt16(None),
608 ConcreteDataType::UInt32(_) => ScalarValue::UInt32(None),
609 ConcreteDataType::UInt64(_) => ScalarValue::UInt64(None),
610 ConcreteDataType::Float32(_) => ScalarValue::Float32(None),
611 ConcreteDataType::Float64(_) => ScalarValue::Float64(None),
612 ConcreteDataType::Binary(_) | ConcreteDataType::Json(_) | ConcreteDataType::Vector(_) => {
613 ScalarValue::Binary(None)
614 }
615 ConcreteDataType::String(t) => {
616 if t.is_large() {
617 ScalarValue::LargeUtf8(None)
618 } else {
619 ScalarValue::Utf8(None)
620 }
621 }
622 ConcreteDataType::Date(_) => ScalarValue::Date32(None),
623 ConcreteDataType::Timestamp(t) => timestamp_to_scalar_value(t.unit(), None),
624 ConcreteDataType::Interval(v) => match v {
625 IntervalType::YearMonth(_) => ScalarValue::IntervalYearMonth(None),
626 IntervalType::DayTime(_) => ScalarValue::IntervalDayTime(None),
627 IntervalType::MonthDayNano(_) => ScalarValue::IntervalMonthDayNano(None),
628 },
629 ConcreteDataType::List(list_type) => {
630 ScalarValue::new_null_list(list_type.item_type().as_arrow_type(), true, 1)
631 }
632 ConcreteDataType::Struct(fields) => {
633 let fields = fields.as_arrow_fields();
634 ScalarStructBuilder::new_null(fields)
635 }
636 ConcreteDataType::Dictionary(dict) => ScalarValue::Dictionary(
637 Box::new(dict.key_type().as_arrow_type()),
638 Box::new(to_null_scalar_value(dict.value_type())?),
639 ),
640 ConcreteDataType::Time(t) => time_to_scalar_value(t.unit(), None)?,
641 ConcreteDataType::Duration(d) => duration_to_scalar_value(d.unit(), None),
642 ConcreteDataType::Decimal128(d) => ScalarValue::Decimal128(None, d.precision(), d.scale()),
643 })
644}
645
646pub fn timestamp_to_scalar_value(unit: TimeUnit, val: Option<i64>) -> ScalarValue {
647 match unit {
648 TimeUnit::Second => ScalarValue::TimestampSecond(val, None),
649 TimeUnit::Millisecond => ScalarValue::TimestampMillisecond(val, None),
650 TimeUnit::Microsecond => ScalarValue::TimestampMicrosecond(val, None),
651 TimeUnit::Nanosecond => ScalarValue::TimestampNanosecond(val, None),
652 }
653}
654
655pub fn time_to_scalar_value(unit: TimeUnit, val: Option<i64>) -> Result<ScalarValue> {
657 Ok(match unit {
658 TimeUnit::Second => ScalarValue::Time32Second(
659 val.map(|i| i.try_into().context(error::CastTimeTypeSnafu))
660 .transpose()?,
661 ),
662 TimeUnit::Millisecond => ScalarValue::Time32Millisecond(
663 val.map(|i| i.try_into().context(error::CastTimeTypeSnafu))
664 .transpose()?,
665 ),
666 TimeUnit::Microsecond => ScalarValue::Time64Microsecond(val),
667 TimeUnit::Nanosecond => ScalarValue::Time64Nanosecond(val),
668 })
669}
670
671pub fn duration_to_scalar_value(unit: TimeUnit, val: Option<i64>) -> ScalarValue {
673 match unit {
674 TimeUnit::Second => ScalarValue::DurationSecond(val),
675 TimeUnit::Millisecond => ScalarValue::DurationMillisecond(val),
676 TimeUnit::Microsecond => ScalarValue::DurationMicrosecond(val),
677 TimeUnit::Nanosecond => ScalarValue::DurationNanosecond(val),
678 }
679}
680
681pub fn scalar_value_to_timestamp(
685 scalar: &ScalarValue,
686 timezone: Option<&Timezone>,
687) -> Option<Timestamp> {
688 match scalar {
689 ScalarValue::Utf8(Some(s)) => match Timestamp::from_str(s, timezone) {
690 Ok(t) => Some(t),
691 Err(e) => {
692 error!(e;"Failed to convert string literal {s} to timestamp");
693 None
694 }
695 },
696 ScalarValue::TimestampSecond(v, _) => v.map(Timestamp::new_second),
697 ScalarValue::TimestampMillisecond(v, _) => v.map(Timestamp::new_millisecond),
698 ScalarValue::TimestampMicrosecond(v, _) => v.map(Timestamp::new_microsecond),
699 ScalarValue::TimestampNanosecond(v, _) => v.map(Timestamp::new_nanosecond),
700 _ => None,
701 }
702}
703
704macro_rules! impl_ord_for_value_like {
705 ($Type: ident, $left: ident, $right: ident) => {
706 if $left.is_null() && !$right.is_null() {
707 return Ordering::Less;
708 } else if !$left.is_null() && $right.is_null() {
709 return Ordering::Greater;
710 } else {
711 match ($left, $right) {
712 ($Type::Null, $Type::Null) => Ordering::Equal,
713 ($Type::Boolean(v1), $Type::Boolean(v2)) => v1.cmp(v2),
714 ($Type::UInt8(v1), $Type::UInt8(v2)) => v1.cmp(v2),
715 ($Type::UInt16(v1), $Type::UInt16(v2)) => v1.cmp(v2),
716 ($Type::UInt32(v1), $Type::UInt32(v2)) => v1.cmp(v2),
717 ($Type::UInt64(v1), $Type::UInt64(v2)) => v1.cmp(v2),
718 ($Type::Int8(v1), $Type::Int8(v2)) => v1.cmp(v2),
719 ($Type::Int16(v1), $Type::Int16(v2)) => v1.cmp(v2),
720 ($Type::Int32(v1), $Type::Int32(v2)) => v1.cmp(v2),
721 ($Type::Int64(v1), $Type::Int64(v2)) => v1.cmp(v2),
722 ($Type::Float32(v1), $Type::Float32(v2)) => v1.cmp(v2),
723 ($Type::Float64(v1), $Type::Float64(v2)) => v1.cmp(v2),
724 ($Type::String(v1), $Type::String(v2)) => v1.cmp(v2),
725 ($Type::Binary(v1), $Type::Binary(v2)) => v1.cmp(v2),
726 ($Type::Date(v1), $Type::Date(v2)) => v1.cmp(v2),
727 ($Type::Timestamp(v1), $Type::Timestamp(v2)) => v1.cmp(v2),
728 ($Type::Time(v1), $Type::Time(v2)) => v1.cmp(v2),
729 ($Type::IntervalYearMonth(v1), $Type::IntervalYearMonth(v2)) => v1.cmp(v2),
730 ($Type::IntervalDayTime(v1), $Type::IntervalDayTime(v2)) => v1.cmp(v2),
731 ($Type::IntervalMonthDayNano(v1), $Type::IntervalMonthDayNano(v2)) => v1.cmp(v2),
732 ($Type::Duration(v1), $Type::Duration(v2)) => v1.cmp(v2),
733 ($Type::List(v1), $Type::List(v2)) => v1.cmp(v2),
734 _ => panic!(
735 "Cannot compare different values {:?} and {:?}",
736 $left, $right
737 ),
738 }
739 }
740 };
741}
742
743impl PartialOrd for Value {
744 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
745 Some(self.cmp(other))
746 }
747}
748
749impl Ord for Value {
750 fn cmp(&self, other: &Self) -> Ordering {
751 impl_ord_for_value_like!(Value, self, other)
752 }
753}
754
755macro_rules! impl_try_from_value {
756 ($Variant: ident, $Type: ident) => {
757 impl TryFrom<Value> for $Type {
758 type Error = Error;
759
760 #[inline]
761 fn try_from(from: Value) -> std::result::Result<Self, Self::Error> {
762 match from {
763 Value::$Variant(v) => Ok(v.into()),
764 _ => TryFromValueSnafu {
765 reason: format!("{:?} is not a {}", from, stringify!($Type)),
766 }
767 .fail(),
768 }
769 }
770 }
771
772 impl TryFrom<Value> for Option<$Type> {
773 type Error = Error;
774
775 #[inline]
776 fn try_from(from: Value) -> std::result::Result<Self, Self::Error> {
777 match from {
778 Value::$Variant(v) => Ok(Some(v.into())),
779 Value::Null => Ok(None),
780 _ => TryFromValueSnafu {
781 reason: format!("{:?} is not a {}", from, stringify!($Type)),
782 }
783 .fail(),
784 }
785 }
786 }
787 };
788}
789
790impl_try_from_value!(Boolean, bool);
791impl_try_from_value!(UInt8, u8);
792impl_try_from_value!(UInt16, u16);
793impl_try_from_value!(UInt32, u32);
794impl_try_from_value!(UInt64, u64);
795impl_try_from_value!(Int8, i8);
796impl_try_from_value!(Int16, i16);
797impl_try_from_value!(Int32, i32);
798impl_try_from_value!(Int64, i64);
799impl_try_from_value!(Float32, f32);
800impl_try_from_value!(Float64, f64);
801impl_try_from_value!(Float32, OrderedF32);
802impl_try_from_value!(Float64, OrderedF64);
803impl_try_from_value!(String, StringBytes);
804impl_try_from_value!(Binary, Bytes);
805impl_try_from_value!(Date, Date);
806impl_try_from_value!(Time, Time);
807impl_try_from_value!(Timestamp, Timestamp);
808impl_try_from_value!(IntervalYearMonth, IntervalYearMonth);
809impl_try_from_value!(IntervalDayTime, IntervalDayTime);
810impl_try_from_value!(IntervalMonthDayNano, IntervalMonthDayNano);
811impl_try_from_value!(Duration, Duration);
812impl_try_from_value!(Decimal128, Decimal128);
813
814macro_rules! impl_value_from {
815 ($Variant: ident, $Type: ident) => {
816 impl From<$Type> for Value {
817 fn from(value: $Type) -> Self {
818 Value::$Variant(value.into())
819 }
820 }
821
822 impl From<Option<$Type>> for Value {
823 fn from(value: Option<$Type>) -> Self {
824 match value {
825 Some(v) => Value::$Variant(v.into()),
826 None => Value::Null,
827 }
828 }
829 }
830 };
831}
832
833impl_value_from!(Boolean, bool);
834impl_value_from!(UInt8, u8);
835impl_value_from!(UInt16, u16);
836impl_value_from!(UInt32, u32);
837impl_value_from!(UInt64, u64);
838impl_value_from!(Int8, i8);
839impl_value_from!(Int16, i16);
840impl_value_from!(Int32, i32);
841impl_value_from!(Int64, i64);
842impl_value_from!(Float32, f32);
843impl_value_from!(Float64, f64);
844impl_value_from!(Float32, OrderedF32);
845impl_value_from!(Float64, OrderedF64);
846impl_value_from!(String, StringBytes);
847impl_value_from!(Binary, Bytes);
848impl_value_from!(Date, Date);
849impl_value_from!(Time, Time);
850impl_value_from!(Timestamp, Timestamp);
851impl_value_from!(IntervalYearMonth, IntervalYearMonth);
852impl_value_from!(IntervalDayTime, IntervalDayTime);
853impl_value_from!(IntervalMonthDayNano, IntervalMonthDayNano);
854impl_value_from!(Duration, Duration);
855impl_value_from!(String, String);
856impl_value_from!(Decimal128, Decimal128);
857
858impl From<&str> for Value {
859 fn from(string: &str) -> Value {
860 Value::String(string.into())
861 }
862}
863
864impl From<Vec<u8>> for Value {
865 fn from(bytes: Vec<u8>) -> Value {
866 Value::Binary(bytes.into())
867 }
868}
869
870impl From<&[u8]> for Value {
871 fn from(bytes: &[u8]) -> Value {
872 Value::Binary(bytes.into())
873 }
874}
875
876impl TryFrom<Value> for serde_json::Value {
877 type Error = serde_json::Error;
878
879 fn try_from(value: Value) -> serde_json::Result<serde_json::Value> {
880 let json_value = match value {
881 Value::Null => serde_json::Value::Null,
882 Value::Boolean(v) => serde_json::Value::Bool(v),
883 Value::UInt8(v) => serde_json::Value::from(v),
884 Value::UInt16(v) => serde_json::Value::from(v),
885 Value::UInt32(v) => serde_json::Value::from(v),
886 Value::UInt64(v) => serde_json::Value::from(v),
887 Value::Int8(v) => serde_json::Value::from(v),
888 Value::Int16(v) => serde_json::Value::from(v),
889 Value::Int32(v) => serde_json::Value::from(v),
890 Value::Int64(v) => serde_json::Value::from(v),
891 Value::Float32(v) => serde_json::Value::from(v.0),
892 Value::Float64(v) => serde_json::Value::from(v.0),
893 Value::String(bytes) => serde_json::Value::String(bytes.into_string()),
894 Value::Binary(bytes) => serde_json::to_value(bytes)?,
895 Value::Date(v) => serde_json::Value::Number(v.val().into()),
896 Value::List(v) => {
897 let items = v
898 .take_items()
899 .into_iter()
900 .map(serde_json::Value::try_from)
901 .collect::<serde_json::Result<Vec<_>>>()?;
902 serde_json::Value::Array(items)
903 }
904 Value::Timestamp(v) => serde_json::to_value(v.value())?,
905 Value::Time(v) => serde_json::to_value(v.value())?,
906 Value::IntervalYearMonth(v) => serde_json::to_value(v.to_i32())?,
907 Value::IntervalDayTime(v) => serde_json::to_value(v.to_i64())?,
908 Value::IntervalMonthDayNano(v) => serde_json::to_value(v.to_i128())?,
909 Value::Duration(v) => serde_json::to_value(v.value())?,
910 Value::Decimal128(v) => serde_json::to_value(v.to_string())?,
911 Value::Struct(v) => {
912 let (items, struct_type) = v.into_parts();
913 let map = struct_type
914 .fields()
915 .iter()
916 .zip(items.into_iter())
917 .map(|(field, value)| {
918 Ok((
919 field.name().to_string(),
920 serde_json::Value::try_from(value)?,
921 ))
922 })
923 .collect::<serde_json::Result<Map<String, serde_json::Value>>>()?;
924 serde_json::Value::Object(map)
925 }
926 Value::Json(v) => serde_json::Value::try_from(*v)?,
927 };
928
929 Ok(json_value)
930 }
931}
932
933#[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize)]
936pub struct ListValue {
937 items: Vec<Value>,
938 datatype: Arc<ConcreteDataType>,
941}
942
943impl Eq for ListValue {}
944
945impl ListValue {
946 pub fn new(items: Vec<Value>, datatype: Arc<ConcreteDataType>) -> Self {
947 Self { items, datatype }
948 }
949
950 pub fn items(&self) -> &[Value] {
951 &self.items
952 }
953
954 pub fn take_items(self) -> Vec<Value> {
955 self.items
956 }
957
958 pub fn into_parts(self) -> (Vec<Value>, Arc<ConcreteDataType>) {
959 (self.items, self.datatype)
960 }
961
962 pub fn datatype(&self) -> Arc<ConcreteDataType> {
964 self.datatype.clone()
965 }
966
967 pub fn len(&self) -> usize {
968 self.items.len()
969 }
970
971 pub fn is_empty(&self) -> bool {
972 self.items.is_empty()
973 }
974
975 pub fn try_to_scalar_value(&self, output_type: &ListType) -> Result<ScalarValue> {
976 let vs = self
977 .items
978 .iter()
979 .map(|v| v.try_to_scalar_value(output_type.item_type()))
980 .collect::<Result<Vec<_>>>()?;
981 Ok(ScalarValue::List(ScalarValue::new_list(
982 &vs,
983 &self.datatype.as_arrow_type(),
984 true,
985 )))
986 }
987
988 fn estimated_size(&self) -> usize {
991 self.items
992 .first()
993 .map(|x| x.as_value_ref().data_size() * self.items.len())
994 .unwrap_or(0)
995 + std::mem::size_of::<Arc<ConcreteDataType>>()
996 }
997}
998
999impl Default for ListValue {
1000 fn default() -> ListValue {
1001 ListValue::new(vec![], Arc::new(ConcreteDataType::null_datatype()))
1002 }
1003}
1004
1005impl PartialOrd for ListValue {
1006 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1007 Some(self.cmp(other))
1008 }
1009}
1010
1011impl Ord for ListValue {
1012 fn cmp(&self, other: &Self) -> Ordering {
1013 assert_eq!(
1014 self.datatype, other.datatype,
1015 "Cannot compare different datatypes!"
1016 );
1017 self.items.cmp(&other.items)
1018 }
1019}
1020
1021#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
1022pub struct StructValue {
1023 items: Vec<Value>,
1024 fields: StructType,
1025}
1026
1027impl StructValue {
1028 pub fn try_new(items: Vec<Value>, fields: StructType) -> Result<Self> {
1029 ensure!(
1030 items.len() == fields.fields().len(),
1031 InconsistentStructFieldsAndItemsSnafu {
1032 field_len: fields.fields().len(),
1033 item_len: items.len()
1034 }
1035 );
1036 Ok(Self { items, fields })
1037 }
1038
1039 pub fn new(items: Vec<Value>, fields: StructType) -> Self {
1043 Self::try_new(items, fields).unwrap()
1044 }
1045
1046 pub fn items(&self) -> &[Value] {
1047 &self.items
1048 }
1049
1050 pub fn take_items(self) -> Vec<Value> {
1051 self.items
1052 }
1053
1054 pub fn into_parts(self) -> (Vec<Value>, StructType) {
1055 (self.items, self.fields)
1056 }
1057
1058 pub fn struct_type(&self) -> &StructType {
1059 &self.fields
1060 }
1061
1062 pub fn len(&self) -> usize {
1063 self.items.len()
1064 }
1065
1066 pub fn is_empty(&self) -> bool {
1067 self.items.is_empty()
1068 }
1069
1070 fn estimated_size(&self) -> usize {
1071 self.items
1072 .iter()
1073 .map(|x| x.as_value_ref().data_size())
1074 .sum::<usize>()
1075 + std::mem::size_of::<StructType>()
1076 }
1077
1078 fn try_to_scalar_value(&self, output_type: &StructType) -> Result<ScalarValue> {
1079 let arrays = self
1080 .items
1081 .iter()
1082 .map(|value| {
1083 let scalar_value = value.try_to_scalar_value(&value.data_type())?;
1084 scalar_value
1085 .to_array()
1086 .context(ConvertScalarToArrowArraySnafu)
1087 })
1088 .collect::<Result<Vec<Arc<dyn Array>>>>()?;
1089
1090 let fields = output_type.as_arrow_fields();
1091 let struct_array = StructArray::new(fields, arrays, None);
1092 Ok(ScalarValue::Struct(Arc::new(struct_array)))
1093 }
1094}
1095
1096impl Default for StructValue {
1097 fn default() -> StructValue {
1098 StructValue::try_new(vec![], StructType::new(Arc::new(vec![]))).unwrap()
1099 }
1100}
1101
1102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1105pub struct DictionaryValue {
1106 key_type: ConcreteDataType,
1108 value_type: ConcreteDataType,
1109}
1110
1111impl Eq for DictionaryValue {}
1112
1113impl TryFrom<ScalarValue> for Value {
1114 type Error = error::Error;
1115
1116 fn try_from(v: ScalarValue) -> Result<Self> {
1117 let v = match v {
1118 ScalarValue::Null => Value::Null,
1119 ScalarValue::Boolean(b) => Value::from(b),
1120 ScalarValue::Float32(f) => Value::from(f),
1121 ScalarValue::Float64(f) => Value::from(f),
1122 ScalarValue::Int8(i) => Value::from(i),
1123 ScalarValue::Int16(i) => Value::from(i),
1124 ScalarValue::Int32(i) => Value::from(i),
1125 ScalarValue::Int64(i) => Value::from(i),
1126 ScalarValue::UInt8(u) => Value::from(u),
1127 ScalarValue::UInt16(u) => Value::from(u),
1128 ScalarValue::UInt32(u) => Value::from(u),
1129 ScalarValue::UInt64(u) => Value::from(u),
1130 ScalarValue::Utf8(s) | ScalarValue::LargeUtf8(s) => {
1131 Value::from(s.map(StringBytes::from))
1132 }
1133 ScalarValue::Binary(b)
1134 | ScalarValue::LargeBinary(b)
1135 | ScalarValue::FixedSizeBinary(_, b) => Value::from(b.map(Bytes::from)),
1136 ScalarValue::List(array) => {
1137 let datatype = ConcreteDataType::try_from(&array.value_type())?;
1139 let items = ScalarValue::convert_array_to_scalar_vec(array.as_ref())
1140 .context(ConvertArrowArrayToScalarsSnafu)?
1141 .into_iter()
1142 .flatten()
1143 .map(|x| x.try_into())
1144 .collect::<Result<Vec<Value>>>()?;
1145 Value::List(ListValue::new(items, Arc::new(datatype)))
1146 }
1147 ScalarValue::Date32(d) => d.map(|x| Value::Date(Date::new(x))).unwrap_or(Value::Null),
1148 ScalarValue::TimestampSecond(t, _) => t
1149 .map(|x| Value::Timestamp(Timestamp::new(x, TimeUnit::Second)))
1150 .unwrap_or(Value::Null),
1151 ScalarValue::TimestampMillisecond(t, _) => t
1152 .map(|x| Value::Timestamp(Timestamp::new(x, TimeUnit::Millisecond)))
1153 .unwrap_or(Value::Null),
1154 ScalarValue::TimestampMicrosecond(t, _) => t
1155 .map(|x| Value::Timestamp(Timestamp::new(x, TimeUnit::Microsecond)))
1156 .unwrap_or(Value::Null),
1157 ScalarValue::TimestampNanosecond(t, _) => t
1158 .map(|x| Value::Timestamp(Timestamp::new(x, TimeUnit::Nanosecond)))
1159 .unwrap_or(Value::Null),
1160 ScalarValue::Time32Second(t) => t
1161 .map(|x| Value::Time(Time::new(x as i64, TimeUnit::Second)))
1162 .unwrap_or(Value::Null),
1163 ScalarValue::Time32Millisecond(t) => t
1164 .map(|x| Value::Time(Time::new(x as i64, TimeUnit::Millisecond)))
1165 .unwrap_or(Value::Null),
1166 ScalarValue::Time64Microsecond(t) => t
1167 .map(|x| Value::Time(Time::new(x, TimeUnit::Microsecond)))
1168 .unwrap_or(Value::Null),
1169 ScalarValue::Time64Nanosecond(t) => t
1170 .map(|x| Value::Time(Time::new(x, TimeUnit::Nanosecond)))
1171 .unwrap_or(Value::Null),
1172
1173 ScalarValue::IntervalYearMonth(t) => t
1174 .map(|x| Value::IntervalYearMonth(IntervalYearMonth::from_i32(x)))
1175 .unwrap_or(Value::Null),
1176 ScalarValue::IntervalDayTime(t) => t
1177 .map(|x| Value::IntervalDayTime(IntervalDayTime::from(x)))
1178 .unwrap_or(Value::Null),
1179 ScalarValue::IntervalMonthDayNano(t) => t
1180 .map(|x| Value::IntervalMonthDayNano(IntervalMonthDayNano::from(x)))
1181 .unwrap_or(Value::Null),
1182 ScalarValue::DurationSecond(d) => d
1183 .map(|x| Value::Duration(Duration::new(x, TimeUnit::Second)))
1184 .unwrap_or(Value::Null),
1185 ScalarValue::DurationMillisecond(d) => d
1186 .map(|x| Value::Duration(Duration::new(x, TimeUnit::Millisecond)))
1187 .unwrap_or(Value::Null),
1188 ScalarValue::DurationMicrosecond(d) => d
1189 .map(|x| Value::Duration(Duration::new(x, TimeUnit::Microsecond)))
1190 .unwrap_or(Value::Null),
1191 ScalarValue::DurationNanosecond(d) => d
1192 .map(|x| Value::Duration(Duration::new(x, TimeUnit::Nanosecond)))
1193 .unwrap_or(Value::Null),
1194 ScalarValue::Decimal128(v, p, s) => v
1195 .map(|v| Value::Decimal128(Decimal128::new(v, p, s)))
1196 .unwrap_or(Value::Null),
1197 ScalarValue::Struct(struct_array) => {
1198 let struct_type: StructType = (struct_array.fields()).try_into()?;
1199 let items = struct_array
1200 .columns()
1201 .iter()
1202 .map(|array| {
1203 let field_scalar_value = ScalarValue::try_from_array(array.as_ref(), 0)
1205 .context(ConvertArrowArrayToScalarsSnafu)?;
1206 field_scalar_value.try_into()
1207 })
1208 .collect::<Result<Vec<Value>>>()?;
1209 Value::Struct(StructValue::try_new(items, struct_type)?)
1210 }
1211 ScalarValue::Decimal32(_, _, _)
1212 | ScalarValue::Decimal64(_, _, _)
1213 | ScalarValue::Decimal256(_, _, _)
1214 | ScalarValue::FixedSizeList(_)
1215 | ScalarValue::LargeList(_)
1216 | ScalarValue::Dictionary(_, _)
1217 | ScalarValue::Union(_, _, _)
1218 | ScalarValue::Float16(_)
1219 | ScalarValue::Utf8View(_)
1220 | ScalarValue::BinaryView(_)
1221 | ScalarValue::Map(_)
1222 | ScalarValue::Date64(_) => {
1223 return error::UnsupportedArrowTypeSnafu {
1224 arrow_type: v.data_type(),
1225 }
1226 .fail();
1227 }
1228 };
1229 Ok(v)
1230 }
1231}
1232
1233impl From<ValueRef<'_>> for Value {
1234 fn from(value: ValueRef<'_>) -> Self {
1235 match value {
1236 ValueRef::Null => Value::Null,
1237 ValueRef::Boolean(v) => Value::Boolean(v),
1238 ValueRef::UInt8(v) => Value::UInt8(v),
1239 ValueRef::UInt16(v) => Value::UInt16(v),
1240 ValueRef::UInt32(v) => Value::UInt32(v),
1241 ValueRef::UInt64(v) => Value::UInt64(v),
1242 ValueRef::Int8(v) => Value::Int8(v),
1243 ValueRef::Int16(v) => Value::Int16(v),
1244 ValueRef::Int32(v) => Value::Int32(v),
1245 ValueRef::Int64(v) => Value::Int64(v),
1246 ValueRef::Float32(v) => Value::Float32(v),
1247 ValueRef::Float64(v) => Value::Float64(v),
1248 ValueRef::String(v) => Value::String(v.into()),
1249 ValueRef::Binary(v) => Value::Binary(v.into()),
1250 ValueRef::Date(v) => Value::Date(v),
1251 ValueRef::Timestamp(v) => Value::Timestamp(v),
1252 ValueRef::Time(v) => Value::Time(v),
1253 ValueRef::IntervalYearMonth(v) => Value::IntervalYearMonth(v),
1254 ValueRef::IntervalDayTime(v) => Value::IntervalDayTime(v),
1255 ValueRef::IntervalMonthDayNano(v) => Value::IntervalMonthDayNano(v),
1256 ValueRef::Duration(v) => Value::Duration(v),
1257 ValueRef::List(v) => v.to_value(),
1258 ValueRef::Decimal128(v) => Value::Decimal128(v),
1259 ValueRef::Struct(v) => v.to_value(),
1260 ValueRef::Json(v) => Value::Json(Box::new(Value::from(*v))),
1261 }
1262 }
1263}
1264
1265#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1267pub enum ValueRef<'a> {
1268 Null,
1269
1270 Boolean(bool),
1272 UInt8(u8),
1273 UInt16(u16),
1274 UInt32(u32),
1275 UInt64(u64),
1276 Int8(i8),
1277 Int16(i16),
1278 Int32(i32),
1279 Int64(i64),
1280 Float32(OrderedF32),
1281 Float64(OrderedF64),
1282
1283 Decimal128(Decimal128),
1285
1286 String(&'a str),
1288 Binary(&'a [u8]),
1289
1290 Date(Date),
1292 Timestamp(Timestamp),
1293 Time(Time),
1294 Duration(Duration),
1295 IntervalYearMonth(IntervalYearMonth),
1297 IntervalDayTime(IntervalDayTime),
1298 IntervalMonthDayNano(IntervalMonthDayNano),
1299
1300 List(ListValueRef<'a>),
1302 Struct(StructValueRef<'a>),
1303
1304 Json(Box<ValueRef<'a>>),
1305}
1306
1307macro_rules! impl_as_for_value_ref {
1308 ($value: ident, $Variant: ident) => {
1309 match $value {
1310 ValueRef::Null => Ok(None),
1311 ValueRef::$Variant(v) => Ok(Some(v.clone())),
1312 ValueRef::Json(v) => match v.as_ref() {
1313 ValueRef::Null => Ok(None),
1314 ValueRef::$Variant(v) => Ok(Some(v.clone())),
1315 other => error::CastTypeSnafu {
1316 msg: format!(
1317 "Failed to cast value ref {:?} to {}",
1318 other,
1319 stringify!($Variant)
1320 ),
1321 }
1322 .fail(),
1323 },
1324 other => error::CastTypeSnafu {
1325 msg: format!(
1326 "Failed to cast value ref {:?} to {}",
1327 other,
1328 stringify!($Variant)
1329 ),
1330 }
1331 .fail(),
1332 }
1333 };
1334}
1335
1336impl<'a> ValueRef<'a> {
1337 define_data_type_func!(ValueRef);
1338
1339 pub fn is_null(&self) -> bool {
1341 match self {
1342 ValueRef::Null => true,
1343 ValueRef::Json(v) => v.is_null(),
1344 _ => false,
1345 }
1346 }
1347
1348 pub fn try_into_binary(&self) -> Result<Option<&'a [u8]>> {
1350 impl_as_for_value_ref!(self, Binary)
1351 }
1352
1353 pub fn try_into_string(&self) -> Result<Option<&'a str>> {
1355 impl_as_for_value_ref!(self, String)
1356 }
1357
1358 pub fn try_into_boolean(&self) -> Result<Option<bool>> {
1360 impl_as_for_value_ref!(self, Boolean)
1361 }
1362
1363 pub fn try_into_i8(&self) -> Result<Option<i8>> {
1364 impl_as_for_value_ref!(self, Int8)
1365 }
1366
1367 pub fn try_into_u8(&self) -> Result<Option<u8>> {
1368 impl_as_for_value_ref!(self, UInt8)
1369 }
1370
1371 pub fn try_into_i16(&self) -> Result<Option<i16>> {
1372 impl_as_for_value_ref!(self, Int16)
1373 }
1374
1375 pub fn try_into_u16(&self) -> Result<Option<u16>> {
1376 impl_as_for_value_ref!(self, UInt16)
1377 }
1378
1379 pub fn try_into_i32(&self) -> Result<Option<i32>> {
1380 impl_as_for_value_ref!(self, Int32)
1381 }
1382
1383 pub fn try_into_u32(&self) -> Result<Option<u32>> {
1384 impl_as_for_value_ref!(self, UInt32)
1385 }
1386
1387 pub fn try_into_i64(&self) -> Result<Option<i64>> {
1388 impl_as_for_value_ref!(self, Int64)
1389 }
1390
1391 pub fn try_into_u64(&self) -> Result<Option<u64>> {
1392 impl_as_for_value_ref!(self, UInt64)
1393 }
1394
1395 pub fn try_into_f32(&self) -> Result<Option<f32>> {
1396 match self {
1397 ValueRef::Null => Ok(None),
1398 ValueRef::Float32(f) => Ok(Some(f.0)),
1399 ValueRef::Json(v) => v.try_into_f32(),
1400 other => error::CastTypeSnafu {
1401 msg: format!("Failed to cast value ref {:?} to ValueRef::Float32", other,),
1402 }
1403 .fail(),
1404 }
1405 }
1406
1407 pub fn try_into_f64(&self) -> Result<Option<f64>> {
1408 match self {
1409 ValueRef::Null => Ok(None),
1410 ValueRef::Float64(f) => Ok(Some(f.0)),
1411 ValueRef::Json(v) => v.try_into_f64(),
1412 other => error::CastTypeSnafu {
1413 msg: format!("Failed to cast value ref {:?} to ValueRef::Float64", other,),
1414 }
1415 .fail(),
1416 }
1417 }
1418
1419 pub fn try_into_date(&self) -> Result<Option<Date>> {
1421 impl_as_for_value_ref!(self, Date)
1422 }
1423
1424 pub fn try_into_timestamp(&self) -> Result<Option<Timestamp>> {
1426 impl_as_for_value_ref!(self, Timestamp)
1427 }
1428
1429 pub fn try_into_time(&self) -> Result<Option<Time>> {
1431 impl_as_for_value_ref!(self, Time)
1432 }
1433
1434 pub fn try_into_duration(&self) -> Result<Option<Duration>> {
1435 impl_as_for_value_ref!(self, Duration)
1436 }
1437
1438 pub fn try_into_interval_year_month(&self) -> Result<Option<IntervalYearMonth>> {
1440 impl_as_for_value_ref!(self, IntervalYearMonth)
1441 }
1442
1443 pub fn try_into_interval_day_time(&self) -> Result<Option<IntervalDayTime>> {
1445 impl_as_for_value_ref!(self, IntervalDayTime)
1446 }
1447
1448 pub fn try_into_interval_month_day_nano(&self) -> Result<Option<IntervalMonthDayNano>> {
1450 impl_as_for_value_ref!(self, IntervalMonthDayNano)
1451 }
1452
1453 pub fn try_into_list(&self) -> Result<Option<ListValueRef<'_>>> {
1455 impl_as_for_value_ref!(self, List)
1456 }
1457
1458 pub fn try_into_struct(&self) -> Result<Option<StructValueRef<'_>>> {
1460 impl_as_for_value_ref!(self, Struct)
1461 }
1462
1463 pub fn try_into_decimal128(&self) -> Result<Option<Decimal128>> {
1465 impl_as_for_value_ref!(self, Decimal128)
1466 }
1467}
1468
1469impl PartialOrd for ValueRef<'_> {
1470 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1471 Some(self.cmp(other))
1472 }
1473}
1474
1475impl Ord for ValueRef<'_> {
1476 fn cmp(&self, other: &Self) -> Ordering {
1477 impl_ord_for_value_like!(ValueRef, self, other)
1478 }
1479}
1480
1481macro_rules! impl_value_ref_from {
1482 ($Variant:ident, $Type:ident) => {
1483 impl From<$Type> for ValueRef<'_> {
1484 fn from(value: $Type) -> Self {
1485 ValueRef::$Variant(value.into())
1486 }
1487 }
1488
1489 impl From<Option<$Type>> for ValueRef<'_> {
1490 fn from(value: Option<$Type>) -> Self {
1491 match value {
1492 Some(v) => ValueRef::$Variant(v.into()),
1493 None => ValueRef::Null,
1494 }
1495 }
1496 }
1497 };
1498}
1499
1500impl_value_ref_from!(Boolean, bool);
1501impl_value_ref_from!(UInt8, u8);
1502impl_value_ref_from!(UInt16, u16);
1503impl_value_ref_from!(UInt32, u32);
1504impl_value_ref_from!(UInt64, u64);
1505impl_value_ref_from!(Int8, i8);
1506impl_value_ref_from!(Int16, i16);
1507impl_value_ref_from!(Int32, i32);
1508impl_value_ref_from!(Int64, i64);
1509impl_value_ref_from!(Float32, f32);
1510impl_value_ref_from!(Float64, f64);
1511impl_value_ref_from!(Date, Date);
1512impl_value_ref_from!(Timestamp, Timestamp);
1513impl_value_ref_from!(Time, Time);
1514impl_value_ref_from!(IntervalYearMonth, IntervalYearMonth);
1515impl_value_ref_from!(IntervalDayTime, IntervalDayTime);
1516impl_value_ref_from!(IntervalMonthDayNano, IntervalMonthDayNano);
1517impl_value_ref_from!(Duration, Duration);
1518impl_value_ref_from!(Decimal128, Decimal128);
1519
1520impl<'a> From<&'a str> for ValueRef<'a> {
1521 fn from(string: &'a str) -> ValueRef<'a> {
1522 ValueRef::String(string)
1523 }
1524}
1525
1526impl<'a> From<&'a [u8]> for ValueRef<'a> {
1527 fn from(bytes: &'a [u8]) -> ValueRef<'a> {
1528 ValueRef::Binary(bytes)
1529 }
1530}
1531
1532impl<'a> From<Option<ListValueRef<'a>>> for ValueRef<'a> {
1533 fn from(list: Option<ListValueRef>) -> ValueRef {
1534 match list {
1535 Some(v) => ValueRef::List(v),
1536 None => ValueRef::Null,
1537 }
1538 }
1539}
1540
1541#[derive(Debug, Clone)]
1547pub enum ListValueRef<'a> {
1548 Indexed {
1550 vector: &'a ListVector,
1551 idx: usize,
1552 },
1553 Ref {
1554 val: &'a ListValue,
1555 },
1556 RefList {
1557 val: Vec<ValueRef<'a>>,
1558 item_datatype: Arc<ConcreteDataType>,
1559 },
1560}
1561
1562impl ListValueRef<'_> {
1563 fn to_value(&self) -> Value {
1565 match self {
1566 ListValueRef::Indexed { vector, idx } => vector.get(*idx),
1567 ListValueRef::Ref { val } => Value::List((*val).clone()),
1568 ListValueRef::RefList { val, item_datatype } => Value::List(ListValue::new(
1569 val.iter().map(|v| Value::from(v.clone())).collect(),
1570 item_datatype.clone(),
1571 )),
1572 }
1573 }
1574 fn datatype(&self) -> Arc<ConcreteDataType> {
1576 match self {
1577 ListValueRef::Indexed { vector, .. } => vector.item_type(),
1578 ListValueRef::Ref { val } => val.datatype().clone(),
1579 ListValueRef::RefList { item_datatype, .. } => item_datatype.clone(),
1580 }
1581 }
1582}
1583
1584impl Serialize for ListValueRef<'_> {
1585 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1586 match self {
1587 ListValueRef::Indexed { vector, idx } => match vector.get(*idx) {
1588 Value::List(v) => v.serialize(serializer),
1589 _ => unreachable!(),
1590 },
1591 ListValueRef::Ref { val } => val.serialize(serializer),
1592 ListValueRef::RefList { val, .. } => val.serialize(serializer),
1593 }
1594 }
1595}
1596
1597impl PartialEq for ListValueRef<'_> {
1598 fn eq(&self, other: &Self) -> bool {
1599 self.to_value().eq(&other.to_value())
1600 }
1601}
1602
1603impl Eq for ListValueRef<'_> {}
1604
1605impl Ord for ListValueRef<'_> {
1606 fn cmp(&self, other: &Self) -> Ordering {
1607 self.to_value().cmp(&other.to_value())
1609 }
1610}
1611
1612impl PartialOrd for ListValueRef<'_> {
1613 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1614 Some(self.cmp(other))
1615 }
1616}
1617
1618#[derive(Debug, Clone)]
1619pub enum StructValueRef<'a> {
1620 Indexed {
1621 vector: &'a StructVector,
1622 idx: usize,
1623 },
1624 Ref(&'a StructValue),
1625 RefList {
1626 val: Vec<ValueRef<'a>>,
1627 fields: StructType,
1628 },
1629}
1630
1631impl<'a> StructValueRef<'a> {
1632 pub fn to_value(&self) -> Value {
1633 match self {
1634 StructValueRef::Indexed { vector, idx } => vector.get(*idx),
1635 StructValueRef::Ref(val) => Value::Struct((*val).clone()),
1636 StructValueRef::RefList { val, fields } => {
1637 let items = val.iter().map(|v| Value::from(v.clone())).collect();
1638 Value::Struct(StructValue::try_new(items, fields.clone()).unwrap())
1639 }
1640 }
1641 }
1642
1643 pub fn struct_type(&self) -> &StructType {
1644 match self {
1645 StructValueRef::Indexed { vector, .. } => vector.struct_type(),
1646 StructValueRef::Ref(val) => val.struct_type(),
1647 StructValueRef::RefList { fields, .. } => fields,
1648 }
1649 }
1650}
1651
1652impl Serialize for StructValueRef<'_> {
1653 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1654 match self {
1655 StructValueRef::Indexed { vector, idx } => match vector.get(*idx) {
1656 Value::Struct(v) => v.serialize(serializer),
1657 _ => unreachable!(),
1658 },
1659 StructValueRef::Ref(val) => val.serialize(serializer),
1660 StructValueRef::RefList { val, .. } => val.serialize(serializer),
1661 }
1662 }
1663}
1664
1665impl PartialEq for StructValueRef<'_> {
1666 fn eq(&self, other: &Self) -> bool {
1667 self.to_value().eq(&other.to_value())
1668 }
1669}
1670
1671impl Eq for StructValueRef<'_> {}
1672
1673impl Ord for StructValueRef<'_> {
1674 fn cmp(&self, other: &Self) -> Ordering {
1675 self.to_value().cmp(&other.to_value())
1677 }
1678}
1679
1680impl PartialOrd for StructValueRef<'_> {
1681 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1682 Some(self.cmp(other))
1683 }
1684}
1685
1686impl ValueRef<'_> {
1687 pub fn data_size(&self) -> usize {
1690 match self {
1691 ValueRef::Null => 8,
1694 ValueRef::Boolean(_) => 1,
1695 ValueRef::UInt8(_) => 1,
1696 ValueRef::UInt16(_) => 2,
1697 ValueRef::UInt32(_) => 4,
1698 ValueRef::UInt64(_) => 8,
1699 ValueRef::Int8(_) => 1,
1700 ValueRef::Int16(_) => 2,
1701 ValueRef::Int32(_) => 4,
1702 ValueRef::Int64(_) => 8,
1703 ValueRef::Float32(_) => 4,
1704 ValueRef::Float64(_) => 8,
1705 ValueRef::String(v) => std::mem::size_of_val(*v),
1706 ValueRef::Binary(v) => std::mem::size_of_val(*v),
1707 ValueRef::Date(_) => 4,
1708 ValueRef::Timestamp(_) => 16,
1709 ValueRef::Time(_) => 16,
1710 ValueRef::Duration(_) => 16,
1711 ValueRef::IntervalYearMonth(_) => 4,
1712 ValueRef::IntervalDayTime(_) => 8,
1713 ValueRef::IntervalMonthDayNano(_) => 16,
1714 ValueRef::Decimal128(_) => 32,
1715 ValueRef::List(v) => match v {
1716 ListValueRef::Indexed { vector, .. } => vector.memory_size() / vector.len(),
1717 ListValueRef::Ref { val } => val.estimated_size(),
1718 ListValueRef::RefList { val, .. } => {
1719 val.iter().map(|v| v.data_size()).sum::<usize>()
1720 + std::mem::size_of::<Arc<ConcreteDataType>>()
1721 }
1722 },
1723 ValueRef::Struct(val) => match val {
1724 StructValueRef::Indexed { vector, .. } => vector.memory_size() / vector.len(),
1725 StructValueRef::Ref(val) => val.estimated_size(),
1726 StructValueRef::RefList { val, .. } => {
1727 val.iter().map(|v| v.data_size()).sum::<usize>()
1728 + std::mem::size_of::<StructType>()
1729 }
1730 },
1731 ValueRef::Json(v) => v.data_size(),
1732 }
1733 }
1734}
1735
1736#[cfg(test)]
1737pub(crate) mod tests {
1738 use arrow::datatypes::{DataType as ArrowDataType, Field};
1739 use common_time::timezone::set_default_timezone;
1740 use num_traits::Float;
1741
1742 use super::*;
1743 use crate::types::StructField;
1744 use crate::vectors::ListVectorBuilder;
1745
1746 pub(crate) fn build_struct_type() -> StructType {
1747 StructType::new(Arc::new(vec![
1748 StructField::new("id".to_string(), ConcreteDataType::int32_datatype(), false),
1749 StructField::new(
1750 "name".to_string(),
1751 ConcreteDataType::string_datatype(),
1752 true,
1753 ),
1754 StructField::new("age".to_string(), ConcreteDataType::uint8_datatype(), true),
1755 StructField::new(
1756 "address".to_string(),
1757 ConcreteDataType::string_datatype(),
1758 true,
1759 ),
1760 StructField::new(
1761 "awards".to_string(),
1762 ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::boolean_datatype())),
1763 true,
1764 ),
1765 ]))
1766 }
1767
1768 pub(crate) fn build_struct_value() -> StructValue {
1769 let struct_type = build_struct_type();
1770
1771 let struct_items = vec![
1772 Value::Int32(1),
1773 Value::String("tom".into()),
1774 Value::UInt8(25),
1775 Value::String("94038".into()),
1776 Value::List(build_list_value()),
1777 ];
1778 StructValue::try_new(struct_items, struct_type).unwrap()
1779 }
1780
1781 pub(crate) fn build_scalar_struct_value() -> ScalarValue {
1782 let struct_type = build_struct_type();
1783 let arrays = vec![
1784 ScalarValue::Int32(Some(1)).to_array().unwrap(),
1785 ScalarValue::Utf8(Some("tom".into())).to_array().unwrap(),
1786 ScalarValue::UInt8(Some(25)).to_array().unwrap(),
1787 ScalarValue::Utf8(Some("94038".into())).to_array().unwrap(),
1788 build_scalar_list_value().to_array().unwrap(),
1789 ];
1790 let struct_arrow_array = StructArray::new(struct_type.as_arrow_fields(), arrays, None);
1791 ScalarValue::Struct(Arc::new(struct_arrow_array))
1792 }
1793
1794 pub fn build_list_type() -> ConcreteDataType {
1795 ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::boolean_datatype()))
1796 }
1797
1798 pub(crate) fn build_list_value() -> ListValue {
1799 let items = vec![Value::Boolean(true), Value::Boolean(false)];
1800 ListValue::new(items, Arc::new(ConcreteDataType::boolean_datatype()))
1801 }
1802
1803 pub(crate) fn build_scalar_list_value() -> ScalarValue {
1804 let items = vec![
1805 ScalarValue::Boolean(Some(true)),
1806 ScalarValue::Boolean(Some(false)),
1807 ];
1808 ScalarValue::List(ScalarValue::new_list(&items, &ArrowDataType::Boolean, true))
1809 }
1810
1811 #[test]
1812 fn test_try_from_scalar_value() {
1813 assert_eq!(
1814 Value::Boolean(true),
1815 ScalarValue::Boolean(Some(true)).try_into().unwrap()
1816 );
1817 assert_eq!(
1818 Value::Boolean(false),
1819 ScalarValue::Boolean(Some(false)).try_into().unwrap()
1820 );
1821 assert_eq!(Value::Null, ScalarValue::Boolean(None).try_into().unwrap());
1822
1823 assert_eq!(
1824 Value::Float32(1.0f32.into()),
1825 ScalarValue::Float32(Some(1.0f32)).try_into().unwrap()
1826 );
1827 assert_eq!(Value::Null, ScalarValue::Float32(None).try_into().unwrap());
1828
1829 assert_eq!(
1830 Value::Float64(2.0f64.into()),
1831 ScalarValue::Float64(Some(2.0f64)).try_into().unwrap()
1832 );
1833 assert_eq!(Value::Null, ScalarValue::Float64(None).try_into().unwrap());
1834
1835 assert_eq!(
1836 Value::Int8(i8::MAX),
1837 ScalarValue::Int8(Some(i8::MAX)).try_into().unwrap()
1838 );
1839 assert_eq!(Value::Null, ScalarValue::Int8(None).try_into().unwrap());
1840
1841 assert_eq!(
1842 Value::Int16(i16::MAX),
1843 ScalarValue::Int16(Some(i16::MAX)).try_into().unwrap()
1844 );
1845 assert_eq!(Value::Null, ScalarValue::Int16(None).try_into().unwrap());
1846
1847 assert_eq!(
1848 Value::Int32(i32::MAX),
1849 ScalarValue::Int32(Some(i32::MAX)).try_into().unwrap()
1850 );
1851 assert_eq!(Value::Null, ScalarValue::Int32(None).try_into().unwrap());
1852
1853 assert_eq!(
1854 Value::Int64(i64::MAX),
1855 ScalarValue::Int64(Some(i64::MAX)).try_into().unwrap()
1856 );
1857 assert_eq!(Value::Null, ScalarValue::Int64(None).try_into().unwrap());
1858
1859 assert_eq!(
1860 Value::UInt8(u8::MAX),
1861 ScalarValue::UInt8(Some(u8::MAX)).try_into().unwrap()
1862 );
1863 assert_eq!(Value::Null, ScalarValue::UInt8(None).try_into().unwrap());
1864
1865 assert_eq!(
1866 Value::UInt16(u16::MAX),
1867 ScalarValue::UInt16(Some(u16::MAX)).try_into().unwrap()
1868 );
1869 assert_eq!(Value::Null, ScalarValue::UInt16(None).try_into().unwrap());
1870
1871 assert_eq!(
1872 Value::UInt32(u32::MAX),
1873 ScalarValue::UInt32(Some(u32::MAX)).try_into().unwrap()
1874 );
1875 assert_eq!(Value::Null, ScalarValue::UInt32(None).try_into().unwrap());
1876
1877 assert_eq!(
1878 Value::UInt64(u64::MAX),
1879 ScalarValue::UInt64(Some(u64::MAX)).try_into().unwrap()
1880 );
1881 assert_eq!(Value::Null, ScalarValue::UInt64(None).try_into().unwrap());
1882
1883 assert_eq!(
1884 Value::from("hello"),
1885 ScalarValue::Utf8(Some("hello".to_string()))
1886 .try_into()
1887 .unwrap()
1888 );
1889 assert_eq!(Value::Null, ScalarValue::Utf8(None).try_into().unwrap());
1890
1891 assert_eq!(
1892 Value::from("large_hello"),
1893 ScalarValue::LargeUtf8(Some("large_hello".to_string()))
1894 .try_into()
1895 .unwrap()
1896 );
1897 assert_eq!(
1898 Value::Null,
1899 ScalarValue::LargeUtf8(None).try_into().unwrap()
1900 );
1901
1902 assert_eq!(
1903 Value::from("world".as_bytes()),
1904 ScalarValue::Binary(Some("world".as_bytes().to_vec()))
1905 .try_into()
1906 .unwrap()
1907 );
1908 assert_eq!(Value::Null, ScalarValue::Binary(None).try_into().unwrap());
1909
1910 assert_eq!(
1911 Value::from("large_world".as_bytes()),
1912 ScalarValue::LargeBinary(Some("large_world".as_bytes().to_vec()))
1913 .try_into()
1914 .unwrap()
1915 );
1916 assert_eq!(
1917 Value::Null,
1918 ScalarValue::LargeBinary(None).try_into().unwrap()
1919 );
1920
1921 assert_eq!(
1922 Value::List(build_list_value()),
1923 build_scalar_list_value().try_into().unwrap()
1924 );
1925 assert_eq!(
1926 Value::List(ListValue::new(
1927 vec![],
1928 Arc::new(ConcreteDataType::uint32_datatype())
1929 )),
1930 ScalarValue::List(ScalarValue::new_list(&[], &ArrowDataType::UInt32, true))
1931 .try_into()
1932 .unwrap()
1933 );
1934
1935 assert_eq!(
1936 Value::Date(Date::new(123)),
1937 ScalarValue::Date32(Some(123)).try_into().unwrap()
1938 );
1939 assert_eq!(Value::Null, ScalarValue::Date32(None).try_into().unwrap());
1940
1941 assert_eq!(
1942 Value::Timestamp(Timestamp::new(1, TimeUnit::Second)),
1943 ScalarValue::TimestampSecond(Some(1), None)
1944 .try_into()
1945 .unwrap()
1946 );
1947 assert_eq!(
1948 Value::Null,
1949 ScalarValue::TimestampSecond(None, None).try_into().unwrap()
1950 );
1951
1952 assert_eq!(
1953 Value::Timestamp(Timestamp::new(1, TimeUnit::Millisecond)),
1954 ScalarValue::TimestampMillisecond(Some(1), None)
1955 .try_into()
1956 .unwrap()
1957 );
1958 assert_eq!(
1959 Value::Null,
1960 ScalarValue::TimestampMillisecond(None, None)
1961 .try_into()
1962 .unwrap()
1963 );
1964
1965 assert_eq!(
1966 Value::Timestamp(Timestamp::new(1, TimeUnit::Microsecond)),
1967 ScalarValue::TimestampMicrosecond(Some(1), None)
1968 .try_into()
1969 .unwrap()
1970 );
1971 assert_eq!(
1972 Value::Null,
1973 ScalarValue::TimestampMicrosecond(None, None)
1974 .try_into()
1975 .unwrap()
1976 );
1977
1978 assert_eq!(
1979 Value::Timestamp(Timestamp::new(1, TimeUnit::Nanosecond)),
1980 ScalarValue::TimestampNanosecond(Some(1), None)
1981 .try_into()
1982 .unwrap()
1983 );
1984 assert_eq!(
1985 Value::Null,
1986 ScalarValue::TimestampNanosecond(None, None)
1987 .try_into()
1988 .unwrap()
1989 );
1990 assert_eq!(
1991 Value::Null,
1992 ScalarValue::IntervalMonthDayNano(None).try_into().unwrap()
1993 );
1994 assert_eq!(
1995 Value::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 1, 1)),
1996 ScalarValue::IntervalMonthDayNano(Some(IntervalMonthDayNano::new(1, 1, 1).into()))
1997 .try_into()
1998 .unwrap()
1999 );
2000
2001 assert_eq!(
2002 Value::Time(Time::new(1, TimeUnit::Second)),
2003 ScalarValue::Time32Second(Some(1)).try_into().unwrap()
2004 );
2005 assert_eq!(
2006 Value::Null,
2007 ScalarValue::Time32Second(None).try_into().unwrap()
2008 );
2009
2010 assert_eq!(
2011 Value::Time(Time::new(1, TimeUnit::Millisecond)),
2012 ScalarValue::Time32Millisecond(Some(1)).try_into().unwrap()
2013 );
2014 assert_eq!(
2015 Value::Null,
2016 ScalarValue::Time32Millisecond(None).try_into().unwrap()
2017 );
2018
2019 assert_eq!(
2020 Value::Time(Time::new(1, TimeUnit::Microsecond)),
2021 ScalarValue::Time64Microsecond(Some(1)).try_into().unwrap()
2022 );
2023 assert_eq!(
2024 Value::Null,
2025 ScalarValue::Time64Microsecond(None).try_into().unwrap()
2026 );
2027
2028 assert_eq!(
2029 Value::Time(Time::new(1, TimeUnit::Nanosecond)),
2030 ScalarValue::Time64Nanosecond(Some(1)).try_into().unwrap()
2031 );
2032 assert_eq!(
2033 Value::Null,
2034 ScalarValue::Time64Nanosecond(None).try_into().unwrap()
2035 );
2036
2037 assert_eq!(
2038 Value::Duration(Duration::new_second(1)),
2039 ScalarValue::DurationSecond(Some(1)).try_into().unwrap()
2040 );
2041 assert_eq!(
2042 Value::Null,
2043 ScalarValue::DurationSecond(None).try_into().unwrap()
2044 );
2045
2046 assert_eq!(
2047 Value::Duration(Duration::new_millisecond(1)),
2048 ScalarValue::DurationMillisecond(Some(1))
2049 .try_into()
2050 .unwrap()
2051 );
2052 assert_eq!(
2053 Value::Null,
2054 ScalarValue::DurationMillisecond(None).try_into().unwrap()
2055 );
2056
2057 assert_eq!(
2058 Value::Duration(Duration::new_microsecond(1)),
2059 ScalarValue::DurationMicrosecond(Some(1))
2060 .try_into()
2061 .unwrap()
2062 );
2063 assert_eq!(
2064 Value::Null,
2065 ScalarValue::DurationMicrosecond(None).try_into().unwrap()
2066 );
2067
2068 assert_eq!(
2069 Value::Duration(Duration::new_nanosecond(1)),
2070 ScalarValue::DurationNanosecond(Some(1)).try_into().unwrap()
2071 );
2072 assert_eq!(
2073 Value::Null,
2074 ScalarValue::DurationNanosecond(None).try_into().unwrap()
2075 );
2076
2077 assert_eq!(
2078 Value::Decimal128(Decimal128::new(1, 38, 10)),
2079 ScalarValue::Decimal128(Some(1), 38, 10).try_into().unwrap()
2080 );
2081 assert_eq!(
2082 Value::Null,
2083 ScalarValue::Decimal128(None, 0, 0).try_into().unwrap()
2084 );
2085
2086 let struct_value = build_struct_value();
2087 let scalar_struct_value = build_scalar_struct_value();
2088 assert_eq!(
2089 Value::Struct(struct_value),
2090 scalar_struct_value.try_into().unwrap()
2091 );
2092 }
2093
2094 #[test]
2095 fn test_value_from_inner() {
2096 assert_eq!(Value::Boolean(true), Value::from(true));
2097 assert_eq!(Value::Boolean(false), Value::from(false));
2098
2099 assert_eq!(Value::UInt8(u8::MIN), Value::from(u8::MIN));
2100 assert_eq!(Value::UInt8(u8::MAX), Value::from(u8::MAX));
2101
2102 assert_eq!(Value::UInt16(u16::MIN), Value::from(u16::MIN));
2103 assert_eq!(Value::UInt16(u16::MAX), Value::from(u16::MAX));
2104
2105 assert_eq!(Value::UInt32(u32::MIN), Value::from(u32::MIN));
2106 assert_eq!(Value::UInt32(u32::MAX), Value::from(u32::MAX));
2107
2108 assert_eq!(Value::UInt64(u64::MIN), Value::from(u64::MIN));
2109 assert_eq!(Value::UInt64(u64::MAX), Value::from(u64::MAX));
2110
2111 assert_eq!(Value::Int8(i8::MIN), Value::from(i8::MIN));
2112 assert_eq!(Value::Int8(i8::MAX), Value::from(i8::MAX));
2113
2114 assert_eq!(Value::Int16(i16::MIN), Value::from(i16::MIN));
2115 assert_eq!(Value::Int16(i16::MAX), Value::from(i16::MAX));
2116
2117 assert_eq!(Value::Int32(i32::MIN), Value::from(i32::MIN));
2118 assert_eq!(Value::Int32(i32::MAX), Value::from(i32::MAX));
2119
2120 assert_eq!(Value::Int64(i64::MIN), Value::from(i64::MIN));
2121 assert_eq!(Value::Int64(i64::MAX), Value::from(i64::MAX));
2122
2123 assert_eq!(
2124 Value::Float32(OrderedFloat(f32::MIN)),
2125 Value::from(f32::MIN)
2126 );
2127 assert_eq!(
2128 Value::Float32(OrderedFloat(f32::MAX)),
2129 Value::from(f32::MAX)
2130 );
2131
2132 assert_eq!(
2133 Value::Float64(OrderedFloat(f64::MIN)),
2134 Value::from(f64::MIN)
2135 );
2136 assert_eq!(
2137 Value::Float64(OrderedFloat(f64::MAX)),
2138 Value::from(f64::MAX)
2139 );
2140
2141 let string_bytes = StringBytes::from("hello");
2142 assert_eq!(
2143 Value::String(string_bytes.clone()),
2144 Value::from(string_bytes)
2145 );
2146
2147 let bytes = Bytes::from(b"world".as_slice());
2148 assert_eq!(Value::Binary(bytes.clone()), Value::from(bytes));
2149 }
2150
2151 fn check_type_and_value(data_type: &ConcreteDataType, value: &Value) {
2152 assert_eq!(*data_type, value.data_type());
2153 assert_eq!(data_type.logical_type_id(), value.logical_type_id());
2154 }
2155
2156 #[test]
2157 fn test_value_datatype() {
2158 check_type_and_value(&ConcreteDataType::boolean_datatype(), &Value::Boolean(true));
2159 check_type_and_value(&ConcreteDataType::uint8_datatype(), &Value::UInt8(u8::MIN));
2160 check_type_and_value(
2161 &ConcreteDataType::uint16_datatype(),
2162 &Value::UInt16(u16::MIN),
2163 );
2164 check_type_and_value(
2165 &ConcreteDataType::uint16_datatype(),
2166 &Value::UInt16(u16::MAX),
2167 );
2168 check_type_and_value(
2169 &ConcreteDataType::uint32_datatype(),
2170 &Value::UInt32(u32::MIN),
2171 );
2172 check_type_and_value(
2173 &ConcreteDataType::uint64_datatype(),
2174 &Value::UInt64(u64::MIN),
2175 );
2176 check_type_and_value(&ConcreteDataType::int8_datatype(), &Value::Int8(i8::MIN));
2177 check_type_and_value(&ConcreteDataType::int16_datatype(), &Value::Int16(i16::MIN));
2178 check_type_and_value(&ConcreteDataType::int32_datatype(), &Value::Int32(i32::MIN));
2179 check_type_and_value(&ConcreteDataType::int64_datatype(), &Value::Int64(i64::MIN));
2180 check_type_and_value(
2181 &ConcreteDataType::float32_datatype(),
2182 &Value::Float32(OrderedFloat(f32::MIN)),
2183 );
2184 check_type_and_value(
2185 &ConcreteDataType::float64_datatype(),
2186 &Value::Float64(OrderedFloat(f64::MIN)),
2187 );
2188 check_type_and_value(
2189 &ConcreteDataType::string_datatype(),
2190 &Value::String(StringBytes::from("hello")),
2191 );
2192 check_type_and_value(
2193 &ConcreteDataType::binary_datatype(),
2194 &Value::Binary(Bytes::from(b"world".as_slice())),
2195 );
2196 let item_type = Arc::new(ConcreteDataType::int32_datatype());
2197 check_type_and_value(
2198 &ConcreteDataType::list_datatype(item_type.clone()),
2199 &Value::List(ListValue::new(vec![Value::Int32(10)], item_type.clone())),
2200 );
2201 check_type_and_value(
2202 &ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::null_datatype())),
2203 &Value::List(ListValue::default()),
2204 );
2205 check_type_and_value(
2206 &ConcreteDataType::date_datatype(),
2207 &Value::Date(Date::new(1)),
2208 );
2209 check_type_and_value(
2210 &ConcreteDataType::timestamp_millisecond_datatype(),
2211 &Value::Timestamp(Timestamp::new_millisecond(1)),
2212 );
2213 check_type_and_value(
2214 &ConcreteDataType::time_second_datatype(),
2215 &Value::Time(Time::new_second(1)),
2216 );
2217 check_type_and_value(
2218 &ConcreteDataType::time_millisecond_datatype(),
2219 &Value::Time(Time::new_millisecond(1)),
2220 );
2221 check_type_and_value(
2222 &ConcreteDataType::time_microsecond_datatype(),
2223 &Value::Time(Time::new_microsecond(1)),
2224 );
2225 check_type_and_value(
2226 &ConcreteDataType::time_nanosecond_datatype(),
2227 &Value::Time(Time::new_nanosecond(1)),
2228 );
2229 check_type_and_value(
2230 &ConcreteDataType::interval_year_month_datatype(),
2231 &Value::IntervalYearMonth(IntervalYearMonth::new(1)),
2232 );
2233 check_type_and_value(
2234 &ConcreteDataType::interval_day_time_datatype(),
2235 &Value::IntervalDayTime(IntervalDayTime::new(1, 2)),
2236 );
2237 check_type_and_value(
2238 &ConcreteDataType::interval_month_day_nano_datatype(),
2239 &Value::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 2, 3)),
2240 );
2241 check_type_and_value(
2242 &ConcreteDataType::duration_second_datatype(),
2243 &Value::Duration(Duration::new_second(1)),
2244 );
2245 check_type_and_value(
2246 &ConcreteDataType::duration_millisecond_datatype(),
2247 &Value::Duration(Duration::new_millisecond(1)),
2248 );
2249 check_type_and_value(
2250 &ConcreteDataType::duration_microsecond_datatype(),
2251 &Value::Duration(Duration::new_microsecond(1)),
2252 );
2253 check_type_and_value(
2254 &ConcreteDataType::duration_nanosecond_datatype(),
2255 &Value::Duration(Duration::new_nanosecond(1)),
2256 );
2257 check_type_and_value(
2258 &ConcreteDataType::decimal128_datatype(38, 10),
2259 &Value::Decimal128(Decimal128::new(1, 38, 10)),
2260 );
2261
2262 let item_type = Arc::new(ConcreteDataType::boolean_datatype());
2263 check_type_and_value(
2264 &ConcreteDataType::list_datatype(item_type.clone()),
2265 &Value::List(ListValue::new(
2266 vec![Value::Boolean(true)],
2267 item_type.clone(),
2268 )),
2269 );
2270
2271 check_type_and_value(
2272 &ConcreteDataType::struct_datatype(build_struct_type()),
2273 &Value::Struct(build_struct_value()),
2274 );
2275
2276 check_type_and_value(
2277 &ConcreteDataType::json_native_datatype(ConcreteDataType::boolean_datatype()),
2278 &Value::Json(Box::new(Value::Boolean(true))),
2279 );
2280
2281 check_type_and_value(
2282 &ConcreteDataType::json_native_datatype(build_list_type()),
2283 &Value::Json(Box::new(Value::List(build_list_value()))),
2284 );
2285
2286 check_type_and_value(
2287 &ConcreteDataType::json_native_datatype(ConcreteDataType::struct_datatype(
2288 build_struct_type(),
2289 )),
2290 &Value::Json(Box::new(Value::Struct(build_struct_value()))),
2291 );
2292 }
2293
2294 #[test]
2295 fn test_value_from_string() {
2296 let hello = "hello".to_string();
2297 assert_eq!(
2298 Value::String(StringBytes::from(hello.clone())),
2299 Value::from(hello)
2300 );
2301
2302 let world = "world";
2303 assert_eq!(Value::String(StringBytes::from(world)), Value::from(world));
2304 }
2305
2306 #[test]
2307 fn test_value_from_bytes() {
2308 let hello = b"hello".to_vec();
2309 assert_eq!(
2310 Value::Binary(Bytes::from(hello.clone())),
2311 Value::from(hello)
2312 );
2313
2314 let world: &[u8] = b"world";
2315 assert_eq!(Value::Binary(Bytes::from(world)), Value::from(world));
2316 }
2317
2318 fn to_json(value: Value) -> serde_json::Value {
2319 value.try_into().unwrap()
2320 }
2321
2322 #[test]
2323 fn test_to_json_value() {
2324 assert_eq!(serde_json::Value::Null, to_json(Value::Null));
2325 assert_eq!(serde_json::Value::Bool(true), to_json(Value::Boolean(true)));
2326 assert_eq!(
2327 serde_json::Value::Number(20u8.into()),
2328 to_json(Value::UInt8(20))
2329 );
2330 assert_eq!(
2331 serde_json::Value::Number(20i8.into()),
2332 to_json(Value::Int8(20))
2333 );
2334 assert_eq!(
2335 serde_json::Value::Number(2000u16.into()),
2336 to_json(Value::UInt16(2000))
2337 );
2338 assert_eq!(
2339 serde_json::Value::Number(2000i16.into()),
2340 to_json(Value::Int16(2000))
2341 );
2342 assert_eq!(
2343 serde_json::Value::Number(3000u32.into()),
2344 to_json(Value::UInt32(3000))
2345 );
2346 assert_eq!(
2347 serde_json::Value::Number(3000i32.into()),
2348 to_json(Value::Int32(3000))
2349 );
2350 assert_eq!(
2351 serde_json::Value::Number(4000u64.into()),
2352 to_json(Value::UInt64(4000))
2353 );
2354 assert_eq!(
2355 serde_json::Value::Number(4000i64.into()),
2356 to_json(Value::Int64(4000))
2357 );
2358 assert_eq!(
2359 serde_json::Value::from(125.0f32),
2360 to_json(Value::Float32(125.0.into()))
2361 );
2362 assert_eq!(
2363 serde_json::Value::from(125.0f64),
2364 to_json(Value::Float64(125.0.into()))
2365 );
2366 assert_eq!(
2367 serde_json::Value::String(String::from("hello")),
2368 to_json(Value::String(StringBytes::from("hello")))
2369 );
2370 assert_eq!(
2371 serde_json::Value::from(b"world".as_slice()),
2372 to_json(Value::Binary(Bytes::from(b"world".as_slice())))
2373 );
2374 assert_eq!(
2375 serde_json::Value::Number(5000i32.into()),
2376 to_json(Value::Date(Date::new(5000)))
2377 );
2378 assert_eq!(
2379 serde_json::Value::Number(1.into()),
2380 to_json(Value::Timestamp(Timestamp::new_millisecond(1)))
2381 );
2382 assert_eq!(
2383 serde_json::Value::Number(1.into()),
2384 to_json(Value::Time(Time::new_millisecond(1)))
2385 );
2386 assert_eq!(
2387 serde_json::Value::Number(1.into()),
2388 to_json(Value::Duration(Duration::new_millisecond(1)))
2389 );
2390
2391 let json_value: serde_json::Value = serde_json::from_str(r#"[123]"#).unwrap();
2392 assert_eq!(
2393 json_value,
2394 to_json(Value::List(ListValue {
2395 items: vec![Value::Int32(123)],
2396 datatype: Arc::new(ConcreteDataType::int32_datatype()),
2397 }))
2398 );
2399
2400 let struct_value = StructValue::try_new(
2401 vec![
2402 Value::Int64(42),
2403 Value::String("tomcat".into()),
2404 Value::Boolean(true),
2405 ],
2406 StructType::new(Arc::new(vec![
2407 StructField::new("num".to_string(), ConcreteDataType::int64_datatype(), true),
2408 StructField::new(
2409 "name".to_string(),
2410 ConcreteDataType::string_datatype(),
2411 true,
2412 ),
2413 StructField::new(
2414 "yes_or_no".to_string(),
2415 ConcreteDataType::boolean_datatype(),
2416 true,
2417 ),
2418 ])),
2419 )
2420 .unwrap();
2421 assert_eq!(
2422 serde_json::Value::try_from(Value::Struct(struct_value.clone())).unwrap(),
2423 serde_json::json!({
2424 "num": 42,
2425 "name": "tomcat",
2426 "yes_or_no": true
2427 })
2428 );
2429
2430 assert_eq!(
2432 serde_json::Value::try_from(Value::Json(Box::new(Value::String("hello".into()))))
2433 .unwrap(),
2434 serde_json::json!("hello")
2435 );
2436
2437 assert_eq!(
2439 serde_json::Value::try_from(Value::Json(Box::new(Value::List(ListValue::new(
2440 vec![Value::Int32(1), Value::Int32(2), Value::Int32(3),],
2441 Arc::new(ConcreteDataType::int32_datatype())
2442 )))))
2443 .unwrap(),
2444 serde_json::json!([1, 2, 3])
2445 );
2446
2447 assert_eq!(
2449 serde_json::Value::try_from(Value::Json(Box::new(Value::Struct(struct_value))))
2450 .unwrap(),
2451 serde_json::json!({
2452 "num": 42,
2453 "name": "tomcat",
2454 "yes_or_no": true
2455 })
2456 );
2457 }
2458
2459 #[test]
2460 fn test_null_value() {
2461 assert!(Value::Null.is_null());
2462 assert!(Value::Json(Box::new(Value::Null)).is_null());
2463 assert!(!Value::Boolean(true).is_null());
2464 assert!(Value::Null < Value::Boolean(false));
2465 assert!(Value::Boolean(true) > Value::Null);
2466 assert!(Value::Null < Value::Int32(10));
2467 assert!(Value::Int32(10) > Value::Null);
2468 }
2469
2470 #[test]
2471 fn test_null_value_ref() {
2472 assert!(ValueRef::Null.is_null());
2473 assert!(!ValueRef::Boolean(true).is_null());
2474 assert!(ValueRef::Null < ValueRef::Boolean(false));
2475 assert!(ValueRef::Boolean(true) > ValueRef::Null);
2476 assert!(ValueRef::Null < ValueRef::Int32(10));
2477 assert!(ValueRef::Int32(10) > ValueRef::Null);
2478 }
2479
2480 #[test]
2481 fn test_as_value_ref() {
2482 macro_rules! check_as_value_ref {
2483 ($Variant: ident, $data: expr) => {
2484 let value = Value::$Variant($data);
2485 let value_ref = value.as_value_ref();
2486 let expect_ref = ValueRef::$Variant($data);
2487
2488 assert_eq!(expect_ref, value_ref);
2489 };
2490 }
2491
2492 assert_eq!(ValueRef::Null, Value::Null.as_value_ref());
2493 check_as_value_ref!(Boolean, true);
2494 check_as_value_ref!(UInt8, 123);
2495 check_as_value_ref!(UInt16, 123);
2496 check_as_value_ref!(UInt32, 123);
2497 check_as_value_ref!(UInt64, 123);
2498 check_as_value_ref!(Int8, -12);
2499 check_as_value_ref!(Int16, -12);
2500 check_as_value_ref!(Int32, -12);
2501 check_as_value_ref!(Int64, -12);
2502 check_as_value_ref!(Float32, OrderedF32::from(16.0));
2503 check_as_value_ref!(Float64, OrderedF64::from(16.0));
2504 check_as_value_ref!(Timestamp, Timestamp::new_millisecond(1));
2505 check_as_value_ref!(Time, Time::new_millisecond(1));
2506 check_as_value_ref!(IntervalYearMonth, IntervalYearMonth::new(1));
2507 check_as_value_ref!(IntervalDayTime, IntervalDayTime::new(1, 2));
2508 check_as_value_ref!(IntervalMonthDayNano, IntervalMonthDayNano::new(1, 2, 3));
2509 check_as_value_ref!(Duration, Duration::new_millisecond(1));
2510
2511 assert_eq!(
2512 ValueRef::String("hello"),
2513 Value::String("hello".into()).as_value_ref()
2514 );
2515 assert_eq!(
2516 ValueRef::Binary(b"hello"),
2517 Value::Binary("hello".as_bytes().into()).as_value_ref()
2518 );
2519
2520 check_as_value_ref!(Date, Date::new(103));
2521
2522 let list = build_list_value();
2523 assert_eq!(
2524 ValueRef::List(ListValueRef::Ref { val: &list }),
2525 Value::List(list.clone()).as_value_ref()
2526 );
2527
2528 let jsonb_value = jsonb::parse_value(r#"{"key": "value"}"#.as_bytes())
2529 .unwrap()
2530 .to_vec();
2531 assert_eq!(
2532 ValueRef::Binary(jsonb_value.clone().as_slice()),
2533 Value::Binary(jsonb_value.into()).as_value_ref()
2534 );
2535
2536 let struct_value = build_struct_value();
2537 assert_eq!(
2538 ValueRef::Struct(StructValueRef::Ref(&struct_value)),
2539 Value::Struct(struct_value.clone()).as_value_ref()
2540 );
2541
2542 assert_eq!(
2543 ValueRef::Json(Box::new(ValueRef::Struct(StructValueRef::Ref(
2544 &struct_value
2545 )))),
2546 Value::Json(Box::new(Value::Struct(struct_value.clone()))).as_value_ref()
2547 );
2548 }
2549
2550 #[test]
2551 fn test_value_ref_as() {
2552 macro_rules! check_as_null {
2553 ($method: ident) => {
2554 assert_eq!(None, ValueRef::Null.$method().unwrap());
2555 };
2556 }
2557
2558 check_as_null!(try_into_binary);
2559 check_as_null!(try_into_string);
2560 check_as_null!(try_into_boolean);
2561 check_as_null!(try_into_list);
2562 check_as_null!(try_into_struct);
2563
2564 macro_rules! check_as_correct {
2565 ($data: expr, $Variant: ident, $method: ident) => {
2566 assert_eq!(Some($data), ValueRef::$Variant($data).$method().unwrap());
2567 };
2568 }
2569
2570 check_as_correct!("hello", String, try_into_string);
2571 check_as_correct!("hello".as_bytes(), Binary, try_into_binary);
2572 check_as_correct!(true, Boolean, try_into_boolean);
2573 check_as_correct!(Date::new(123), Date, try_into_date);
2574 check_as_correct!(Time::new_second(12), Time, try_into_time);
2575 check_as_correct!(Duration::new_second(12), Duration, try_into_duration);
2576
2577 let list = build_list_value();
2578 check_as_correct!(ListValueRef::Ref { val: &list }, List, try_into_list);
2579
2580 let struct_value = build_struct_value();
2581 check_as_correct!(StructValueRef::Ref(&struct_value), Struct, try_into_struct);
2582
2583 let wrong_value = ValueRef::Int32(12345);
2584 assert!(wrong_value.try_into_binary().is_err());
2585 assert!(wrong_value.try_into_string().is_err());
2586 assert!(wrong_value.try_into_boolean().is_err());
2587 assert!(wrong_value.try_into_list().is_err());
2588 assert!(wrong_value.try_into_struct().is_err());
2589 assert!(wrong_value.try_into_date().is_err());
2590 assert!(wrong_value.try_into_time().is_err());
2591 assert!(wrong_value.try_into_timestamp().is_err());
2592 assert!(wrong_value.try_into_duration().is_err());
2593 }
2594
2595 #[test]
2596 fn test_display() {
2597 set_default_timezone(Some("Asia/Shanghai")).unwrap();
2598 assert_eq!(Value::Null.to_string(), "Null");
2599 assert_eq!(Value::UInt8(8).to_string(), "8");
2600 assert_eq!(Value::UInt16(16).to_string(), "16");
2601 assert_eq!(Value::UInt32(32).to_string(), "32");
2602 assert_eq!(Value::UInt64(64).to_string(), "64");
2603 assert_eq!(Value::Int8(-8).to_string(), "-8");
2604 assert_eq!(Value::Int16(-16).to_string(), "-16");
2605 assert_eq!(Value::Int32(-32).to_string(), "-32");
2606 assert_eq!(Value::Int64(-64).to_string(), "-64");
2607 assert_eq!(Value::Float32((-32.123).into()).to_string(), "-32.123");
2608 assert_eq!(Value::Float64((-64.123).into()).to_string(), "-64.123");
2609 assert_eq!(Value::Float64(OrderedF64::infinity()).to_string(), "inf");
2610 assert_eq!(Value::Float64(OrderedF64::nan()).to_string(), "NaN");
2611 assert_eq!(Value::String(StringBytes::from("123")).to_string(), "123");
2612 assert_eq!(
2613 Value::Binary(Bytes::from(vec![1, 2, 3])).to_string(),
2614 "010203"
2615 );
2616 assert_eq!(Value::Date(Date::new(0)).to_string(), "1970-01-01");
2617 assert_eq!(
2618 Value::Timestamp(Timestamp::new(1000, TimeUnit::Millisecond)).to_string(),
2619 "1970-01-01 08:00:01+0800"
2620 );
2621 assert_eq!(
2622 Value::Time(Time::new(1000, TimeUnit::Millisecond)).to_string(),
2623 "08:00:01+0800"
2624 );
2625 assert_eq!(
2626 Value::Duration(Duration::new_millisecond(1000)).to_string(),
2627 "1000ms"
2628 );
2629 assert_eq!(
2630 Value::List(build_list_value()).to_string(),
2631 "Boolean[true, false]"
2632 );
2633 assert_eq!(
2634 Value::List(ListValue::new(
2635 vec![],
2636 Arc::new(ConcreteDataType::timestamp_second_datatype()),
2637 ))
2638 .to_string(),
2639 "TimestampSecond[]"
2640 );
2641 assert_eq!(
2642 Value::List(ListValue::new(
2643 vec![],
2644 Arc::new(ConcreteDataType::timestamp_millisecond_datatype()),
2645 ))
2646 .to_string(),
2647 "TimestampMillisecond[]"
2648 );
2649 assert_eq!(
2650 Value::List(ListValue::new(
2651 vec![],
2652 Arc::new(ConcreteDataType::timestamp_microsecond_datatype()),
2653 ))
2654 .to_string(),
2655 "TimestampMicrosecond[]"
2656 );
2657 assert_eq!(
2658 Value::List(ListValue::new(
2659 vec![],
2660 Arc::new(ConcreteDataType::timestamp_nanosecond_datatype()),
2661 ))
2662 .to_string(),
2663 "TimestampNanosecond[]"
2664 );
2665
2666 assert_eq!(
2667 Value::Struct(build_struct_value()).to_string(),
2668 "{ id: 1, name: tom, age: 25, address: 94038, awards: Boolean[true, false] }"
2669 );
2670
2671 assert_eq!(
2672 Value::Json(Box::new(Value::Struct(build_struct_value()))).to_string(),
2673 "Json({ id: 1, name: tom, age: 25, address: 94038, awards: Boolean[true, false] })"
2674 )
2675 }
2676
2677 #[test]
2678 fn test_not_null_value_to_scalar_value() {
2679 assert_eq!(
2680 ScalarValue::Boolean(Some(true)),
2681 Value::Boolean(true)
2682 .try_to_scalar_value(&ConcreteDataType::boolean_datatype())
2683 .unwrap()
2684 );
2685 assert_eq!(
2686 ScalarValue::Boolean(Some(false)),
2687 Value::Boolean(false)
2688 .try_to_scalar_value(&ConcreteDataType::boolean_datatype())
2689 .unwrap()
2690 );
2691 assert_eq!(
2692 ScalarValue::UInt8(Some(u8::MIN + 1)),
2693 Value::UInt8(u8::MIN + 1)
2694 .try_to_scalar_value(&ConcreteDataType::uint8_datatype())
2695 .unwrap()
2696 );
2697 assert_eq!(
2698 ScalarValue::UInt16(Some(u16::MIN + 2)),
2699 Value::UInt16(u16::MIN + 2)
2700 .try_to_scalar_value(&ConcreteDataType::uint16_datatype())
2701 .unwrap()
2702 );
2703 assert_eq!(
2704 ScalarValue::UInt32(Some(u32::MIN + 3)),
2705 Value::UInt32(u32::MIN + 3)
2706 .try_to_scalar_value(&ConcreteDataType::uint32_datatype())
2707 .unwrap()
2708 );
2709 assert_eq!(
2710 ScalarValue::UInt64(Some(u64::MIN + 4)),
2711 Value::UInt64(u64::MIN + 4)
2712 .try_to_scalar_value(&ConcreteDataType::uint64_datatype())
2713 .unwrap()
2714 );
2715 assert_eq!(
2716 ScalarValue::Int8(Some(i8::MIN + 4)),
2717 Value::Int8(i8::MIN + 4)
2718 .try_to_scalar_value(&ConcreteDataType::int8_datatype())
2719 .unwrap()
2720 );
2721 assert_eq!(
2722 ScalarValue::Int16(Some(i16::MIN + 5)),
2723 Value::Int16(i16::MIN + 5)
2724 .try_to_scalar_value(&ConcreteDataType::int16_datatype())
2725 .unwrap()
2726 );
2727 assert_eq!(
2728 ScalarValue::Int32(Some(i32::MIN + 6)),
2729 Value::Int32(i32::MIN + 6)
2730 .try_to_scalar_value(&ConcreteDataType::int32_datatype())
2731 .unwrap()
2732 );
2733 assert_eq!(
2734 ScalarValue::Int64(Some(i64::MIN + 7)),
2735 Value::Int64(i64::MIN + 7)
2736 .try_to_scalar_value(&ConcreteDataType::int64_datatype())
2737 .unwrap()
2738 );
2739 assert_eq!(
2740 ScalarValue::Float32(Some(8.0f32)),
2741 Value::Float32(OrderedFloat(8.0f32))
2742 .try_to_scalar_value(&ConcreteDataType::float32_datatype())
2743 .unwrap()
2744 );
2745 assert_eq!(
2746 ScalarValue::Float64(Some(9.0f64)),
2747 Value::Float64(OrderedFloat(9.0f64))
2748 .try_to_scalar_value(&ConcreteDataType::float64_datatype())
2749 .unwrap()
2750 );
2751 assert_eq!(
2752 ScalarValue::Utf8(Some("hello".to_string())),
2753 Value::String(StringBytes::from("hello"))
2754 .try_to_scalar_value(&ConcreteDataType::string_datatype(),)
2755 .unwrap()
2756 );
2757 assert_eq!(
2758 ScalarValue::Binary(Some("world".as_bytes().to_vec())),
2759 Value::Binary(Bytes::from("world".as_bytes()))
2760 .try_to_scalar_value(&ConcreteDataType::binary_datatype())
2761 .unwrap()
2762 );
2763
2764 let jsonb_value = jsonb::parse_value(r#"{"key": "value"}"#.as_bytes())
2765 .unwrap()
2766 .to_vec();
2767 assert_eq!(
2768 ScalarValue::Binary(Some(jsonb_value.clone())),
2769 Value::Binary(jsonb_value.into())
2770 .try_to_scalar_value(&ConcreteDataType::json_datatype())
2771 .unwrap()
2772 );
2773
2774 assert_eq!(
2775 build_scalar_struct_value(),
2776 Value::Struct(build_struct_value())
2777 .try_to_scalar_value(&ConcreteDataType::struct_datatype(build_struct_type()))
2778 .unwrap()
2779 );
2780
2781 assert_eq!(
2782 build_scalar_list_value(),
2783 Value::List(build_list_value())
2784 .try_to_scalar_value(&ConcreteDataType::list_datatype(Arc::new(
2785 ConcreteDataType::boolean_datatype()
2786 )))
2787 .unwrap()
2788 );
2789 }
2790
2791 #[test]
2792 fn test_null_value_to_scalar_value() {
2793 assert_eq!(
2794 ScalarValue::Boolean(None),
2795 Value::Null
2796 .try_to_scalar_value(&ConcreteDataType::boolean_datatype())
2797 .unwrap()
2798 );
2799 assert_eq!(
2800 ScalarValue::UInt8(None),
2801 Value::Null
2802 .try_to_scalar_value(&ConcreteDataType::uint8_datatype())
2803 .unwrap()
2804 );
2805 assert_eq!(
2806 ScalarValue::UInt16(None),
2807 Value::Null
2808 .try_to_scalar_value(&ConcreteDataType::uint16_datatype())
2809 .unwrap()
2810 );
2811 assert_eq!(
2812 ScalarValue::UInt32(None),
2813 Value::Null
2814 .try_to_scalar_value(&ConcreteDataType::uint32_datatype())
2815 .unwrap()
2816 );
2817 assert_eq!(
2818 ScalarValue::UInt64(None),
2819 Value::Null
2820 .try_to_scalar_value(&ConcreteDataType::uint64_datatype())
2821 .unwrap()
2822 );
2823 assert_eq!(
2824 ScalarValue::Int8(None),
2825 Value::Null
2826 .try_to_scalar_value(&ConcreteDataType::int8_datatype())
2827 .unwrap()
2828 );
2829 assert_eq!(
2830 ScalarValue::Int16(None),
2831 Value::Null
2832 .try_to_scalar_value(&ConcreteDataType::int16_datatype())
2833 .unwrap()
2834 );
2835 assert_eq!(
2836 ScalarValue::Int32(None),
2837 Value::Null
2838 .try_to_scalar_value(&ConcreteDataType::int32_datatype())
2839 .unwrap()
2840 );
2841 assert_eq!(
2842 ScalarValue::Int64(None),
2843 Value::Null
2844 .try_to_scalar_value(&ConcreteDataType::int64_datatype())
2845 .unwrap()
2846 );
2847 assert_eq!(
2848 ScalarValue::Float32(None),
2849 Value::Null
2850 .try_to_scalar_value(&ConcreteDataType::float32_datatype())
2851 .unwrap()
2852 );
2853 assert_eq!(
2854 ScalarValue::Float64(None),
2855 Value::Null
2856 .try_to_scalar_value(&ConcreteDataType::float64_datatype())
2857 .unwrap()
2858 );
2859 assert_eq!(
2860 ScalarValue::Utf8(None),
2861 Value::Null
2862 .try_to_scalar_value(&ConcreteDataType::string_datatype())
2863 .unwrap()
2864 );
2865 assert_eq!(
2866 ScalarValue::Binary(None),
2867 Value::Null
2868 .try_to_scalar_value(&ConcreteDataType::binary_datatype())
2869 .unwrap()
2870 );
2871
2872 assert_eq!(
2873 ScalarValue::Time32Second(None),
2874 Value::Null
2875 .try_to_scalar_value(&ConcreteDataType::time_second_datatype())
2876 .unwrap()
2877 );
2878 assert_eq!(
2879 ScalarValue::Time32Millisecond(None),
2880 Value::Null
2881 .try_to_scalar_value(&ConcreteDataType::time_millisecond_datatype())
2882 .unwrap()
2883 );
2884 assert_eq!(
2885 ScalarValue::Time64Microsecond(None),
2886 Value::Null
2887 .try_to_scalar_value(&ConcreteDataType::time_microsecond_datatype())
2888 .unwrap()
2889 );
2890 assert_eq!(
2891 ScalarValue::Time64Nanosecond(None),
2892 Value::Null
2893 .try_to_scalar_value(&ConcreteDataType::time_nanosecond_datatype())
2894 .unwrap()
2895 );
2896
2897 assert_eq!(
2898 ScalarValue::DurationSecond(None),
2899 Value::Null
2900 .try_to_scalar_value(&ConcreteDataType::duration_second_datatype())
2901 .unwrap()
2902 );
2903 assert_eq!(
2904 ScalarValue::DurationMillisecond(None),
2905 Value::Null
2906 .try_to_scalar_value(&ConcreteDataType::duration_millisecond_datatype())
2907 .unwrap()
2908 );
2909 assert_eq!(
2910 ScalarValue::DurationMicrosecond(None),
2911 Value::Null
2912 .try_to_scalar_value(&ConcreteDataType::duration_microsecond_datatype())
2913 .unwrap()
2914 );
2915 assert_eq!(
2916 ScalarValue::DurationNanosecond(None),
2917 Value::Null
2918 .try_to_scalar_value(&ConcreteDataType::duration_nanosecond_datatype())
2919 .unwrap()
2920 );
2921 assert_eq!(
2922 ScalarValue::Binary(None),
2923 Value::Null
2924 .try_to_scalar_value(&ConcreteDataType::json_datatype())
2925 .unwrap()
2926 );
2927
2928 assert_eq!(
2929 ScalarValue::new_null_list(ArrowDataType::Boolean, true, 1),
2930 Value::Null
2931 .try_to_scalar_value(&ConcreteDataType::list_datatype(Arc::new(
2932 ConcreteDataType::boolean_datatype()
2933 )))
2934 .unwrap()
2935 );
2936
2937 assert_eq!(
2938 ScalarStructBuilder::new_null(build_struct_type().as_arrow_fields()),
2939 Value::Null
2940 .try_to_scalar_value(&ConcreteDataType::struct_datatype(build_struct_type()))
2941 .unwrap()
2942 );
2943 }
2944
2945 #[test]
2946 fn test_list_value_to_scalar_value() {
2947 let items = vec![Value::Int32(-1), Value::Null];
2948 let item_type = Arc::new(ConcreteDataType::int32_datatype());
2949 let list = Value::List(ListValue::new(items, item_type.clone()));
2950 let df_list = list
2951 .try_to_scalar_value(&ConcreteDataType::list_datatype(item_type.clone()))
2952 .unwrap();
2953 assert!(matches!(df_list, ScalarValue::List(_)));
2954 match df_list {
2955 ScalarValue::List(vs) => {
2956 assert_eq!(
2957 ArrowDataType::List(Arc::new(Field::new_list_field(
2958 ArrowDataType::Int32,
2959 true
2960 ))),
2961 *vs.data_type()
2962 );
2963
2964 let vs = ScalarValue::convert_array_to_scalar_vec(vs.as_ref())
2965 .unwrap()
2966 .into_iter()
2967 .flatten()
2968 .collect::<Vec<_>>();
2969 assert_eq!(
2970 vs,
2971 vec![ScalarValue::Int32(Some(-1)), ScalarValue::Int32(None)]
2972 );
2973 }
2974 _ => unreachable!(),
2975 }
2976 }
2977
2978 #[test]
2979 fn test_struct_value_to_scalar_value() {
2980 let struct_value = build_struct_value();
2981 let scalar_value = struct_value
2982 .try_to_scalar_value(&build_struct_type())
2983 .unwrap();
2984
2985 assert_eq!(scalar_value, build_scalar_struct_value());
2986
2987 assert!(matches!(scalar_value, ScalarValue::Struct(_)));
2988 match scalar_value {
2989 ScalarValue::Struct(values) => {
2990 assert_eq!(&build_struct_type().as_arrow_fields(), values.fields());
2991
2992 assert_eq!(
2993 ScalarValue::try_from_array(values.column(0), 0).unwrap(),
2994 ScalarValue::Int32(Some(1))
2995 );
2996 assert_eq!(
2997 ScalarValue::try_from_array(values.column(1), 0).unwrap(),
2998 ScalarValue::Utf8(Some("tom".into()))
2999 );
3000 assert_eq!(
3001 ScalarValue::try_from_array(values.column(2), 0).unwrap(),
3002 ScalarValue::UInt8(Some(25))
3003 );
3004 assert_eq!(
3005 ScalarValue::try_from_array(values.column(3), 0).unwrap(),
3006 ScalarValue::Utf8(Some("94038".into()))
3007 );
3008 }
3009 _ => panic!("Unexpected value type"),
3010 }
3011 }
3012
3013 #[test]
3014 fn test_timestamp_to_scalar_value() {
3015 assert_eq!(
3016 ScalarValue::TimestampSecond(Some(1), None),
3017 timestamp_to_scalar_value(TimeUnit::Second, Some(1))
3018 );
3019 assert_eq!(
3020 ScalarValue::TimestampMillisecond(Some(1), None),
3021 timestamp_to_scalar_value(TimeUnit::Millisecond, Some(1))
3022 );
3023 assert_eq!(
3024 ScalarValue::TimestampMicrosecond(Some(1), None),
3025 timestamp_to_scalar_value(TimeUnit::Microsecond, Some(1))
3026 );
3027 assert_eq!(
3028 ScalarValue::TimestampNanosecond(Some(1), None),
3029 timestamp_to_scalar_value(TimeUnit::Nanosecond, Some(1))
3030 );
3031 }
3032
3033 #[test]
3034 fn test_time_to_scalar_value() {
3035 assert_eq!(
3036 ScalarValue::Time32Second(Some(1)),
3037 time_to_scalar_value(TimeUnit::Second, Some(1)).unwrap()
3038 );
3039 assert_eq!(
3040 ScalarValue::Time32Millisecond(Some(1)),
3041 time_to_scalar_value(TimeUnit::Millisecond, Some(1)).unwrap()
3042 );
3043 assert_eq!(
3044 ScalarValue::Time64Microsecond(Some(1)),
3045 time_to_scalar_value(TimeUnit::Microsecond, Some(1)).unwrap()
3046 );
3047 assert_eq!(
3048 ScalarValue::Time64Nanosecond(Some(1)),
3049 time_to_scalar_value(TimeUnit::Nanosecond, Some(1)).unwrap()
3050 );
3051 }
3052
3053 #[test]
3054 fn test_duration_to_scalar_value() {
3055 assert_eq!(
3056 ScalarValue::DurationSecond(Some(1)),
3057 duration_to_scalar_value(TimeUnit::Second, Some(1))
3058 );
3059 assert_eq!(
3060 ScalarValue::DurationMillisecond(Some(1)),
3061 duration_to_scalar_value(TimeUnit::Millisecond, Some(1))
3062 );
3063 assert_eq!(
3064 ScalarValue::DurationMicrosecond(Some(1)),
3065 duration_to_scalar_value(TimeUnit::Microsecond, Some(1))
3066 );
3067 assert_eq!(
3068 ScalarValue::DurationNanosecond(Some(1)),
3069 duration_to_scalar_value(TimeUnit::Nanosecond, Some(1))
3070 );
3071 }
3072
3073 fn check_value_ref_size_eq(value_ref: &ValueRef, size: usize) {
3074 assert_eq!(value_ref.data_size(), size);
3075 }
3076
3077 #[test]
3078 fn test_value_ref_estimated_size() {
3079 check_value_ref_size_eq(&ValueRef::Null, 8);
3080 check_value_ref_size_eq(&ValueRef::Boolean(true), 1);
3081 check_value_ref_size_eq(&ValueRef::UInt8(1), 1);
3082 check_value_ref_size_eq(&ValueRef::UInt16(1), 2);
3083 check_value_ref_size_eq(&ValueRef::UInt32(1), 4);
3084 check_value_ref_size_eq(&ValueRef::UInt64(1), 8);
3085 check_value_ref_size_eq(&ValueRef::Int8(1), 1);
3086 check_value_ref_size_eq(&ValueRef::Int16(1), 2);
3087 check_value_ref_size_eq(&ValueRef::Int32(1), 4);
3088 check_value_ref_size_eq(&ValueRef::Int64(1), 8);
3089 check_value_ref_size_eq(&ValueRef::Float32(1.0.into()), 4);
3090 check_value_ref_size_eq(&ValueRef::Float64(1.0.into()), 8);
3091 check_value_ref_size_eq(&ValueRef::String("greptimedb"), 10);
3092 check_value_ref_size_eq(&ValueRef::Binary(b"greptimedb"), 10);
3093 check_value_ref_size_eq(&ValueRef::Date(Date::new(1)), 4);
3094 check_value_ref_size_eq(&ValueRef::Timestamp(Timestamp::new_millisecond(1)), 16);
3095 check_value_ref_size_eq(&ValueRef::Time(Time::new_millisecond(1)), 16);
3096 check_value_ref_size_eq(&ValueRef::IntervalYearMonth(IntervalYearMonth::new(1)), 4);
3097 check_value_ref_size_eq(&ValueRef::IntervalDayTime(IntervalDayTime::new(1, 2)), 8);
3098 check_value_ref_size_eq(
3099 &ValueRef::IntervalMonthDayNano(IntervalMonthDayNano::new(1, 2, 3)),
3100 16,
3101 );
3102 check_value_ref_size_eq(&ValueRef::Duration(Duration::new_millisecond(1)), 16);
3103 check_value_ref_size_eq(
3104 &ValueRef::List(ListValueRef::Ref {
3105 val: &ListValue {
3106 items: vec![
3107 Value::String("hello world".into()),
3108 Value::String("greptimedb".into()),
3109 ],
3110 datatype: Arc::new(ConcreteDataType::string_datatype()),
3111 },
3112 }),
3113 30,
3114 );
3115
3116 let data = vec![
3117 Some(vec![Some(1), Some(2), Some(3)]),
3118 None,
3119 Some(vec![Some(4), None, Some(6)]),
3120 ];
3121 let item_type = Arc::new(ConcreteDataType::int32_datatype());
3122 let mut builder = ListVectorBuilder::with_type_capacity(item_type.clone(), 8);
3123 for vec_opt in &data {
3124 if let Some(vec) = vec_opt {
3125 let values = vec.iter().map(|v| Value::from(*v)).collect();
3126 let list_value = ListValue::new(values, item_type.clone());
3127
3128 builder.push(Some(ListValueRef::Ref { val: &list_value }));
3129 } else {
3130 builder.push(None);
3131 }
3132 }
3133 let vector = builder.finish();
3134
3135 check_value_ref_size_eq(
3136 &ValueRef::List(ListValueRef::Indexed {
3137 vector: &vector,
3138 idx: 0,
3139 }),
3140 74,
3141 );
3142 check_value_ref_size_eq(
3143 &ValueRef::List(ListValueRef::Indexed {
3144 vector: &vector,
3145 idx: 1,
3146 }),
3147 74,
3148 );
3149 check_value_ref_size_eq(
3150 &ValueRef::List(ListValueRef::Indexed {
3151 vector: &vector,
3152 idx: 2,
3153 }),
3154 74,
3155 );
3156 check_value_ref_size_eq(&ValueRef::Decimal128(Decimal128::new(1234, 3, 1)), 32);
3157
3158 check_value_ref_size_eq(
3159 &ValueRef::Struct(StructValueRef::Ref(&build_struct_value())),
3160 31,
3161 );
3162
3163 check_value_ref_size_eq(
3164 &ValueRef::Json(Box::new(ValueRef::Struct(StructValueRef::Ref(
3165 &build_struct_value(),
3166 )))),
3167 31,
3168 );
3169 }
3170
3171 #[test]
3172 fn test_incorrect_default_value_issue_3479() {
3173 let value = OrderedF64::from(0.047318541668048164);
3174 let serialized = serde_json::to_string(&value).unwrap();
3175 let deserialized: OrderedF64 = serde_json::from_str(&serialized).unwrap();
3176 assert_eq!(value, deserialized);
3177 }
3178}