-
Notifications
You must be signed in to change notification settings - Fork 178
/
values.rs
2257 lines (2078 loc) · 85.8 KB
/
values.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/*!
* Value in iceberg
*/
use std::str::FromStr;
use std::{any::Any, collections::BTreeMap};
use crate::error::Result;
use bitvec::vec::BitVec;
use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
use ordered_float::OrderedFloat;
use rust_decimal::Decimal;
use serde_bytes::ByteBuf;
use serde_json::{Map as JsonMap, Number, Value as JsonValue};
use uuid::Uuid;
use crate::{Error, ErrorKind};
use super::datatypes::{PrimitiveType, Type};
use super::MAX_DECIMAL_PRECISION;
pub use _serde::RawLiteral;
/// Values present in iceberg type
#[derive(Clone, Debug, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub enum PrimitiveLiteral {
/// 0x00 for false, non-zero byte for true
Boolean(bool),
/// Stored as 4-byte little-endian
Int(i32),
/// Stored as 8-byte little-endian
Long(i64),
/// Stored as 4-byte little-endian
Float(OrderedFloat<f32>),
/// Stored as 8-byte little-endian
Double(OrderedFloat<f64>),
/// Stores days from the 1970-01-01 in an 4-byte little-endian int
Date(i32),
/// Stores microseconds from midnight in an 8-byte little-endian long
Time(i64),
/// Timestamp without timezone
Timestamp(i64),
/// Timestamp with timezone
TimestampTZ(i64),
/// UTF-8 bytes (without length)
String(String),
/// 16-byte big-endian value
UUID(Uuid),
/// Binary value
Fixed(Vec<u8>),
/// Binary value (without length)
Binary(Vec<u8>),
/// Stores unscaled value as big int. According to iceberg spec, the precision must less than 38(`MAX_DECIMAL_PRECISION`) , so i128 is suit here.
Decimal(i128),
}
/// Values present in iceberg type
#[derive(Clone, Debug, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub enum Literal {
/// A primitive value
Primitive(PrimitiveLiteral),
/// A struct is a tuple of typed values. Each field in the tuple is named and has an integer id that is unique in the table schema.
/// Each field can be either optional or required, meaning that values can (or cannot) be null. Fields may be any type.
/// Fields may have an optional comment or doc string. Fields can have default values.
Struct(Struct),
/// A list is a collection of values with some element type.
/// The element field has an integer id that is unique in the table schema.
/// Elements can be either optional or required. Element types may be any type.
List(Vec<Option<Literal>>),
/// A map is a collection of key-value pairs with a key type and a value type.
/// Both the key field and value field each have an integer id that is unique in the table schema.
/// Map keys are required and map values can be either optional or required. Both map keys and map values may be any type, including nested types.
Map(BTreeMap<Literal, Option<Literal>>),
}
impl Literal {
/// Creates a boolean value.
///
/// Example:
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::bool(true);
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Boolean(true)), t);
/// ```
pub fn bool<T: Into<bool>>(t: T) -> Self {
Self::Primitive(PrimitiveLiteral::Boolean(t.into()))
}
/// Creates a boolean value from string.
/// See [Parse bool from str](https://doc.rust-lang.org/stable/std/primitive.bool.html#impl-FromStr-for-bool) for reference.
///
/// Example:
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::bool_from_str("false").unwrap();
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Boolean(false)), t);
/// ```
pub fn bool_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let v = s.as_ref().parse::<bool>().map_err(|e| {
Error::new(ErrorKind::DataInvalid, "Can't parse string to bool.").with_source(e)
})?;
Ok(Self::Primitive(PrimitiveLiteral::Boolean(v)))
}
/// Creates an 32bit integer.
///
/// Example:
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::int(23i8);
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Int(23)), t);
/// ```
pub fn int<T: Into<i32>>(t: T) -> Self {
Self::Primitive(PrimitiveLiteral::Int(t.into()))
}
/// Creates an 64bit integer.
///
/// Example:
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::long(24i8);
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Long(24)), t);
/// ```
pub fn long<T: Into<i64>>(t: T) -> Self {
Self::Primitive(PrimitiveLiteral::Long(t.into()))
}
/// Creates an 32bit floating point number.
///
/// Example:
/// ```rust
/// use ordered_float::OrderedFloat;
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::float( 32.1f32 );
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Float(OrderedFloat(32.1))), t);
/// ```
pub fn float<T: Into<f32>>(t: T) -> Self {
Self::Primitive(PrimitiveLiteral::Float(OrderedFloat(t.into())))
}
/// Creates an 32bit floating point number.
///
/// Example:
/// ```rust
/// use ordered_float::OrderedFloat;
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t = Literal::double( 32.1f64 );
///
/// assert_eq!(Literal::Primitive(PrimitiveLiteral::Double(OrderedFloat(32.1))), t);
/// ```
pub fn double<T: Into<f64>>(t: T) -> Self {
Self::Primitive(PrimitiveLiteral::Double(OrderedFloat(t.into())))
}
/// Returns unix epoch.
pub fn unix_epoch() -> DateTime<Utc> {
Utc.timestamp_nanos(0)
}
/// Creates date literal from number of days from unix epoch directly.
pub fn date(days: i32) -> Self {
Self::Primitive(PrimitiveLiteral::Date(days))
}
/// Creates date literal from `NaiveDate`, assuming it's utc timezone.
fn date_from_naive_date(date: NaiveDate) -> Self {
let days = (date - Self::unix_epoch().date_naive()).num_days();
Self::date(days as i32)
}
/// Creates a date in `%Y-%m-%d` format, assume in utc timezone.
///
/// See [`NaiveDate::from_str`].
///
/// Example
/// ```rust
/// use iceberg::spec::Literal;
/// let t = Literal::date_from_str("1970-01-03").unwrap();
///
/// assert_eq!(Literal::date(2), t);
/// ```
pub fn date_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let t = s.as_ref().parse::<NaiveDate>().map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Can't parse date from string: {}", s.as_ref()),
)
.with_source(e)
})?;
Ok(Self::date_from_naive_date(t))
}
/// Create a date from calendar date (year, month and day).
///
/// See [`NaiveDate::from_ymd_opt`].
///
/// Example:
///
///```rust
/// use iceberg::spec::Literal;
/// let t = Literal::date_from_ymd(1970, 1, 5).unwrap();
///
/// assert_eq!(Literal::date(4), t);
/// ```
pub fn date_from_ymd(year: i32, month: u32, day: u32) -> Result<Self> {
let t = NaiveDate::from_ymd_opt(year, month, day).ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!("Can't create date from year: {year}, month: {month}, day: {day}"),
)
})?;
Ok(Self::date_from_naive_date(t))
}
/// Creates time in microseconds directly
pub fn time(value: i64) -> Self {
Self::Primitive(PrimitiveLiteral::Time(value))
}
/// Creates time literal from [`chrono::NaiveTime`].
fn time_from_naive_time(t: NaiveTime) -> Self {
let duration = t - Self::unix_epoch().time();
// It's safe to unwrap here since less than 24 hours will never overflow.
let micro_secs = duration.num_microseconds().unwrap();
Literal::time(micro_secs)
}
/// Creates time in microseconds in `%H:%M:%S:.f` format.
///
/// See [`NaiveTime::from_str`] for details.
///
/// Example:
/// ```rust
/// use iceberg::spec::Literal;
/// let t = Literal::time_from_str("01:02:01.888999777").unwrap();
///
/// let micro_secs = {
/// 1 * 3600 * 1_000_000 + // 1 hour
/// 2 * 60 * 1_000_000 + // 2 minutes
/// 1 * 1_000_000 + // 1 second
/// 888999 // microseconds
/// };
/// assert_eq!(Literal::time(micro_secs), t);
/// ```
pub fn time_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let t = s.as_ref().parse::<NaiveTime>().map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Can't parse time from string: {}", s.as_ref()),
)
.with_source(e)
})?;
Ok(Self::time_from_naive_time(t))
}
/// Creates time literal from hour, minute, second, and microseconds.
///
/// See [`NaiveTime::from_hms_micro_opt`].
///
/// Example:
/// ```rust
///
/// use iceberg::spec::Literal;
/// let t = Literal::time_from_hms_micro(22, 15, 33, 111).unwrap();
///
/// assert_eq!(Literal::time_from_str("22:15:33.000111").unwrap(), t);
/// ```
pub fn time_from_hms_micro(hour: u32, min: u32, sec: u32, micro: u32) -> Result<Self> {
let t = NaiveTime::from_hms_micro_opt(hour, min, sec, micro)
.ok_or_else(|| Error::new(
ErrorKind::DataInvalid,
format!("Can't create time from hour: {hour}, min: {min}, second: {sec}, microsecond: {micro}"),
))?;
Ok(Self::time_from_naive_time(t))
}
/// Creates a timestamp from unix epoch in microseconds.
pub fn timestamp(value: i64) -> Self {
Self::Primitive(PrimitiveLiteral::Timestamp(value))
}
/// Creates a timestamp with timezone from unix epoch in microseconds.
pub fn timestamptz(value: i64) -> Self {
Self::Primitive(PrimitiveLiteral::TimestampTZ(value))
}
/// Creates a timestamp from [`DateTime`].
pub fn timestamp_from_datetime<T: TimeZone>(dt: DateTime<T>) -> Self {
Self::timestamp(dt.with_timezone(&Utc).timestamp_micros())
}
/// Creates a timestamp with timezone from [`DateTime`].
pub fn timestamptz_from_datetime<T: TimeZone>(dt: DateTime<T>) -> Self {
Self::timestamptz(dt.with_timezone(&Utc).timestamp_micros())
}
/// Parse a timestamp in RFC3339 format.
///
/// See [`DateTime<Utc>::from_str`].
///
/// Example:
///
/// ```rust
/// use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime};
/// use iceberg::spec::Literal;
/// let t = Literal::timestamp_from_str("2012-12-12 12:12:12.8899-04:00").unwrap();
///
/// let t2 = {
/// let date = NaiveDate::from_ymd_opt(2012, 12, 12).unwrap();
/// let time = NaiveTime::from_hms_micro_opt(12, 12, 12, 889900).unwrap();
/// let dt = NaiveDateTime::new(date, time);
/// Literal::timestamp_from_datetime(DateTime::<FixedOffset>::from_local(dt, FixedOffset::west_opt(4 * 3600).unwrap()))
/// };
///
/// assert_eq!(t, t2);
/// ```
pub fn timestamp_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let dt = DateTime::<Utc>::from_str(s.as_ref()).map_err(|e| {
Error::new(ErrorKind::DataInvalid, "Can't parse datetime.").with_source(e)
})?;
Ok(Self::timestamp_from_datetime(dt))
}
/// Similar to [`Literal::timestamp_from_str`], but return timestamp with timezone literal.
pub fn timestamptz_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let dt = DateTime::<Utc>::from_str(s.as_ref()).map_err(|e| {
Error::new(ErrorKind::DataInvalid, "Can't parse datetime.").with_source(e)
})?;
Ok(Self::timestamptz_from_datetime(dt))
}
/// Creates a string literal.
pub fn string<S: ToString>(s: S) -> Self {
Self::Primitive(PrimitiveLiteral::String(s.to_string()))
}
/// Creates uuid literal.
pub fn uuid(uuid: Uuid) -> Self {
Self::Primitive(PrimitiveLiteral::UUID(uuid))
}
/// Creates uuid from str. See [`Uuid::parse_str`].
///
/// Example:
///
/// ```rust
/// use uuid::Uuid;
/// use iceberg::spec::Literal;
/// let t1 = Literal::uuid_from_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
/// let t2 = Literal::uuid(Uuid::from_u128_le(0xd8d7d6d5d4d3d2d1c2c1b2b1a4a3a2a1));
///
/// assert_eq!(t1, t2);
/// ```
pub fn uuid_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let uuid = Uuid::parse_str(s.as_ref()).map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Can't parse uuid from string: {}", s.as_ref()),
)
.with_source(e)
})?;
Ok(Self::uuid(uuid))
}
/// Creates a fixed literal from bytes.
///
/// Example:
///
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t1 = Literal::fixed(vec![1u8, 2u8]);
/// let t2 = Literal::Primitive(PrimitiveLiteral::Fixed(vec![1u8, 2u8]));
///
/// assert_eq!(t1, t2);
/// ```
pub fn fixed<I: IntoIterator<Item = u8>>(input: I) -> Self {
Literal::Primitive(PrimitiveLiteral::Fixed(input.into_iter().collect()))
}
/// Creates a binary literal from bytes.
///
/// Example:
///
/// ```rust
/// use iceberg::spec::{Literal, PrimitiveLiteral};
/// let t1 = Literal::binary(vec![1u8, 2u8]);
/// let t2 = Literal::Primitive(PrimitiveLiteral::Binary(vec![1u8, 2u8]));
///
/// assert_eq!(t1, t2);
/// ```
pub fn binary<I: IntoIterator<Item = u8>>(input: I) -> Self {
Literal::Primitive(PrimitiveLiteral::Binary(input.into_iter().collect()))
}
/// Creates a decimal literal.
pub fn decimal(decimal: i128) -> Self {
Self::Primitive(PrimitiveLiteral::Decimal(decimal))
}
/// Creates decimal literal from string. See [`Decimal::from_str_exact`].
///
/// Example:
///
/// ```rust
/// use rust_decimal::Decimal;
/// use iceberg::spec::Literal;
/// let t1 = Literal::decimal(12345);
/// let t2 = Literal::decimal_from_str("123.45").unwrap();
///
/// assert_eq!(t1, t2);
/// ```
pub fn decimal_from_str<S: AsRef<str>>(s: S) -> Result<Self> {
let decimal = Decimal::from_str_exact(s.as_ref()).map_err(|e| {
Error::new(ErrorKind::DataInvalid, "Can't parse decimal.").with_source(e)
})?;
Ok(Self::decimal(decimal.mantissa()))
}
}
impl From<Literal> for ByteBuf {
fn from(value: Literal) -> Self {
match value {
Literal::Primitive(prim) => match prim {
PrimitiveLiteral::Boolean(val) => {
if val {
ByteBuf::from([1u8])
} else {
ByteBuf::from([0u8])
}
}
PrimitiveLiteral::Int(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Long(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Float(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Double(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Date(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Time(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::Timestamp(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::TimestampTZ(val) => ByteBuf::from(val.to_le_bytes()),
PrimitiveLiteral::String(val) => ByteBuf::from(val.as_bytes()),
PrimitiveLiteral::UUID(val) => ByteBuf::from(val.as_u128().to_be_bytes()),
PrimitiveLiteral::Fixed(val) => ByteBuf::from(val),
PrimitiveLiteral::Binary(val) => ByteBuf::from(val),
PrimitiveLiteral::Decimal(_) => todo!(),
},
_ => unimplemented!(),
}
}
}
impl From<Literal> for Vec<u8> {
fn from(value: Literal) -> Self {
match value {
Literal::Primitive(prim) => match prim {
PrimitiveLiteral::Boolean(val) => {
if val {
Vec::from([1u8])
} else {
Vec::from([0u8])
}
}
PrimitiveLiteral::Int(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Long(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Float(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Double(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Date(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Time(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::Timestamp(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::TimestampTZ(val) => Vec::from(val.to_le_bytes()),
PrimitiveLiteral::String(val) => Vec::from(val.as_bytes()),
PrimitiveLiteral::UUID(val) => Vec::from(val.as_u128().to_be_bytes()),
PrimitiveLiteral::Fixed(val) => val,
PrimitiveLiteral::Binary(val) => val,
PrimitiveLiteral::Decimal(_) => todo!(),
},
_ => unimplemented!(),
}
}
}
impl From<&Literal> for JsonValue {
fn from(value: &Literal) -> Self {
match value {
Literal::Primitive(prim) => match prim {
PrimitiveLiteral::Boolean(val) => JsonValue::Bool(*val),
PrimitiveLiteral::Int(val) => JsonValue::Number((*val).into()),
PrimitiveLiteral::Long(val) => JsonValue::Number((*val).into()),
PrimitiveLiteral::Float(val) => match Number::from_f64(val.0 as f64) {
Some(number) => JsonValue::Number(number),
None => JsonValue::Null,
},
PrimitiveLiteral::Double(val) => match Number::from_f64(val.0) {
Some(number) => JsonValue::Number(number),
None => JsonValue::Null,
},
PrimitiveLiteral::Date(val) => {
JsonValue::String(date::days_to_date(*val).to_string())
}
PrimitiveLiteral::Time(val) => {
JsonValue::String(time::microseconds_to_time(*val).to_string())
}
PrimitiveLiteral::Timestamp(val) => JsonValue::String(
timestamp::microseconds_to_datetime(*val)
.format("%Y-%m-%dT%H:%M:%S%.f")
.to_string(),
),
PrimitiveLiteral::TimestampTZ(val) => JsonValue::String(
timestamptz::microseconds_to_datetimetz(*val)
.format("%Y-%m-%dT%H:%M:%S%.f+00:00")
.to_string(),
),
PrimitiveLiteral::String(val) => JsonValue::String(val.clone()),
PrimitiveLiteral::UUID(val) => JsonValue::String(val.to_string()),
PrimitiveLiteral::Fixed(val) => {
JsonValue::String(val.iter().fold(String::new(), |mut acc, x| {
acc.push_str(&format!("{:x}", x));
acc
}))
}
PrimitiveLiteral::Binary(val) => {
JsonValue::String(val.iter().fold(String::new(), |mut acc, x| {
acc.push_str(&format!("{:x}", x));
acc
}))
}
PrimitiveLiteral::Decimal(_) => todo!(),
},
Literal::Struct(s) => {
JsonValue::Object(JsonMap::from_iter(s.iter().map(|(id, value, _)| {
let json: JsonValue = match value {
Some(val) => val.into(),
None => JsonValue::Null,
};
(id.to_string(), json)
})))
}
Literal::List(list) => JsonValue::Array(
list.iter()
.map(|opt| match opt {
Some(literal) => literal.into(),
None => JsonValue::Null,
})
.collect(),
),
Literal::Map(map) => {
let mut object = JsonMap::with_capacity(2);
object.insert(
"keys".to_string(),
JsonValue::Array(map.keys().map(|literal| literal.into()).collect()),
);
object.insert(
"values".to_string(),
JsonValue::Array(
map.values()
.map(|literal| match literal {
Some(literal) => literal.into(),
None => JsonValue::Null,
})
.collect(),
),
);
JsonValue::Object(object)
}
}
}
}
/// The partition struct stores the tuple of partition values for each file.
/// Its type is derived from the partition fields of the partition spec used to write the manifest file.
/// In v2, the partition struct’s field ids must match the ids from the partition spec.
#[derive(Debug, Clone, PartialEq, Hash, Eq, PartialOrd, Ord)]
pub struct Struct {
/// Vector to store the field values
fields: Vec<Literal>,
/// Vector to store the field ids
field_ids: Vec<i32>,
/// Vector to store the field names
field_names: Vec<String>,
/// Null bitmap
null_bitmap: BitVec,
}
impl Struct {
/// Create a iterator to read the field in order of (field_id, field_value, field_name).
pub fn iter(&self) -> impl Iterator<Item = (&i32, Option<&Literal>, &str)> {
self.null_bitmap
.iter()
.zip(self.fields.iter())
.zip(self.field_ids.iter())
.zip(self.field_names.iter())
.map(|(((null, value), id), name)| {
(id, if *null { None } else { Some(value) }, name.as_str())
})
}
}
/// An iterator that moves out of a struct.
pub struct StructValueIntoIter {
null_bitmap: bitvec::boxed::IntoIter,
fields: std::vec::IntoIter<Literal>,
}
impl Iterator for StructValueIntoIter {
type Item = Option<Literal>;
fn next(&mut self) -> Option<Self::Item> {
match (self.null_bitmap.next(), self.fields.next()) {
(Some(null), Some(value)) => Some(if null { None } else { Some(value) }),
_ => None,
}
}
}
impl IntoIterator for Struct {
type Item = Option<Literal>;
type IntoIter = StructValueIntoIter;
fn into_iter(self) -> Self::IntoIter {
StructValueIntoIter {
null_bitmap: self.null_bitmap.into_iter(),
fields: self.fields.into_iter(),
}
}
}
impl FromIterator<(i32, Option<Literal>, String)> for Struct {
fn from_iter<I: IntoIterator<Item = (i32, Option<Literal>, String)>>(iter: I) -> Self {
let mut fields = Vec::new();
let mut field_ids = Vec::new();
let mut field_names = Vec::new();
let mut null_bitmap = BitVec::new();
for (id, value, name) in iter.into_iter() {
field_ids.push(id);
field_names.push(name);
match value {
Some(value) => {
fields.push(value);
null_bitmap.push(false)
}
None => {
fields.push(Literal::Primitive(PrimitiveLiteral::Boolean(false)));
null_bitmap.push(true)
}
}
}
Struct {
fields,
field_ids,
field_names,
null_bitmap,
}
}
}
impl Literal {
/// Create iceberg value from bytes
pub fn try_from_bytes(bytes: &[u8], data_type: &Type) -> Result<Self> {
match data_type {
Type::Primitive(primitive) => match primitive {
PrimitiveType::Boolean => {
if bytes.len() == 1 && bytes[0] == 0u8 {
Ok(Literal::Primitive(PrimitiveLiteral::Boolean(false)))
} else {
Ok(Literal::Primitive(PrimitiveLiteral::Boolean(true)))
}
}
PrimitiveType::Int => Ok(Literal::Primitive(PrimitiveLiteral::Int(
i32::from_le_bytes(bytes.try_into()?),
))),
PrimitiveType::Long => Ok(Literal::Primitive(PrimitiveLiteral::Long(
i64::from_le_bytes(bytes.try_into()?),
))),
PrimitiveType::Float => Ok(Literal::Primitive(PrimitiveLiteral::Float(
OrderedFloat(f32::from_le_bytes(bytes.try_into()?)),
))),
PrimitiveType::Double => Ok(Literal::Primitive(PrimitiveLiteral::Double(
OrderedFloat(f64::from_le_bytes(bytes.try_into()?)),
))),
PrimitiveType::Date => Ok(Literal::Primitive(PrimitiveLiteral::Date(
i32::from_le_bytes(bytes.try_into()?),
))),
PrimitiveType::Time => Ok(Literal::Primitive(PrimitiveLiteral::Time(
i64::from_le_bytes(bytes.try_into()?),
))),
PrimitiveType::Timestamp => Ok(Literal::Primitive(PrimitiveLiteral::Timestamp(
i64::from_le_bytes(bytes.try_into()?),
))),
PrimitiveType::Timestamptz => Ok(Literal::Primitive(
PrimitiveLiteral::TimestampTZ(i64::from_le_bytes(bytes.try_into()?)),
)),
PrimitiveType::String => Ok(Literal::Primitive(PrimitiveLiteral::String(
std::str::from_utf8(bytes)?.to_string(),
))),
PrimitiveType::Uuid => Ok(Literal::Primitive(PrimitiveLiteral::UUID(
Uuid::from_u128(u128::from_be_bytes(bytes.try_into()?)),
))),
PrimitiveType::Fixed(_) => Ok(Literal::Primitive(PrimitiveLiteral::Fixed(
Vec::from(bytes),
))),
PrimitiveType::Binary => Ok(Literal::Primitive(PrimitiveLiteral::Binary(
Vec::from(bytes),
))),
PrimitiveType::Decimal {
precision: _,
scale: _,
} => todo!(),
},
_ => Err(Error::new(
crate::ErrorKind::DataInvalid,
"Converting bytes to non-primitive types is not supported.",
)),
}
}
/// Create iceberg value from a json value
pub fn try_from_json(value: JsonValue, data_type: &Type) -> Result<Option<Self>> {
match data_type {
Type::Primitive(primitive) => match (primitive, value) {
(PrimitiveType::Boolean, JsonValue::Bool(bool)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::Boolean(bool))))
}
(PrimitiveType::Int, JsonValue::Number(number)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::Int(
number
.as_i64()
.ok_or(Error::new(
crate::ErrorKind::DataInvalid,
"Failed to convert json number to int",
))?
.try_into()?,
))))
}
(PrimitiveType::Long, JsonValue::Number(number)) => Ok(Some(Literal::Primitive(
PrimitiveLiteral::Long(number.as_i64().ok_or(Error::new(
crate::ErrorKind::DataInvalid,
"Failed to convert json number to long",
))?),
))),
(PrimitiveType::Float, JsonValue::Number(number)) => Ok(Some(Literal::Primitive(
PrimitiveLiteral::Float(OrderedFloat(number.as_f64().ok_or(Error::new(
crate::ErrorKind::DataInvalid,
"Failed to convert json number to float",
))? as f32)),
))),
(PrimitiveType::Double, JsonValue::Number(number)) => Ok(Some(Literal::Primitive(
PrimitiveLiteral::Double(OrderedFloat(number.as_f64().ok_or(Error::new(
crate::ErrorKind::DataInvalid,
"Failed to convert json number to double",
))?)),
))),
(PrimitiveType::Date, JsonValue::String(s)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::Date(
date::date_to_days(&NaiveDate::parse_from_str(&s, "%Y-%m-%d")?),
))))
}
(PrimitiveType::Time, JsonValue::String(s)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::Time(
time::time_to_microseconds(&NaiveTime::parse_from_str(&s, "%H:%M:%S%.f")?),
))))
}
(PrimitiveType::Timestamp, JsonValue::String(s)) => Ok(Some(Literal::Primitive(
PrimitiveLiteral::Timestamp(timestamp::datetime_to_microseconds(
&NaiveDateTime::parse_from_str(&s, "%Y-%m-%dT%H:%M:%S%.f")?,
)),
))),
(PrimitiveType::Timestamptz, JsonValue::String(s)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::TimestampTZ(
timestamptz::datetimetz_to_microseconds(&Utc.from_utc_datetime(
&NaiveDateTime::parse_from_str(&s, "%Y-%m-%dT%H:%M:%S%.f+00:00")?,
)),
))))
}
(PrimitiveType::String, JsonValue::String(s)) => {
Ok(Some(Literal::Primitive(PrimitiveLiteral::String(s))))
}
(PrimitiveType::Uuid, JsonValue::String(s)) => Ok(Some(Literal::Primitive(
PrimitiveLiteral::UUID(Uuid::parse_str(&s)?),
))),
(PrimitiveType::Fixed(_), JsonValue::String(_)) => todo!(),
(PrimitiveType::Binary, JsonValue::String(_)) => todo!(),
(
PrimitiveType::Decimal {
precision: _,
scale: _,
},
JsonValue::String(_),
) => todo!(),
(_, JsonValue::Null) => Ok(None),
(i, j) => Err(Error::new(
crate::ErrorKind::DataInvalid,
format!(
"The json value {} doesn't fit to the iceberg type {}.",
j, i
),
)),
},
Type::Struct(schema) => {
if let JsonValue::Object(mut object) = value {
Ok(Some(Literal::Struct(Struct::from_iter(
schema.fields().iter().map(|field| {
(
field.id,
object.remove(&field.id.to_string()).and_then(|value| {
Literal::try_from_json(value, &field.field_type)
.and_then(|value| {
value.ok_or(Error::new(
ErrorKind::DataInvalid,
"Key of map cannot be null",
))
})
.ok()
}),
field.name.clone(),
)
}),
))))
} else {
Err(Error::new(
crate::ErrorKind::DataInvalid,
"The json value for a struct type must be an object.",
))
}
}
Type::List(list) => {
if let JsonValue::Array(array) = value {
Ok(Some(Literal::List(
array
.into_iter()
.map(|value| {
Literal::try_from_json(value, &list.element_field.field_type)
})
.collect::<Result<Vec<_>>>()?,
)))
} else {
Err(Error::new(
crate::ErrorKind::DataInvalid,
"The json value for a list type must be an array.",
))
}
}
Type::Map(map) => {
if let JsonValue::Object(mut object) = value {
if let (Some(JsonValue::Array(keys)), Some(JsonValue::Array(values))) =
(object.remove("keys"), object.remove("values"))
{
Ok(Some(Literal::Map(BTreeMap::from_iter(
keys.into_iter()
.zip(values.into_iter())
.map(|(key, value)| {
Ok((
Literal::try_from_json(key, &map.key_field.field_type)
.and_then(|value| {
value.ok_or(Error::new(
ErrorKind::DataInvalid,
"Key of map cannot be null",
))
})?,
Literal::try_from_json(value, &map.value_field.field_type)?,
))
})
.collect::<Result<Vec<_>>>()?,
))))
} else {
Err(Error::new(
crate::ErrorKind::DataInvalid,
"The json value for a list type must be an array.",
))
}
} else {
Err(Error::new(
crate::ErrorKind::DataInvalid,
"The json value for a list type must be an array.",
))
}
}
}
}
/// Get datatype of value
pub fn datatype(&self) -> Type {
match self {
Literal::Primitive(prim) => match prim {
PrimitiveLiteral::Boolean(_) => Type::Primitive(PrimitiveType::Boolean),
PrimitiveLiteral::Int(_) => Type::Primitive(PrimitiveType::Int),
PrimitiveLiteral::Long(_) => Type::Primitive(PrimitiveType::Long),
PrimitiveLiteral::Float(_) => Type::Primitive(PrimitiveType::Float),
PrimitiveLiteral::Double(_) => Type::Primitive(PrimitiveType::Double),
PrimitiveLiteral::Date(_) => Type::Primitive(PrimitiveType::Date),
PrimitiveLiteral::Time(_) => Type::Primitive(PrimitiveType::Time),
PrimitiveLiteral::Timestamp(_) => Type::Primitive(PrimitiveType::Timestamp),
PrimitiveLiteral::TimestampTZ(_) => Type::Primitive(PrimitiveType::Timestamptz),
PrimitiveLiteral::Fixed(vec) => {
Type::Primitive(PrimitiveType::Fixed(vec.len() as u64))
}
PrimitiveLiteral::Binary(_) => Type::Primitive(PrimitiveType::Binary),
PrimitiveLiteral::String(_) => Type::Primitive(PrimitiveType::String),
PrimitiveLiteral::UUID(_) => Type::Primitive(PrimitiveType::Uuid),
PrimitiveLiteral::Decimal(_) => Type::Primitive(PrimitiveType::Decimal {
precision: MAX_DECIMAL_PRECISION,
scale: 0,
}),
},
_ => unimplemented!(),
}
}
/// Convert Value to the any type
pub fn into_any(self) -> Box<dyn Any> {
match self {
Literal::Primitive(prim) => match prim {
PrimitiveLiteral::Boolean(any) => Box::new(any),
PrimitiveLiteral::Int(any) => Box::new(any),
PrimitiveLiteral::Long(any) => Box::new(any),
PrimitiveLiteral::Float(any) => Box::new(any),
PrimitiveLiteral::Double(any) => Box::new(any),
PrimitiveLiteral::Date(any) => Box::new(any),
PrimitiveLiteral::Time(any) => Box::new(any),
PrimitiveLiteral::Timestamp(any) => Box::new(any),
PrimitiveLiteral::TimestampTZ(any) => Box::new(any),
PrimitiveLiteral::Fixed(any) => Box::new(any),
PrimitiveLiteral::Binary(any) => Box::new(any),
PrimitiveLiteral::String(any) => Box::new(any),
PrimitiveLiteral::UUID(any) => Box::new(any),
PrimitiveLiteral::Decimal(any) => Box::new(any),
},
_ => unimplemented!(),
}
}
}
mod date {
use chrono::{NaiveDate, NaiveDateTime};
pub(crate) fn date_to_days(date: &NaiveDate) -> i32 {
date.signed_duration_since(
// This is always the same and shouldn't fail
NaiveDate::from_ymd_opt(1970, 1, 1).unwrap(),
)
.num_days() as i32
}
pub(crate) fn days_to_date(days: i32) -> NaiveDate {
// This shouldn't fail until the year 262000
NaiveDateTime::from_timestamp_opt(days as i64 * 86_400, 0)
.unwrap()
.date()
}
}
mod time {
use chrono::NaiveTime;
pub(crate) fn time_to_microseconds(time: &NaiveTime) -> i64 {
time.signed_duration_since(
// This is always the same and shouldn't fail
NaiveTime::from_num_seconds_from_midnight_opt(0, 0).unwrap(),
)
.num_microseconds()
.unwrap()
}
pub(crate) fn microseconds_to_time(micros: i64) -> NaiveTime {
let (secs, rem) = (micros / 1_000_000, micros % 1_000_000);
NaiveTime::from_num_seconds_from_midnight_opt(secs as u32, rem as u32 * 1_000).unwrap()
}
}
mod timestamp {
use chrono::NaiveDateTime;