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