This repository has been archived by the owner on Jan 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
api.rs
1422 lines (1226 loc) · 45.5 KB
/
api.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.
//! Contains Row enum that is used to represent record in Rust.
use std::fmt;
use basic::{LogicalType, Type as PhysicalType};
use chrono::{Local, TimeZone};
use data_type::{ByteArray, Decimal, Int96};
use errors::{ParquetError, Result};
use num_bigint::{BigInt, Sign};
use schema::types::ColumnDescPtr;
/// Macro as a shortcut to generate 'not yet implemented' panic error.
macro_rules! nyi {
($column_descr:ident, $value:ident) => {{
unimplemented!(
"Conversion for physical type {}, logical type {}, value {:?}",
$column_descr.physical_type(),
$column_descr.logical_type(),
$value
);
}};
}
/// `Row` represents a nested Parquet record.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
fields: Vec<(String, Field)>,
}
impl Row {
/// Get the number of fields in this row.
pub fn len(&self) -> usize { self.fields.len() }
}
/// Trait for type-safe convenient access to fields within a Row.
pub trait RowAccessor {
fn get_bool(&self, i: usize) -> Result<bool>;
fn get_byte(&self, i: usize) -> Result<i8>;
fn get_short(&self, i: usize) -> Result<i16>;
fn get_int(&self, i: usize) -> Result<i32>;
fn get_long(&self, i: usize) -> Result<i64>;
fn get_ubyte(&self, i: usize) -> Result<u8>;
fn get_ushort(&self, i: usize) -> Result<u16>;
fn get_uint(&self, i: usize) -> Result<u32>;
fn get_ulong(&self, i: usize) -> Result<u64>;
fn get_float(&self, i: usize) -> Result<f32>;
fn get_double(&self, i: usize) -> Result<f64>;
fn get_timestamp(&self, i: usize) -> Result<u64>;
fn get_decimal(&self, i: usize) -> Result<&Decimal>;
fn get_string(&self, i: usize) -> Result<&String>;
fn get_bytes(&self, i: usize) -> Result<&ByteArray>;
fn get_group(&self, i: usize) -> Result<&Row>;
fn get_list(&self, i: usize) -> Result<&List>;
fn get_map(&self, i: usize) -> Result<&Map>;
}
/// Macro to generate type-safe get_xxx methods for primitive types,
/// e.g. `get_bool`, `get_short`.
macro_rules! row_primitive_accessor {
($METHOD:ident, $VARIANT:ident, $TY:ty) => {
fn $METHOD(&self, i: usize) -> Result<$TY> {
match self.fields[i].1 {
Field::$VARIANT(v) => Ok(v),
_ => Err(general_err!("Cannot access {} as {}",
self.fields[i].1.get_type_name(), stringify!($VARIANT)))
}
}
}
}
/// Macro to generate type-safe get_xxx methods for reference types,
/// e.g. `get_list`, `get_map`.
macro_rules! row_complex_accessor {
($METHOD:ident, $VARIANT:ident, $TY:ty) => {
fn $METHOD(&self, i: usize) -> Result<&$TY> {
match self.fields[i].1 {
Field::$VARIANT(ref v) => Ok(v),
_ => Err(general_err!("Cannot access {} as {}",
self.fields[i].1.get_type_name(), stringify!($VARIANT)))
}
}
}
}
impl RowAccessor for Row {
row_primitive_accessor!(get_bool, Bool, bool);
row_primitive_accessor!(get_byte, Byte, i8);
row_primitive_accessor!(get_short, Short, i16);
row_primitive_accessor!(get_int, Int, i32);
row_primitive_accessor!(get_long, Long, i64);
row_primitive_accessor!(get_ubyte, UByte, u8);
row_primitive_accessor!(get_ushort, UShort, u16);
row_primitive_accessor!(get_uint, UInt, u32);
row_primitive_accessor!(get_ulong, ULong, u64);
row_primitive_accessor!(get_float, Float, f32);
row_primitive_accessor!(get_double, Double, f64);
row_primitive_accessor!(get_timestamp, Timestamp, u64);
row_complex_accessor!(get_decimal, Decimal, Decimal);
row_complex_accessor!(get_string, Str, String);
row_complex_accessor!(get_bytes, Bytes, ByteArray);
row_complex_accessor!(get_group, Group, Row);
row_complex_accessor!(get_list, ListInternal, List);
row_complex_accessor!(get_map, MapInternal, Map);
}
/// Constructs a `Row` from the list of `fields` and returns it.
#[inline]
pub fn make_row(fields: Vec<(String, Field)>) -> Row { Row { fields } }
impl fmt::Display for Row {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{")?;
for (i, &(ref key, ref value)) in self.fields.iter().enumerate() {
key.fmt(f)?;
write!(f, ": ")?;
value.fmt(f)?;
if i < self.fields.len() - 1 {
write!(f, ", ")?;
}
}
write!(f, "}}")
}
}
/// `List` represents a list which contains an array of elements.
#[derive(Clone, Debug, PartialEq)]
pub struct List {
elements: Vec<Field>,
}
impl List {
/// Get the number of fields in this row
pub fn len(&self) -> usize { self.elements.len() }
}
/// Constructs a `List` from the list of `fields` and returns it.
#[inline]
pub fn make_list(elements: Vec<Field>) -> List { List { elements } }
/// Trait for type-safe access of an index for a `List`.
/// Note that the get_XXX methods do not do bound checking.
pub trait ListAccessor {
fn get_bool(&self, i: usize) -> Result<bool>;
fn get_byte(&self, i: usize) -> Result<i8>;
fn get_short(&self, i: usize) -> Result<i16>;
fn get_int(&self, i: usize) -> Result<i32>;
fn get_long(&self, i: usize) -> Result<i64>;
fn get_ubyte(&self, i: usize) -> Result<u8>;
fn get_ushort(&self, i: usize) -> Result<u16>;
fn get_uint(&self, i: usize) -> Result<u32>;
fn get_ulong(&self, i: usize) -> Result<u64>;
fn get_float(&self, i: usize) -> Result<f32>;
fn get_double(&self, i: usize) -> Result<f64>;
fn get_timestamp(&self, i: usize) -> Result<u64>;
fn get_decimal(&self, i: usize) -> Result<&Decimal>;
fn get_string(&self, i: usize) -> Result<&String>;
fn get_bytes(&self, i: usize) -> Result<&ByteArray>;
fn get_group(&self, i: usize) -> Result<&Row>;
fn get_list(&self, i: usize) -> Result<&List>;
fn get_map(&self, i: usize) -> Result<&Map>;
}
/// Macro to generate type-safe get_xxx methods for primitive types,
/// e.g. get_bool, get_short
macro_rules! list_primitive_accessor {
($METHOD:ident, $VARIANT:ident, $TY:ty) => {
fn $METHOD(&self, i: usize) -> Result<$TY> {
match self.elements[i] {
Field::$VARIANT(v) => Ok(v),
_ => Err(general_err!(
"Cannot access {} as {}",
self.elements[i].get_type_name(), stringify!($VARIANT))
)
}
}
}
}
/// Macro to generate type-safe get_xxx methods for reference types
/// e.g. get_list, get_map
macro_rules! list_complex_accessor {
($METHOD:ident, $VARIANT:ident, $TY:ty) => {
fn $METHOD(&self, i: usize) -> Result<&$TY> {
match self.elements[i] {
Field::$VARIANT(ref v) => Ok(v),
_ => Err(general_err!(
"Cannot access {} as {}",
self.elements[i].get_type_name(), stringify!($VARIANT))
)
}
}
}
}
impl ListAccessor for List {
list_primitive_accessor!(get_bool, Bool, bool);
list_primitive_accessor!(get_byte, Byte, i8);
list_primitive_accessor!(get_short, Short, i16);
list_primitive_accessor!(get_int, Int, i32);
list_primitive_accessor!(get_long, Long, i64);
list_primitive_accessor!(get_ubyte, UByte, u8);
list_primitive_accessor!(get_ushort, UShort, u16);
list_primitive_accessor!(get_uint, UInt, u32);
list_primitive_accessor!(get_ulong, ULong, u64);
list_primitive_accessor!(get_float, Float, f32);
list_primitive_accessor!(get_double, Double, f64);
list_primitive_accessor!(get_timestamp, Timestamp, u64);
list_complex_accessor!(get_decimal, Decimal, Decimal);
list_complex_accessor!(get_string, Str, String);
list_complex_accessor!(get_bytes, Bytes, ByteArray);
list_complex_accessor!(get_group, Group, Row);
list_complex_accessor!(get_list, ListInternal, List);
list_complex_accessor!(get_map, MapInternal, Map);
}
/// `Map` represents a map which contains an list of key->value pairs.
#[derive(Clone, Debug, PartialEq)]
pub struct Map {
entries: Vec<(Field, Field)>,
}
impl Map {
/// Get the number of fields in this row
pub fn len(&self) -> usize { self.entries.len() }
}
/// Constructs a `Map` from the list of `entries` and returns it.
#[inline]
pub fn make_map(entries: Vec<(Field, Field)>) -> Map { Map { entries } }
/// Trait for type-safe access of an index for a `Map`
pub trait MapAccessor {
fn get_keys<'a>(&'a self) -> Box<ListAccessor + 'a>;
fn get_values<'a>(&'a self) -> Box<ListAccessor + 'a>;
}
struct MapList<'a> {
elements: Vec<&'a Field>,
}
/// Macro to generate type-safe get_xxx methods for primitive types,
/// e.g. get_bool, get_short
macro_rules! map_list_primitive_accessor {
($METHOD:ident, $VARIANT:ident, $TY:ty) => {
fn $METHOD(&self, i: usize) -> Result<$TY> {
match self.elements[i] {
Field::$VARIANT(v) => Ok(*v),
_ => Err(general_err!(
"Cannot access {} as {}",
self.elements[i].get_type_name(), stringify!($VARIANT))
)
}
}
}
}
impl<'a> ListAccessor for MapList<'a> {
map_list_primitive_accessor!(get_bool, Bool, bool);
map_list_primitive_accessor!(get_byte, Byte, i8);
map_list_primitive_accessor!(get_short, Short, i16);
map_list_primitive_accessor!(get_int, Int, i32);
map_list_primitive_accessor!(get_long, Long, i64);
map_list_primitive_accessor!(get_ubyte, UByte, u8);
map_list_primitive_accessor!(get_ushort, UShort, u16);
map_list_primitive_accessor!(get_uint, UInt, u32);
map_list_primitive_accessor!(get_ulong, ULong, u64);
map_list_primitive_accessor!(get_float, Float, f32);
map_list_primitive_accessor!(get_double, Double, f64);
map_list_primitive_accessor!(get_timestamp, Timestamp, u64);
list_complex_accessor!(get_decimal, Decimal, Decimal);
list_complex_accessor!(get_string, Str, String);
list_complex_accessor!(get_bytes, Bytes, ByteArray);
list_complex_accessor!(get_group, Group, Row);
list_complex_accessor!(get_list, ListInternal, List);
list_complex_accessor!(get_map, MapInternal, Map);
}
impl MapAccessor for Map {
fn get_keys<'a>(&'a self) -> Box<ListAccessor + 'a> {
let map_list = MapList {
elements: self.entries.iter().map(|v| &v.0).collect(),
};
Box::new(map_list)
}
fn get_values<'a>(&'a self) -> Box<ListAccessor + 'a> {
let map_list = MapList {
elements: self.entries.iter().map(|v| &v.1).collect(),
};
Box::new(map_list)
}
}
/// API to represent a single field in a `Row`.
#[derive(Clone, Debug, PartialEq)]
pub enum Field {
// Primitive types
/// Null value.
Null,
/// Boolean value (`true`, `false`).
Bool(bool),
/// Signed integer INT_8.
Byte(i8),
/// Signed integer INT_16.
Short(i16),
/// Signed integer INT_32.
Int(i32),
/// Signed integer INT_64.
Long(i64),
// Unsigned integer UINT_8.
UByte(u8),
// Unsigned integer UINT_16.
UShort(u16),
// Unsigned integer UINT_32.
UInt(u32),
// Unsigned integer UINT_64.
ULong(u64),
/// IEEE 32-bit floating point value.
Float(f32),
/// IEEE 64-bit floating point value.
Double(f64),
/// Decimal value.
Decimal(Decimal),
/// UTF-8 encoded character string.
Str(String),
/// General binary value.
Bytes(ByteArray),
/// Date without a time of day, stores the number of days from the
/// Unix epoch, 1 January 1970.
Date(u32),
/// Milliseconds from the Unix epoch, 1 January 1970.
Timestamp(u64),
// ----------------------------------------------------------------------
// Complex types
/// Struct, child elements are tuples of field-value pairs.
Group(Row),
/// List of elements.
ListInternal(List),
/// List of key-value pairs.
MapInternal(Map),
}
impl Field {
/// Get the type name.
fn get_type_name(&self) -> &'static str {
match *self {
Field::Null => "Null",
Field::Bool(_) => "Bool",
Field::Byte(_) => "Byte",
Field::Short(_) => "Short",
Field::Int(_) => "Int",
Field::Long(_) => "Long",
Field::UByte(_) => "UByte",
Field::UShort(_) => "UShort",
Field::UInt(_) => "UInt",
Field::ULong(_) => "ULong",
Field::Float(_) => "Float",
Field::Double(_) => "Double",
Field::Decimal(_) => "Decimal",
Field::Date(_) => "Date",
Field::Str(_) => "Str",
Field::Bytes(_) => "Bytes",
Field::Timestamp(_) => "Timestamp",
Field::Group(_) => "Group",
Field::ListInternal(_) => "ListInternal",
Field::MapInternal(_) => "MapInternal",
}
}
/// Determines if this Row represents a primitive value.
pub fn is_primitive(&self) -> bool {
match *self {
Field::Group(_) => false,
Field::ListInternal(_) => false,
Field::MapInternal(_) => false,
_ => true,
}
}
/// Converts Parquet BOOLEAN type with logical type into `bool` value.
#[inline]
pub fn convert_bool(_descr: &ColumnDescPtr, value: bool) -> Self { Field::Bool(value) }
/// Converts Parquet INT32 type with logical type into `i32` value.
#[inline]
pub fn convert_int32(descr: &ColumnDescPtr, value: i32) -> Self {
match descr.logical_type() {
LogicalType::INT_8 => Field::Byte(value as i8),
LogicalType::INT_16 => Field::Short(value as i16),
LogicalType::INT_32 | LogicalType::NONE => Field::Int(value),
LogicalType::UINT_8 => Field::UByte(value as u8),
LogicalType::UINT_16 => Field::UShort(value as u16),
LogicalType::UINT_32 => Field::UInt(value as u32),
LogicalType::DATE => Field::Date(value as u32),
LogicalType::DECIMAL => Field::Decimal(Decimal::from_i32(
value,
descr.type_precision(),
descr.type_scale(),
)),
_ => nyi!(descr, value),
}
}
/// Converts Parquet INT64 type with logical type into `i64` value.
#[inline]
pub fn convert_int64(descr: &ColumnDescPtr, value: i64) -> Self {
match descr.logical_type() {
LogicalType::INT_64 | LogicalType::NONE => Field::Long(value),
LogicalType::UINT_64 => Field::ULong(value as u64),
LogicalType::TIMESTAMP_MILLIS => Field::Timestamp(value as u64),
LogicalType::DECIMAL => Field::Decimal(Decimal::from_i64(
value,
descr.type_precision(),
descr.type_scale(),
)),
_ => nyi!(descr, value),
}
}
/// Converts Parquet INT96 (nanosecond timestamps) type and logical type into
/// `Timestamp` value.
#[inline]
pub fn convert_int96(_descr: &ColumnDescPtr, value: Int96) -> Self {
const JULIAN_DAY_OF_EPOCH: i64 = 2_440_588;
const SECONDS_PER_DAY: i64 = 86_400;
const MILLIS_PER_SECOND: i64 = 1_000;
let day = value.data()[2] as i64;
let nanoseconds = ((value.data()[1] as i64) << 32) + value.data()[0] as i64;
let seconds = (day - JULIAN_DAY_OF_EPOCH) * SECONDS_PER_DAY;
let millis = seconds * MILLIS_PER_SECOND + nanoseconds / 1_000_000;
// TODO: Add support for negative milliseconds.
// Chrono library does not handle negative timestamps, but we could probably write
// something similar to java.util.Date and java.util.Calendar.
if millis < 0 {
panic!(
"Expected non-negative milliseconds when converting Int96, found {}",
millis
);
}
Field::Timestamp(millis as u64)
}
/// Converts Parquet FLOAT type with logical type into `f32` value.
#[inline]
pub fn convert_float(_descr: &ColumnDescPtr, value: f32) -> Self { Field::Float(value) }
/// Converts Parquet DOUBLE type with logical type into `f64` value.
#[inline]
pub fn convert_double(_descr: &ColumnDescPtr, value: f64) -> Self {
Field::Double(value)
}
/// Converts Parquet BYTE_ARRAY type with logical type into either UTF8 string or
/// array of bytes.
#[inline]
pub fn convert_byte_array(descr: &ColumnDescPtr, value: ByteArray) -> Self {
match descr.physical_type() {
PhysicalType::BYTE_ARRAY => match descr.logical_type() {
LogicalType::UTF8 | LogicalType::ENUM | LogicalType::JSON => {
let value = unsafe { String::from_utf8_unchecked(value.data().to_vec()) };
Field::Str(value)
},
LogicalType::BSON | LogicalType::NONE => Field::Bytes(value),
LogicalType::DECIMAL => Field::Decimal(Decimal::from_bytes(
value,
descr.type_precision(),
descr.type_scale(),
)),
_ => nyi!(descr, value),
},
PhysicalType::FIXED_LEN_BYTE_ARRAY => match descr.logical_type() {
LogicalType::DECIMAL => Field::Decimal(Decimal::from_bytes(
value,
descr.type_precision(),
descr.type_scale(),
)),
LogicalType::NONE => Field::Bytes(value),
_ => nyi!(descr, value),
},
_ => nyi!(descr, value),
}
}
}
impl fmt::Display for Field {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Field::Null => write!(f, "null"),
Field::Bool(value) => write!(f, "{}", value),
Field::Byte(value) => write!(f, "{}", value),
Field::Short(value) => write!(f, "{}", value),
Field::Int(value) => write!(f, "{}", value),
Field::Long(value) => write!(f, "{}", value),
Field::UByte(value) => write!(f, "{}", value),
Field::UShort(value) => write!(f, "{}", value),
Field::UInt(value) => write!(f, "{}", value),
Field::ULong(value) => write!(f, "{}", value),
Field::Float(value) => {
if value > 1e19 || value < 1e-15 {
write!(f, "{:E}", value)
} else {
write!(f, "{:?}", value)
}
},
Field::Double(value) => {
if value > 1e19 || value < 1e-15 {
write!(f, "{:E}", value)
} else {
write!(f, "{:?}", value)
}
},
Field::Decimal(ref value) => write!(f, "{}", convert_decimal_to_string(value)),
Field::Str(ref value) => write!(f, "\"{}\"", value),
Field::Bytes(ref value) => write!(f, "{:?}", value.data()),
Field::Date(value) => write!(f, "{}", convert_date_to_string(value)),
Field::Timestamp(value) => write!(f, "{}", convert_timestamp_to_string(value)),
Field::Group(ref fields) => write!(f, "{}", fields),
Field::ListInternal(ref list) => {
let elems = &list.elements;
write!(f, "[")?;
for (i, field) in elems.iter().enumerate() {
field.fmt(f)?;
if i < elems.len() - 1 {
write!(f, ", ")?;
}
}
write!(f, "]")
},
Field::MapInternal(ref map) => {
let entries = &map.entries;
write!(f, "{{")?;
for (i, &(ref key, ref value)) in entries.iter().enumerate() {
key.fmt(f)?;
write!(f, " -> ")?;
value.fmt(f)?;
if i < entries.len() - 1 {
write!(f, ", ")?;
}
}
write!(f, "}}")
},
}
}
}
/// Helper method to convert Parquet date into a string.
/// Input `value` is a number of days since the epoch in UTC.
/// Date is displayed in local timezone.
#[inline]
fn convert_date_to_string(value: u32) -> String {
static NUM_SECONDS_IN_DAY: i64 = 60 * 60 * 24;
let dt = Local.timestamp(value as i64 * NUM_SECONDS_IN_DAY, 0).date();
format!("{}", dt.format("%Y-%m-%d %:z"))
}
/// Helper method to convert Parquet timestamp into a string.
/// Input `value` is a number of milliseconds since the epoch in UTC.
/// Datetime is displayed in local timezone.
#[inline]
fn convert_timestamp_to_string(value: u64) -> String {
let dt = Local.timestamp((value / 1000) as i64, 0);
format!("{}", dt.format("%Y-%m-%d %H:%M:%S %:z"))
}
/// Helper method to convert Parquet decimal into a string.
/// We assert that `scale >= 0` and `precision > scale`, but this will be enforced
/// when constructing Parquet schema.
#[inline]
fn convert_decimal_to_string(decimal: &Decimal) -> String {
assert!(decimal.scale() >= 0 && decimal.precision() > decimal.scale());
// Specify as signed bytes to resolve sign as part of conversion.
let num = BigInt::from_signed_bytes_be(decimal.data());
// Offset of the first digit in a string.
let negative = if num.sign() == Sign::Minus { 1 } else { 0 };
let mut num_str = num.to_string();
let mut point = num_str.len() as i32 - decimal.scale() - negative;
// Convert to string form without scientific notation.
if point <= 0 {
// Zeros need to be prepended to the unscaled value.
while point < 0 {
num_str.insert(negative as usize, '0');
point += 1;
}
num_str.insert_str(negative as usize, "0.");
} else {
// No zeroes need to be prepended to the unscaled value, simply insert decimal point.
num_str.insert((point + negative) as usize, '.');
}
num_str
}
#[cfg(test)]
mod tests {
use std::rc::Rc;
use super::*;
use chrono;
use schema::types::{ColumnDescriptor, ColumnPath, PrimitiveTypeBuilder};
/// Creates test column descriptor based on provided type parameters.
macro_rules! make_column_descr {
($physical_type:expr, $logical_type:expr) => {{
let tpe = PrimitiveTypeBuilder::new("col", $physical_type)
.with_logical_type($logical_type)
.build()
.unwrap();
Rc::new(ColumnDescriptor::new(
Rc::new(tpe),
None,
0,
0,
ColumnPath::from("col"),
))
}};
($physical_type:expr, $logical_type:expr, $len:expr, $prec:expr, $scale:expr) => {{
let tpe = PrimitiveTypeBuilder::new("col", $physical_type)
.with_logical_type($logical_type)
.with_length($len)
.with_precision($prec)
.with_scale($scale)
.build()
.unwrap();
Rc::new(ColumnDescriptor::new(
Rc::new(tpe),
None,
0,
0,
ColumnPath::from("col"),
))
}};
}
#[test]
fn test_row_convert_bool() {
// BOOLEAN value does not depend on logical type
let descr = make_column_descr![PhysicalType::BOOLEAN, LogicalType::NONE];
let row = Field::convert_bool(&descr, true);
assert_eq!(row, Field::Bool(true));
let row = Field::convert_bool(&descr, false);
assert_eq!(row, Field::Bool(false));
}
#[test]
fn test_row_convert_int32() {
let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_8];
let row = Field::convert_int32(&descr, 111);
assert_eq!(row, Field::Byte(111));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_16];
let row = Field::convert_int32(&descr, 222);
assert_eq!(row, Field::Short(222));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::INT_32];
let row = Field::convert_int32(&descr, 333);
assert_eq!(row, Field::Int(333));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_8];
let row = Field::convert_int32(&descr, -1);
assert_eq!(row, Field::UByte(255));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_16];
let row = Field::convert_int32(&descr, 256);
assert_eq!(row, Field::UShort(256));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::UINT_32];
let row = Field::convert_int32(&descr, 1234);
assert_eq!(row, Field::UInt(1234));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::NONE];
let row = Field::convert_int32(&descr, 444);
assert_eq!(row, Field::Int(444));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::DATE];
let row = Field::convert_int32(&descr, 14611);
assert_eq!(row, Field::Date(14611));
let descr = make_column_descr![PhysicalType::INT32, LogicalType::DECIMAL, 0, 8, 2];
let row = Field::convert_int32(&descr, 444);
assert_eq!(row, Field::Decimal(Decimal::from_i32(444, 8, 2)));
}
#[test]
fn test_row_convert_int64() {
let descr = make_column_descr![PhysicalType::INT64, LogicalType::INT_64];
let row = Field::convert_int64(&descr, 1111);
assert_eq!(row, Field::Long(1111));
let descr = make_column_descr![PhysicalType::INT64, LogicalType::UINT_64];
let row = Field::convert_int64(&descr, 78239823);
assert_eq!(row, Field::ULong(78239823));
let descr = make_column_descr![PhysicalType::INT64, LogicalType::TIMESTAMP_MILLIS];
let row = Field::convert_int64(&descr, 1541186529153);
assert_eq!(row, Field::Timestamp(1541186529153));
let descr = make_column_descr![PhysicalType::INT64, LogicalType::NONE];
let row = Field::convert_int64(&descr, 2222);
assert_eq!(row, Field::Long(2222));
let descr = make_column_descr![PhysicalType::INT64, LogicalType::DECIMAL, 0, 8, 2];
let row = Field::convert_int64(&descr, 3333);
assert_eq!(row, Field::Decimal(Decimal::from_i64(3333, 8, 2)));
}
#[test]
fn test_row_convert_int96() {
// INT96 value does not depend on logical type
let descr = make_column_descr![PhysicalType::INT96, LogicalType::NONE];
let value = Int96::from(vec![0, 0, 2454923]);
let row = Field::convert_int96(&descr, value);
assert_eq!(row, Field::Timestamp(1238544000000));
let value = Int96::from(vec![4165425152, 13, 2454923]);
let row = Field::convert_int96(&descr, value);
assert_eq!(row, Field::Timestamp(1238544060000));
}
#[test]
#[should_panic(expected = "Expected non-negative milliseconds when converting Int96")]
fn test_row_convert_int96_invalid() {
// INT96 value does not depend on logical type
let descr = make_column_descr![PhysicalType::INT96, LogicalType::NONE];
let value = Int96::from(vec![0, 0, 0]);
Field::convert_int96(&descr, value);
}
#[test]
fn test_row_convert_float() {
// FLOAT value does not depend on logical type
let descr = make_column_descr![PhysicalType::FLOAT, LogicalType::NONE];
let row = Field::convert_float(&descr, 2.31);
assert_eq!(row, Field::Float(2.31));
}
#[test]
fn test_row_convert_double() {
// DOUBLE value does not depend on logical type
let descr = make_column_descr![PhysicalType::DOUBLE, LogicalType::NONE];
let row = Field::convert_double(&descr, 1.56);
assert_eq!(row, Field::Double(1.56));
}
#[test]
fn test_row_convert_byte_array() {
// UTF8
let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::UTF8];
let value = ByteArray::from(vec![b'A', b'B', b'C', b'D']);
let row = Field::convert_byte_array(&descr, value);
assert_eq!(row, Field::Str("ABCD".to_string()));
// ENUM
let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::ENUM];
let value = ByteArray::from(vec![b'1', b'2', b'3']);
let row = Field::convert_byte_array(&descr, value);
assert_eq!(row, Field::Str("123".to_string()));
// JSON
let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::JSON];
let value = ByteArray::from(vec![b'{', b'"', b'a', b'"', b':', b'1', b'}']);
let row = Field::convert_byte_array(&descr, value);
assert_eq!(row, Field::Str("{\"a\":1}".to_string()));
// NONE
let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::NONE];
let value = ByteArray::from(vec![1, 2, 3, 4, 5]);
let row = Field::convert_byte_array(&descr, value.clone());
assert_eq!(row, Field::Bytes(value));
// BSON
let descr = make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::BSON];
let value = ByteArray::from(vec![1, 2, 3, 4, 5]);
let row = Field::convert_byte_array(&descr, value.clone());
assert_eq!(row, Field::Bytes(value));
// DECIMAL
let descr =
make_column_descr![PhysicalType::BYTE_ARRAY, LogicalType::DECIMAL, 0, 8, 2];
let value = ByteArray::from(vec![207, 200]);
let row = Field::convert_byte_array(&descr, value.clone());
assert_eq!(row, Field::Decimal(Decimal::from_bytes(value, 8, 2)));
// DECIMAL (FIXED_LEN_BYTE_ARRAY)
let descr = make_column_descr![
PhysicalType::FIXED_LEN_BYTE_ARRAY,
LogicalType::DECIMAL,
8,
17,
5
];
let value = ByteArray::from(vec![0, 0, 0, 0, 0, 4, 147, 224]);
let row = Field::convert_byte_array(&descr, value.clone());
assert_eq!(row, Field::Decimal(Decimal::from_bytes(value, 17, 5)));
// NONE (FIXED_LEN_BYTE_ARRAY)
let descr = make_column_descr![
PhysicalType::FIXED_LEN_BYTE_ARRAY,
LogicalType::NONE,
6,
0,
0
];
let value = ByteArray::from(vec![1, 2, 3, 4, 5, 6]);
let row = Field::convert_byte_array(&descr, value.clone());
assert_eq!(row, Field::Bytes(value));
}
#[test]
fn test_convert_date_to_string() {
fn check_date_conversion(y: u32, m: u32, d: u32) {
let datetime = chrono::NaiveDate::from_ymd(y as i32, m, d).and_hms(0, 0, 0);
let dt = Local.from_utc_datetime(&datetime);
let res = convert_date_to_string((dt.timestamp() / 60 / 60 / 24) as u32);
let exp = format!("{}", dt.format("%Y-%m-%d %:z"));
assert_eq!(res, exp);
}
check_date_conversion(2010, 01, 02);
check_date_conversion(2014, 05, 01);
check_date_conversion(2016, 02, 29);
check_date_conversion(2017, 09, 12);
check_date_conversion(2018, 03, 31);
}
#[test]
fn test_convert_timestamp_to_string() {
fn check_datetime_conversion(y: u32, m: u32, d: u32, h: u32, mi: u32, s: u32) {
let datetime = chrono::NaiveDate::from_ymd(y as i32, m, d).and_hms(h, mi, s);
let dt = Local.from_utc_datetime(&datetime);
let res = convert_timestamp_to_string(dt.timestamp_millis() as u64);
let exp = format!("{}", dt.format("%Y-%m-%d %H:%M:%S %:z"));
assert_eq!(res, exp);
}
check_datetime_conversion(2010, 01, 02, 13, 12, 54);
check_datetime_conversion(2011, 01, 03, 08, 23, 01);
check_datetime_conversion(2012, 04, 05, 11, 06, 32);
check_datetime_conversion(2013, 05, 12, 16, 38, 00);
check_datetime_conversion(2014, 11, 28, 21, 15, 12);
}
#[test]
fn test_convert_float_to_string() {
assert_eq!(format!("{}", Field::Float(1.0)), "1.0");
assert_eq!(format!("{}", Field::Float(9.63)), "9.63");
assert_eq!(format!("{}", Field::Float(1e-15)), "0.000000000000001");
assert_eq!(format!("{}", Field::Float(1e-16)), "1E-16");
assert_eq!(format!("{}", Field::Float(1e19)), "10000000000000000000.0");
assert_eq!(format!("{}", Field::Float(1e20)), "1E20");
assert_eq!(format!("{}", Field::Float(1.7976931E30)), "1.7976931E30");
assert_eq!(format!("{}", Field::Float(-1.7976931E30)), "-1.7976931E30");
}
#[test]
fn test_convert_double_to_string() {
assert_eq!(format!("{}", Field::Double(1.0)), "1.0");
assert_eq!(format!("{}", Field::Double(9.63)), "9.63");
assert_eq!(format!("{}", Field::Double(1e-15)), "0.000000000000001");
assert_eq!(format!("{}", Field::Double(1e-16)), "1E-16");
assert_eq!(format!("{}", Field::Double(1e19)), "10000000000000000000.0");
assert_eq!(format!("{}", Field::Double(1e20)), "1E20");
assert_eq!(
format!("{}", Field::Double(1.79769313486E308)),
"1.79769313486E308"
);
assert_eq!(
format!("{}", Field::Double(-1.79769313486E308)),
"-1.79769313486E308"
);
}
#[test]
fn test_convert_decimal_to_string() {
// Helper method to compare decimal
fn check_decimal(bytes: Vec<u8>, precision: i32, scale: i32, res: &str) {
let decimal = Decimal::from_bytes(ByteArray::from(bytes), precision, scale);
assert_eq!(convert_decimal_to_string(&decimal), res);
}
// This example previously used to fail in some engines
check_decimal(
vec![0, 0, 0, 0, 0, 0, 0, 0, 13, 224, 182, 179, 167, 100, 0, 0],
38,
18,
"1.000000000000000000",
);
check_decimal(
vec![
249, 233, 247, 16, 185, 192, 202, 223, 215, 165, 192, 166, 67, 72,
],
36,
28,
"-12344.0242342304923409234234293432",
);
check_decimal(vec![0, 0, 0, 0, 0, 4, 147, 224], 17, 5, "3.00000");
check_decimal(vec![0, 0, 0, 0, 1, 201, 195, 140], 18, 2, "300000.12");
check_decimal(vec![207, 200], 10, 2, "-123.44");
check_decimal(vec![207, 200], 10, 8, "-0.00012344");
}
#[test]
fn test_row_display() {
// Primitive types
assert_eq!(format!("{}", Field::Null), "null");
assert_eq!(format!("{}", Field::Bool(true)), "true");
assert_eq!(format!("{}", Field::Bool(false)), "false");
assert_eq!(format!("{}", Field::Byte(1)), "1");
assert_eq!(format!("{}", Field::Short(2)), "2");
assert_eq!(format!("{}", Field::Int(3)), "3");
assert_eq!(format!("{}", Field::Long(4)), "4");
assert_eq!(format!("{}", Field::UByte(1)), "1");
assert_eq!(format!("{}", Field::UShort(2)), "2");
assert_eq!(format!("{}", Field::UInt(3)), "3");
assert_eq!(format!("{}", Field::ULong(4)), "4");
assert_eq!(format!("{}", Field::Float(5.0)), "5.0");
assert_eq!(format!("{}", Field::Float(5.1234)), "5.1234");
assert_eq!(format!("{}", Field::Double(6.0)), "6.0");
assert_eq!(format!("{}", Field::Double(6.1234)), "6.1234");
assert_eq!(format!("{}", Field::Str("abc".to_string())), "\"abc\"");
assert_eq!(
format!("{}", Field::Bytes(ByteArray::from(vec![1, 2, 3]))),