/
Importer.cpp
3791 lines (3502 loc) · 132 KB
/
Importer.cpp
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
/*
* Copyright 2017 MapD Technologies, Inc.
*
* Licensed 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.
*/
/*
* @file Importer.cpp
* @author Wei Hong <wei@mapd.com>
* @brief Functions for Importer class
*/
#include <csignal>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <stdexcept>
#include <list>
#include <vector>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <thread>
#include <future>
#include <mutex>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/dynamic_bitset.hpp>
#include <glog/logging.h>
#include <ogrsf_frmts.h>
#include <gdal.h>
#include "../QueryEngine/SqlTypesLayout.h"
#include "../QueryEngine/TypePunning.h"
#include "../Shared/mapdpath.h"
#include "../Shared/measure.h"
#include "../Shared/unreachable.h"
#include "../Shared/geosupport.h"
#include "../Shared/mapd_glob.h"
#include "../Shared/scope.h"
#include "Importer.h"
#include "DataMgr/LockMgr.h"
#include "Utils/ChunkAccessorTable.h"
#include "gen-cpp/MapD.h"
#include <vector>
#include <iostream>
#include <arrow/api.h>
#include "../Archive/PosixFileArchive.h"
#include "../Archive/S3Archive.h"
using std::ostream;
namespace Importer_NS {
using FieldNameToIndexMapType = std::map<std::string, size_t>;
using ColumnNameToSourceNameMapType = std::map<std::string, std::string>;
using ColumnIdToRenderGroupAnalyzerMapType = std::map<int, std::shared_ptr<RenderGroupAnalyzer>>;
using FeaturePtrVector = std::vector<OGRFeature*>;
using GeometryPtrVector = std::vector<OGRGeometry*>;
#define DEBUG_TIMING false
#define DEBUG_RENDER_GROUP_ANALYZER 0
#define DEBUG_AWS_AUTHENTICATION 0
#define DISABLE_MULTI_THREADED_SHAPEFILE_IMPORT 0
#define PROMOTE_POLYGON_TO_MULTIPOLYGON 1
// the EPSG that we force geographic data to
// 4326 = WGS84 lat/lon
#define GEOGRAPHIC_SPATIAL_REFERENCE 4326
static mapd_shared_mutex status_mutex;
static std::map<std::string, ImportStatus> import_status_map;
Importer::Importer(Catalog_Namespace::Catalog& c, const TableDescriptor* t, const std::string& f, const CopyParams& p)
: Importer(new Loader(c, t), f, p) {}
Importer::Importer(Loader* providedLoader, const std::string& f, const CopyParams& p)
: DataStreamSink(p, f), loader(providedLoader) {
import_id = boost::filesystem::path(file_path).filename().string();
file_size = 0;
max_threads = 0;
p_file = nullptr;
buffer[0] = nullptr;
buffer[1] = nullptr;
auto is_array = std::unique_ptr<bool[]>(new bool[loader->get_column_descs().size()]);
int i = 0;
bool has_array = false;
for (auto& p : loader->get_column_descs()) {
if (p->columnType.get_type() == kARRAY) {
is_array.get()[i] = true;
has_array = true;
} else
is_array.get()[i] = false;
++i;
}
if (has_array)
is_array_a = std::unique_ptr<bool[]>(is_array.release());
else
is_array_a = std::unique_ptr<bool[]>(nullptr);
}
Importer::~Importer() {
if (p_file != nullptr)
fclose(p_file);
if (buffer[0] != nullptr)
free(buffer[0]);
if (buffer[1] != nullptr)
free(buffer[1]);
}
ImportStatus Importer::get_import_status(const std::string& import_id) {
mapd_shared_lock<mapd_shared_mutex> read_lock(status_mutex);
return import_status_map.at(import_id);
}
void Importer::set_import_status(const std::string& import_id, ImportStatus is) {
mapd_lock_guard<mapd_shared_mutex> write_lock(status_mutex);
is.end = std::chrono::steady_clock::now();
is.elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(is.end - is.start);
import_status_map[import_id] = is;
}
static const std::string trim_space(const char* field, const size_t len) {
size_t i = 0;
size_t j = len;
while (i < j && (field[i] == ' ' || field[i] == '\r')) {
i++;
}
while (i < j && (field[j - 1] == ' ' || field[j - 1] == '\r')) {
j--;
}
return std::string(field + i, j - i);
}
static const bool is_eol(const char& p, const std::string& line_delims) {
for (auto i : line_delims) {
if (p == i) {
return true;
}
}
return false;
}
static const char* get_row(const char* buf,
const char* buf_end,
const char* entire_buf_end,
const CopyParams& copy_params,
bool is_begin,
const bool* is_array,
std::vector<std::string>& row,
bool& try_single_thread) {
const char* field = buf;
const char* p;
bool in_quote = false;
bool in_array = false;
bool has_escape = false;
bool strip_quotes = false;
try_single_thread = false;
std::string line_endings({copy_params.line_delim, '\r', '\n'});
for (p = buf; p < entire_buf_end; p++) {
if (*p == copy_params.escape && p < entire_buf_end - 1 && *(p + 1) == copy_params.quote) {
p++;
has_escape = true;
} else if (copy_params.quoted && *p == copy_params.quote) {
in_quote = !in_quote;
if (in_quote)
strip_quotes = true;
} else if (!in_quote && is_array != nullptr && *p == copy_params.array_begin && is_array[row.size()]) {
in_array = true;
} else if (!in_quote && is_array != nullptr && *p == copy_params.array_end && is_array[row.size()]) {
in_array = false;
} else if (*p == copy_params.delimiter || is_eol(*p, line_endings)) {
if (!in_quote && !in_array) {
if (!has_escape && !strip_quotes) {
std::string s = trim_space(field, p - field);
row.push_back(s);
} else {
auto field_buf = std::unique_ptr<char[]>(new char[p - field + 1]);
int j = 0, i = 0;
for (; i < p - field; i++, j++) {
if (has_escape && field[i] == copy_params.escape && field[i + 1] == copy_params.quote) {
field_buf[j] = copy_params.quote;
i++;
} else {
field_buf[j] = field[i];
}
}
std::string s = trim_space(field_buf.get(), j);
if (copy_params.quoted && s.size() > 0 && s.front() == copy_params.quote) {
s.erase(0, 1);
}
if (copy_params.quoted && s.size() > 0 && s.back() == copy_params.quote) {
s.pop_back();
}
row.push_back(s);
}
field = p + 1;
has_escape = false;
strip_quotes = false;
}
if (is_eol(*p, line_endings) && ((!in_quote && !in_array) || copy_params.threads != 1)) {
while (p + 1 < buf_end && is_eol(*(p + 1), line_endings)) {
p++;
}
break;
}
}
}
/*
@TODO(wei) do error handling
*/
if (in_quote) {
LOG(ERROR) << "Unmatched quote.";
try_single_thread = true;
}
if (in_array) {
LOG(ERROR) << "Unmatched array.";
try_single_thread = true;
}
return p;
}
int8_t* appendDatum(int8_t* buf, Datum d, const SQLTypeInfo& ti) {
switch (ti.get_type()) {
case kBOOLEAN:
*(bool*)buf = d.boolval;
return buf + sizeof(bool);
case kNUMERIC:
case kDECIMAL:
case kBIGINT:
*(int64_t*)buf = d.bigintval;
return buf + sizeof(int64_t);
case kINT:
*(int32_t*)buf = d.intval;
return buf + sizeof(int32_t);
case kSMALLINT:
*(int16_t*)buf = d.smallintval;
return buf + sizeof(int16_t);
case kTINYINT:
*(int8_t*)buf = d.tinyintval;
return buf + sizeof(int8_t);
case kFLOAT:
*(float*)buf = d.floatval;
return buf + sizeof(float);
case kDOUBLE:
*(double*)buf = d.doubleval;
return buf + sizeof(double);
case kTIME:
case kTIMESTAMP:
case kDATE:
*(time_t*)buf = d.timeval;
return buf + sizeof(time_t);
default:
return NULL;
}
return NULL;
}
ArrayDatum StringToArray(const std::string& s, const SQLTypeInfo& ti, const CopyParams& copy_params) {
SQLTypeInfo elem_ti = ti.get_elem_type();
if (s[0] != copy_params.array_begin || s[s.size() - 1] != copy_params.array_end) {
LOG(WARNING) << "Malformed array: " << s;
return ArrayDatum(0, NULL, true);
}
std::vector<std::string> elem_strs;
size_t last = 1;
for (size_t i = s.find(copy_params.array_delim, 1); i != std::string::npos;
i = s.find(copy_params.array_delim, last)) {
elem_strs.push_back(s.substr(last, i - last));
last = i + 1;
}
if (last + 1 < s.size()) {
elem_strs.push_back(s.substr(last, s.size() - 1 - last));
}
if (!elem_ti.is_string()) {
size_t len = elem_strs.size() * elem_ti.get_size();
int8_t* buf = (int8_t*)checked_malloc(len);
int8_t* p = buf;
for (auto& e : elem_strs) {
Datum d = StringToDatum(e, elem_ti);
p = appendDatum(p, d, elem_ti);
}
return ArrayDatum(len, buf, len == 0);
}
// must not be called for array of strings
CHECK(false);
return ArrayDatum(0, NULL, true);
}
void addBinaryStringArray(const TDatum& datum, std::vector<std::string>& string_vec) {
const auto& arr = datum.val.arr_val;
for (const auto& elem_datum : arr) {
string_vec.push_back(elem_datum.val.str_val);
}
}
Datum TDatumToDatum(const TDatum& datum, SQLTypeInfo& ti) {
Datum d;
const auto type = ti.is_decimal() ? decimal_to_int_type(ti) : ti.get_type();
switch (type) {
case kBOOLEAN:
d.boolval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kBIGINT:
d.bigintval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kINT:
d.intval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kSMALLINT:
d.smallintval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kTINYINT:
d.tinyintval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kFLOAT:
d.floatval = datum.is_null ? NULL_FLOAT : datum.val.real_val;
break;
case kDOUBLE:
d.doubleval = datum.is_null ? NULL_DOUBLE : datum.val.real_val;
break;
case kTIME:
case kTIMESTAMP:
case kDATE:
d.timeval = datum.is_null ? inline_fixed_encoding_null_val(ti) : datum.val.int_val;
break;
case kPOINT:
case kLINESTRING:
case kPOLYGON:
case kMULTIPOLYGON:
throw std::runtime_error("Internal error: geometry type in TDatumToDatum.");
default:
throw std::runtime_error("Internal error: invalid type in TDatumToDatum.");
}
return d;
}
ArrayDatum TDatumToArrayDatum(const TDatum& datum, const SQLTypeInfo& ti) {
SQLTypeInfo elem_ti = ti.get_elem_type();
CHECK(!elem_ti.is_string());
size_t len = datum.val.arr_val.size() * elem_ti.get_size();
int8_t* buf = (int8_t*)checked_malloc(len);
int8_t* p = buf;
for (auto& e : datum.val.arr_val) {
p = appendDatum(p, TDatumToDatum(e, elem_ti), elem_ti);
}
return ArrayDatum(len, buf, len == 0);
}
static size_t find_beginning(const char* buffer, size_t begin, size_t end, const CopyParams& copy_params) {
// @TODO(wei) line_delim is in quotes note supported
if (begin == 0 || (begin > 0 && buffer[begin - 1] == copy_params.line_delim))
return 0;
size_t i;
const char* buf = buffer + begin;
for (i = 0; i < end - begin; i++)
if (buf[i] == copy_params.line_delim)
return i + 1;
return i;
}
void TypedImportBuffer::add_value(const ColumnDescriptor* cd,
const std::string& val,
const bool is_null,
const CopyParams& copy_params) {
const auto type = cd->columnType.get_type();
switch (type) {
case kBOOLEAN: {
if (is_null) {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addBoolean(inline_fixed_encoding_null_val(cd->columnType));
} else {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addBoolean((int8_t)d.boolval);
}
break;
}
case kTINYINT: {
if (!is_null && (isdigit(val[0]) || val[0] == '-')) {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addTinyint(d.tinyintval);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addTinyint(inline_fixed_encoding_null_val(cd->columnType));
}
break;
}
case kSMALLINT: {
if (!is_null && (isdigit(val[0]) || val[0] == '-')) {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addSmallint(d.smallintval);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addSmallint(inline_fixed_encoding_null_val(cd->columnType));
}
break;
}
case kINT: {
if (!is_null && (isdigit(val[0]) || val[0] == '-')) {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addInt(d.intval);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addInt(inline_fixed_encoding_null_val(cd->columnType));
}
break;
}
case kBIGINT: {
if (!is_null && (isdigit(val[0]) || val[0] == '-')) {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addBigint(d.bigintval);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addBigint(inline_fixed_encoding_null_val(cd->columnType));
}
break;
}
case kDECIMAL:
case kNUMERIC: {
if (!is_null) {
SQLTypeInfo ti(kNUMERIC, 0, 0, false);
Datum d = StringToDatum(val, ti);
const auto converted_decimal_value = convert_decimal_value_to_scale(d.bigintval, ti, cd->columnType);
addBigint(converted_decimal_value);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addBigint(inline_fixed_encoding_null_val(cd->columnType));
}
break;
}
case kFLOAT:
if (!is_null && (val[0] == '.' || isdigit(val[0]) || val[0] == '-')) {
addFloat((float)std::atof(val.c_str()));
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addFloat(NULL_FLOAT);
}
break;
case kDOUBLE:
if (!is_null && (val[0] == '.' || isdigit(val[0]) || val[0] == '-')) {
addDouble(std::atof(val.c_str()));
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addDouble(NULL_DOUBLE);
}
break;
case kTEXT:
case kVARCHAR:
case kCHAR: {
// @TODO(wei) for now, use empty string for nulls
if (is_null) {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addString(std::string());
} else {
if (val.length() > StringDictionary::MAX_STRLEN)
throw std::runtime_error("String too long for column " + cd->columnName + " was " +
std::to_string(val.length()) + " max is " +
std::to_string(StringDictionary::MAX_STRLEN));
addString(val);
}
break;
}
case kTIME:
case kTIMESTAMP:
case kDATE:
if (!is_null && (isdigit(val[0]) || val[0] == '-')) {
SQLTypeInfo ti = cd->columnType;
Datum d = StringToDatum(val, ti);
addTime(d.timeval);
} else {
if (cd->columnType.get_notnull())
throw std::runtime_error("NULL for column " + cd->columnName);
addTime(inline_fixed_encoding_null_val(cd->columnType));
}
break;
case kARRAY:
if (is_null && cd->columnType.get_notnull()) {
throw std::runtime_error("NULL for column " + cd->columnName);
}
if (IS_STRING(cd->columnType.get_subtype())) {
std::vector<std::string>& string_vec = addStringArray();
ImporterUtils::parseStringArray(val, copy_params, string_vec);
} else {
if (!is_null) {
ArrayDatum d = StringToArray(val, cd->columnType, copy_params);
addArray(d);
} else {
addArray(ArrayDatum(0, NULL, true));
}
}
break;
case kPOINT:
case kLINESTRING:
case kPOLYGON:
case kMULTIPOLYGON:
addGeoString(val);
break;
default:
CHECK(false);
}
}
void TypedImportBuffer::pop_value() {
const auto type = column_desc_->columnType.is_decimal() ? decimal_to_int_type(column_desc_->columnType)
: column_desc_->columnType.get_type();
switch (type) {
case kBOOLEAN:
bool_buffer_->pop_back();
break;
case kSMALLINT:
smallint_buffer_->pop_back();
break;
case kINT:
int_buffer_->pop_back();
break;
case kBIGINT:
bigint_buffer_->pop_back();
break;
case kFLOAT:
float_buffer_->pop_back();
break;
case kDOUBLE:
double_buffer_->pop_back();
break;
case kTEXT:
case kVARCHAR:
case kCHAR:
string_buffer_->pop_back();
break;
case kTIME:
case kTIMESTAMP:
case kDATE:
time_buffer_->pop_back();
break;
case kARRAY:
if (IS_STRING(column_desc_->columnType.get_subtype())) {
string_array_buffer_->pop_back();
} else {
array_buffer_->pop_back();
}
break;
case kPOINT:
case kLINESTRING:
case kPOLYGON:
case kMULTIPOLYGON:
geo_string_buffer_->pop_back();
break;
default:
CHECK(false);
}
}
namespace {
using namespace arrow;
#define ARROW_THROW_IF(cond, message) \
if ((cond)) { \
LOG(ERROR) << message; \
throw std::runtime_error(message); \
}
template <typename ArrayType, typename T>
inline void append_arrow_primitive(const Array& values, const T null_sentinel, std::vector<T>* buffer) {
const auto& typed_values = static_cast<const ArrayType&>(values);
buffer->reserve(typed_values.length());
const T* raw_values = typed_values.raw_values();
if (typed_values.null_count() > 0) {
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
buffer->push_back(raw_values[i]);
}
}
} else {
for (int64_t i = 0; i < typed_values.length(); i++) {
buffer->push_back(raw_values[i]);
}
}
}
void append_arrow_boolean(const ColumnDescriptor* cd, const Array& values, std::vector<int8_t>* buffer) {
ARROW_THROW_IF(values.type_id() != Type::BOOL, "Expected boolean col");
const int8_t null_sentinel = inline_fixed_encoding_null_val(cd->columnType);
const auto& typed_values = static_cast<const BooleanArray&>(values);
buffer->reserve(typed_values.length());
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
buffer->push_back(static_cast<int8_t>(typed_values.Value(i)));
}
}
}
template <typename ArrowType, typename T>
void append_arrow_integer(const ColumnDescriptor* cd, const Array& values, std::vector<T>* buffer) {
using ArrayType = typename TypeTraits<ArrowType>::ArrayType;
const T null_sentinel = inline_fixed_encoding_null_val(cd->columnType);
append_arrow_primitive<ArrayType, T>(values, null_sentinel, buffer);
}
void append_arrow_float(const ColumnDescriptor* cd, const Array& values, std::vector<float>* buffer) {
ARROW_THROW_IF(values.type_id() != Type::FLOAT, "Expected float col");
append_arrow_primitive<FloatArray, float>(values, NULL_FLOAT, buffer);
}
void append_arrow_double(const ColumnDescriptor* cd, const Array& values, std::vector<double>* buffer) {
ARROW_THROW_IF(values.type_id() != Type::DOUBLE, "Expected double col");
append_arrow_primitive<DoubleArray, double>(values, NULL_DOUBLE, buffer);
}
constexpr int64_t kMillisecondsInSecond = 1000L;
constexpr int64_t kMicrosecondsInSecond = 1000L * 1000L;
constexpr int64_t kNanosecondsinSecond = 1000L * 1000L * 1000L;
constexpr int32_t kSecondsInDay = 86400;
void append_arrow_time(const ColumnDescriptor* cd, const Array& values, std::vector<time_t>* buffer) {
const time_t null_sentinel = inline_fixed_encoding_null_val(cd->columnType);
if (values.type_id() == Type::TIME32) {
const auto& typed_values = static_cast<const Time32Array&>(values);
const auto& type = static_cast<const Time32Type&>(*values.type());
buffer->reserve(typed_values.length());
const int32_t* raw_values = typed_values.raw_values();
const TimeUnit::type unit = type.unit();
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
switch (unit) {
case TimeUnit::SECOND:
buffer->push_back(static_cast<time_t>(raw_values[i]));
break;
case TimeUnit::MILLI:
buffer->push_back(static_cast<time_t>(raw_values[i] / kMillisecondsInSecond));
break;
default:
// unreachable code
CHECK(false);
break;
}
}
}
} else if (values.type_id() == Type::TIME64) {
const auto& typed_values = static_cast<const Time64Array&>(values);
const auto& type = static_cast<const Time64Type&>(*values.type());
buffer->reserve(typed_values.length());
const int64_t* raw_values = typed_values.raw_values();
const TimeUnit::type unit = type.unit();
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
switch (unit) {
case TimeUnit::MICRO:
buffer->push_back(static_cast<time_t>(raw_values[i] / kMicrosecondsInSecond));
break;
case TimeUnit::NANO:
buffer->push_back(static_cast<time_t>(raw_values[i] / kNanosecondsinSecond));
break;
default:
// unreachable code
CHECK(false);
break;
}
}
}
} else {
ARROW_THROW_IF(true, "Column was not time32 or time64");
}
}
void append_arrow_timestamp(const ColumnDescriptor* cd, const Array& values, std::vector<time_t>* buffer) {
ARROW_THROW_IF(values.type_id() != Type::TIMESTAMP, "Expected timestamp col");
const time_t null_sentinel = inline_fixed_encoding_null_val(cd->columnType);
const auto& typed_values = static_cast<const TimestampArray&>(values);
const auto& type = static_cast<const TimestampType&>(*values.type());
buffer->reserve(typed_values.length());
const int64_t* raw_values = typed_values.raw_values();
const TimeUnit::type unit = type.unit();
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
switch (unit) {
case TimeUnit::SECOND:
buffer->push_back(static_cast<time_t>(raw_values[i]));
break;
case TimeUnit::MILLI:
buffer->push_back(static_cast<time_t>(raw_values[i] / kMillisecondsInSecond));
break;
case TimeUnit::MICRO:
buffer->push_back(static_cast<time_t>(raw_values[i] / kMicrosecondsInSecond));
break;
case TimeUnit::NANO:
buffer->push_back(static_cast<time_t>(raw_values[i] / kNanosecondsinSecond));
break;
default:
break;
}
}
}
}
void append_arrow_date(const ColumnDescriptor* cd, const Array& values, std::vector<time_t>* buffer) {
const time_t null_sentinel = inline_fixed_encoding_null_val(cd->columnType);
if (values.type_id() == Type::DATE32) {
const auto& typed_values = static_cast<const Date32Array&>(values);
buffer->reserve(typed_values.length());
const int32_t* raw_values = typed_values.raw_values();
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
buffer->push_back(static_cast<time_t>(raw_values[i] * kSecondsInDay));
}
}
} else if (values.type_id() == Type::DATE64) {
const auto& typed_values = static_cast<const Date64Array&>(values);
buffer->reserve(typed_values.length());
const int64_t* raw_values = typed_values.raw_values();
// Convert from milliseconds since UNIX epoch
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
buffer->push_back(null_sentinel);
} else {
buffer->push_back(static_cast<time_t>(raw_values[i] / 1000));
}
}
} else {
ARROW_THROW_IF(true, "Column was not date32 or date64");
}
}
void append_arrow_binary(const ColumnDescriptor* cd, const Array& values, std::vector<std::string>* buffer) {
ARROW_THROW_IF(values.type_id() != Type::BINARY && values.type_id() != Type::STRING, "Expected binary col");
const auto& typed_values = static_cast<const BinaryArray&>(values);
buffer->reserve(typed_values.length());
const char* bytes;
int32_t bytes_length = 0;
for (int64_t i = 0; i < typed_values.length(); i++) {
if (typed_values.IsNull(i)) {
// TODO(wesm): How are nulls handled for strings?
buffer->push_back(std::string());
} else {
bytes = reinterpret_cast<const char*>(typed_values.GetValue(i, &bytes_length));
buffer->push_back(std::string(bytes, bytes_length));
}
}
}
} // namespace
size_t TypedImportBuffer::add_arrow_values(const ColumnDescriptor* cd, const arrow::Array& col) {
const auto type = cd->columnType.is_decimal() ? decimal_to_int_type(cd->columnType) : cd->columnType.get_type();
if (cd->columnType.get_notnull()) {
// We can't have any null values for this column; to have them is an error
if (col.null_count() > 0) {
throw std::runtime_error("NULL not allowed for column " + cd->columnName);
}
}
switch (type) {
case kBOOLEAN:
append_arrow_boolean(cd, col, bool_buffer_);
break;
case kSMALLINT:
ARROW_THROW_IF(col.type_id() != arrow::Type::INT16, "Expected int16 type");
append_arrow_integer<arrow::Int16Type, int16_t>(cd, col, smallint_buffer_);
break;
case kINT:
ARROW_THROW_IF(col.type_id() != arrow::Type::INT32, "Expected int32 type");
append_arrow_integer<arrow::Int32Type, int32_t>(cd, col, int_buffer_);
break;
case kBIGINT:
ARROW_THROW_IF(col.type_id() != arrow::Type::INT64, "Expected int64 type");
append_arrow_integer<arrow::Int64Type, int64_t>(cd, col, bigint_buffer_);
break;
case kFLOAT:
append_arrow_float(cd, col, float_buffer_);
break;
case kDOUBLE:
append_arrow_double(cd, col, double_buffer_);
break;
case kTEXT:
case kVARCHAR:
case kCHAR:
append_arrow_binary(cd, col, string_buffer_);
break;
case kTIME:
append_arrow_time(cd, col, time_buffer_);
break;
case kTIMESTAMP:
append_arrow_timestamp(cd, col, time_buffer_);
break;
case kDATE:
append_arrow_date(cd, col, time_buffer_);
break;
case kARRAY:
throw std::runtime_error("Arrow array appends not yet supported");
default:
throw std::runtime_error("Invalid Type");
}
return col.length();
}
size_t TypedImportBuffer::add_values(const ColumnDescriptor* cd, const TColumn& col) {
size_t dataSize = 0;
const auto type = cd->columnType.is_decimal() ? decimal_to_int_type(cd->columnType) : cd->columnType.get_type();
if (cd->columnType.get_notnull()) {
// We can't have any null values for this column; to have them is an error
if (std::any_of(col.nulls.begin(), col.nulls.end(), [](int i) { return i != 0; }))
throw std::runtime_error("NULL for column " + cd->columnName);
}
switch (type) {
case kBOOLEAN: {
dataSize = col.data.int_col.size();
bool_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
bool_buffer_->push_back(inline_fixed_encoding_null_val(cd->columnType));
else
bool_buffer_->push_back((int8_t)col.data.int_col[i]);
}
break;
}
case kSMALLINT: {
dataSize = col.data.int_col.size();
smallint_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
smallint_buffer_->push_back(inline_fixed_encoding_null_val(cd->columnType));
else
smallint_buffer_->push_back((int16_t)col.data.int_col[i]);
}
break;
}
case kINT: {
dataSize = col.data.int_col.size();
int_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
int_buffer_->push_back(inline_fixed_encoding_null_val(cd->columnType));
else
int_buffer_->push_back((int32_t)col.data.int_col[i]);
}
break;
}
case kBIGINT: {
dataSize = col.data.int_col.size();
bigint_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
bigint_buffer_->push_back(inline_fixed_encoding_null_val(cd->columnType));
else
bigint_buffer_->push_back((int64_t)col.data.int_col[i]);
}
break;
}
case kFLOAT: {
dataSize = col.data.real_col.size();
float_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
float_buffer_->push_back(NULL_FLOAT);
else
float_buffer_->push_back((float)col.data.real_col[i]);
}
break;
}
case kDOUBLE: {
dataSize = col.data.real_col.size();
double_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
double_buffer_->push_back(NULL_DOUBLE);
else
double_buffer_->push_back((double)col.data.real_col[i]);
}
break;
}
case kTEXT:
case kVARCHAR:
case kCHAR: {
// TODO: for now, use empty string for nulls
dataSize = col.data.str_col.size();
string_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
string_buffer_->push_back(std::string());
else
string_buffer_->push_back(col.data.str_col[i]);
}
break;
}
case kTIME:
case kTIMESTAMP:
case kDATE: {
dataSize = col.data.int_col.size();
time_buffer_->reserve(dataSize);
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
time_buffer_->push_back(inline_fixed_encoding_null_val(cd->columnType));
else
time_buffer_->push_back((time_t)col.data.int_col[i]);
}
break;
}
case kARRAY: {
// TODO: add support for nulls inside array
dataSize = col.data.arr_col.size();
if (IS_STRING(cd->columnType.get_subtype())) {
for (size_t i = 0; i < dataSize; i++) {
std::vector<std::string>& string_vec = addStringArray();
if (!col.nulls[i]) {
size_t stringArrSize = col.data.arr_col[i].data.str_col.size();
for (size_t str_idx = 0; str_idx != stringArrSize; ++str_idx)
string_vec.push_back(col.data.arr_col[i].data.str_col[str_idx]);
}
}
} else {
auto elem_ti = cd->columnType.get_subtype();
switch (elem_ti) {
case kBOOLEAN: {
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
addArray(ArrayDatum(0, NULL, true));
else {
size_t len = col.data.arr_col[i].data.int_col.size();
size_t byteSize = len * sizeof(int8_t);
int8_t* buf = (int8_t*)checked_malloc(len * byteSize);
int8_t* p = buf;
for (size_t j = 0; j < len; ++j) {
*(bool*)p = static_cast<bool>(col.data.arr_col[i].data.int_col[j]);
p += sizeof(bool);
}
addArray(ArrayDatum(byteSize, buf, len == 0));
}
}
break;
}
case kSMALLINT: {
for (size_t i = 0; i < dataSize; i++) {
if (col.nulls[i])
addArray(ArrayDatum(0, NULL, true));
else {
size_t len = col.data.arr_col[i].data.int_col.size();
size_t byteSize = len * sizeof(int16_t);
int8_t* buf = (int8_t*)checked_malloc(len * byteSize);
int8_t* p = buf;
for (size_t j = 0; j < len; ++j) {
*(int16_t*)p = static_cast<int16_t>(col.data.arr_col[i].data.int_col[j]);
p += sizeof(int16_t);
}
addArray(ArrayDatum(byteSize, buf, len == 0));