forked from apache/arrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtpch_node.cc
More file actions
3543 lines (3206 loc) · 146 KB
/
Copy pathtpch_node.cc
File metadata and controls
3543 lines (3206 loc) · 146 KB
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.
#include "arrow/compute/exec/tpch_node.h"
#include <algorithm>
#include <bitset>
#include <cstring>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "arrow/buffer.h"
#include "arrow/compute/exec.h"
#include "arrow/compute/exec/exec_plan.h"
#include "arrow/compute/exec/query_context.h"
#include "arrow/datum.h"
#include "arrow/util/async_util.h"
#include "arrow/util/formatting.h"
#include "arrow/util/future.h"
#include "arrow/util/io_util.h"
#include "arrow/util/logging.h"
#include "arrow/util/pcg_random.h"
#include "arrow/util/unreachable.h"
namespace arrow {
using internal::checked_cast;
using internal::GetRandomSeed;
namespace compute {
namespace internal {
/*
Architecture of the generator:
This is a multithreaded implementation of TPC-H's DBGen data generator. For each table
that doesn't depend on any other tables, it gets its own generator. For tables that
are dependent on each other (namely [ORDERS, LINEITEM] and [PART, PARTSUPP]), we
implement a "double generator". Each generator is given a list of columns to generate.
Columns are then generated lazily a batch at a time. If column A depends on another column
B, column A will ensure that column B is always generated. We don't have to worry about
breaking cycles of dependencies because the dependency graph is acyclic (so there's no
code to even bother breaking cycles). Double generators work by maintaining two output
queues. Batches for each of the tables are generated in sync, and batches that are not
being output immediately are appended to the queue.
To generate a batch, we grab a lock, increment a counter, check the output queue (if
applicable), and then call the necessary generator functions. To generate a column, we
first check if it's already been generated. If not, we allocate the batch and then fill it
according to the spec.
There are a few types of columns that get generated:
- Primary Keys: incrementing counters from 1 to N (with N being the number of rows).
These are generated by incrementing a counter (this counter is gated under a lock).
- V-String: Random-length string of alphanumerics
- Phone Number: 2, 3, 3, and 4, digit numbers separated by -'s
- Random Numbers: random numbers within some range
- Expressions: expressions based on some other columns
Please consult the spec for intended behavior of each individual column. Columns are
generated by a function of the same name (so e.g. the column PS_PARTKEY is generated by a
function PS_PARTKEY).
*/
namespace {
const char* NameParts[] = {
"almond", "antique", "aquamarine", "azure", "beige", "bisque",
"black", "blanched", "blue", "blush", "brown", "burlywood",
"burnished", "chartreuse", "chiffon", "chocolate", "coral", "cornflower",
"cornsilk", "cream", "cyan", "dark", "deep", "dim",
"dodger", "drab", "firebrick", "floral", "forest", "frosted",
"gainsboro", "ghost", "goldenrod", "green", "grey", "honeydew",
"hot", "indian", "ivory", "khaki", "lace", "lavender",
"lawn", "lemon", "light", "lime", "linen", "magenta",
"maroon", "medium", "metallic", "midnight", "mint", "misty",
"moccasin", "navajo", "navy", "olive", "orange", "orchid",
"pale", "papaya", "peach", "peru", "pink", "plum",
"powder", "puff", "purple", "red", "rose", "rosy",
"royal", "saddle", "salmon", "sandy", "seashell", "sienna",
"sky", "slate", "smoke", "snow", "spring", "steel",
"tan", "thistle", "tomato", "turquoise", "violet", "wheat",
"white", "yellow",
};
constexpr size_t kNumNameParts = sizeof(NameParts) / sizeof(NameParts[0]);
const char* Types_1[] = {
"STANDARD ", "SMALL ", "MEDIUM ", "LARGE ", "ECONOMY ", "PROMO ",
};
constexpr size_t kNumTypes_1 = sizeof(Types_1) / sizeof(Types_1[0]);
const char* Types_2[] = {
"ANODIZED ", "BURNISHED ", "PLATED ", "POLISHED ", "BRUSHED ",
};
constexpr size_t kNumTypes_2 = sizeof(Types_2) / sizeof(Types_2[0]);
const char* Types_3[] = {
"TIN", "NICKEL", "BRASS", "STEEL", "COPPER",
};
constexpr size_t kNumTypes_3 = sizeof(Types_3) / sizeof(Types_3[0]);
const char* Containers_1[] = {
"SM ", "LG ", "MD ", "JUMBO ", "WRAP ",
};
constexpr size_t kNumContainers_1 = sizeof(Containers_1) / sizeof(Containers_1[0]);
const char* Containers_2[] = {
"CASE", "BOX", "BAG", "JAR", "PKG", "PACK", "CAN", "DRUM",
};
constexpr size_t kNumContainers_2 = sizeof(Containers_2) / sizeof(Containers_2[0]);
const char* Segments[] = {
"AUTOMOBILE", "BUILDING", "FURNITURE", "MACHINERY", "HOUSEHOLD",
};
constexpr size_t kNumSegments = sizeof(Segments) / sizeof(Segments[0]);
const char* Priorities[] = {
"1-URGENT", "2-HIGH", "3-MEDIUM", "4-NOT SPECIFIED", "5-LOW",
};
constexpr size_t kNumPriorities = sizeof(Priorities) / sizeof(Priorities[0]);
const char* Instructions[] = {
"DELIVER IN PERSON",
"COLLECT COD",
"NONE",
"TAKE BACK RETURN",
};
constexpr size_t kNumInstructions = sizeof(Instructions) / sizeof(Instructions[0]);
const char* Modes[] = {
"REG AIR", "AIR", "RAIL", "SHIP", "TRUCK", "MAIL", "FOB",
};
constexpr size_t kNumModes = sizeof(Modes) / sizeof(Modes[0]);
const char* Nouns[] = {
"foxes ", "ideas ", "theodolites ", "pinto beans ", "instructions ",
"dependencies ", "excuses ", "platelets ", "asymptotes ", "courts ",
"dolphins ", "multipliers ", "sautemes ", "warthogs ", "frets ",
"dinos ", "attainments ", "somas ", "Tiresias '", "patterns ",
"forges ", "braids ", "hockey players ", "frays ", "warhorses ",
"dugouts ", "notomis ", "epitaphs ", "pearls ", "tithes ",
"waters ", "orbits ", "gifts ", "sheaves ", "depths ",
"sentiments ", "decoys ", "realms ", "pains ", "grouches ",
"escapades ",
};
constexpr size_t kNumNouns = sizeof(Nouns) / sizeof(Nouns[0]);
const char* Verbs[] = {
"sleep ", "wake ", "are ", "cajole ", "haggle ", "nag ", "use ",
"boost ", "affix ", "detect ", "integrate ", "maintain ", "nod ", "was ",
"lose ", "sublate ", "solve ", "thrash ", "promise ", "engage ", "hinder ",
"print ", "x-ray ", "breach ", "eat ", "grow ", "impress ", "mold ",
"poach ", "serve ", "run ", "dazzle ", "snooze ", "doze ", "unwind ",
"kindle ", "play ", "hang ", "believe ", "doubt ",
};
constexpr size_t kNumVerbs = sizeof(Verbs) / sizeof(Verbs[0]);
const char* Adjectives[] = {
"furious ", "sly ", "careful ", "blithe ", "quick ", "fluffy ", "slow ",
"quiet ", "ruthless ", "thin ", "close ", "dogged ", "daring ", "brave ",
"stealthy ", "permanent ", "enticing ", "idle ", "busy ", "regular ", "final ",
"ironic ", "even ", "bold ", "silent ",
};
constexpr size_t kNumAdjectives = sizeof(Adjectives) / sizeof(Adjectives[0]);
const char* Adverbs[] = {
"sometimes ", "always ", "never ", "furiously ", "slyly ", "carefully ",
"blithely ", "quickly ", "fluffily ", "slowly ", "quietly ", "ruthlessly ",
"thinly ", "closely ", "doggedly ", "daringly ", "bravely ", "stealthily ",
"permanently ", "enticingly ", "idly ", "busily ", "regularly ", "finally ",
"ironically ", "evenly ", "boldly ", "silently ",
};
constexpr size_t kNumAdverbs = sizeof(Adverbs) / sizeof(Adverbs[0]);
const char* Prepositions[] = {
"about ", "above ", "according to ", "across ", "after ", "against ",
"along ", "alongside of ", "among ", "around ", "at ", "atop ",
"before ", "behind ", "beneath ", "beside ", "besides ", "between ",
"beyond ", "beyond ", "by ", "despite ", "during ", "except ",
"for ", "from ", "in place of ", "inside ", "instead of ", "into ",
"near ", "of ", "on ", "outside ", "over ", "past ",
"since ", "through ", "throughout ", "to ", "toward ", "under ",
"until ", "up ", "upon ", "without ", "with ", "within ",
};
constexpr size_t kNumPrepositions = sizeof(Prepositions) / sizeof(Prepositions[0]);
const char* Auxiliaries[] = {
"do ",
"may ",
"might ",
"shall ",
"will ",
"would ",
"can ",
"could ",
"should ",
"ought to ",
"must ",
"will have to ",
"shall have to ",
"could have to ",
"should have to ",
"must have to ",
"need to ",
"try to ",
};
constexpr size_t kNumAuxiliaries = sizeof(Auxiliaries) / sizeof(Auxiliaries[0]);
const char* Terminators[] = {
".", ";", ":", "?", "!", "--",
};
constexpr size_t kNumTerminators = sizeof(Terminators) / sizeof(Terminators[0]);
constexpr uint32_t kStartDate =
8035; // January 1, 1992 is 8035 days after January 1, 1970
constexpr uint32_t kCurrentDate =
9298; // June 17, 1995 is 9298 days after January 1, 1970
constexpr uint32_t kEndDate =
10591; // December 12, 1998 is 10591 days after January 1, 1970
std::uniform_int_distribution<int64_t> kSeedDist(std::numeric_limits<int64_t>::min(),
std::numeric_limits<int64_t>::max());
// The spec says to generate a 300 MB string according to a grammar. This is a
// concurrent implementation of the generator. Each thread generates the text in
// (up to) 8KB chunks of text. The generator maintains a cursor into the
// 300 MB buffer. After generating the chunk, the cursor is incremented
// to reserve space, and the chunk is memcpy-d in.
// This text is used to generate the COMMENT columns. To generate a comment, the spec
// says to pick a random length and a random offset into the 300 MB buffer (it does
// not specify it should be word/sentence aligned), and that slice of text becomes
// the comment.
class TpchPseudotext {
public:
Status EnsureInitialized(random::pcg32_fast& rng);
Result<Datum> GenerateComments(size_t num_comments, size_t min_length,
size_t max_length, random::pcg32_fast& rng);
private:
bool GenerateWord(int64_t& offset, random::pcg32_fast& rng, char* arr,
const char** words, size_t num_choices);
bool GenerateNoun(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateVerb(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateAdjective(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateAdverb(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GeneratePreposition(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateAuxiliary(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateTerminator(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateNounPhrase(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateVerbPhrase(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GeneratePrepositionalPhrase(int64_t& offset, random::pcg32_fast& rng, char* arr);
bool GenerateSentence(int64_t& offset, random::pcg32_fast& rng, char* arr);
std::atomic<bool> done_ = {false};
int64_t generated_offset_{0};
std::mutex text_guard_;
std::unique_ptr<Buffer> text_;
static constexpr int64_t kChunkSize = 8192;
static constexpr int64_t kTextBytes = 300 * 1024 * 1024; // 300 MB
};
static TpchPseudotext g_text;
Status TpchPseudotext::EnsureInitialized(random::pcg32_fast& rng) {
if (done_.load()) return Status::OK();
{
std::lock_guard<std::mutex> lock(text_guard_);
if (!text_) {
ARROW_ASSIGN_OR_RAISE(text_, AllocateBuffer(kTextBytes));
}
}
char* out = reinterpret_cast<char*>(text_->mutable_data());
char temp_buff[kChunkSize];
while (!done_.load()) {
int64_t known_valid_offset = 0;
int64_t try_offset = 0;
while (GenerateSentence(try_offset, rng, temp_buff)) known_valid_offset = try_offset;
bool last_one;
int64_t offset;
int64_t memcpy_size;
{
std::lock_guard<std::mutex> lock(text_guard_);
if (done_.load()) return Status::OK();
int64_t bytes_remaining = kTextBytes - generated_offset_;
memcpy_size = std::min(known_valid_offset, bytes_remaining);
offset = generated_offset_;
generated_offset_ += memcpy_size;
last_one = generated_offset_ == kTextBytes;
}
std::memcpy(out + offset, temp_buff, memcpy_size);
if (last_one) done_.store(true);
}
return Status::OK();
}
Result<Datum> TpchPseudotext::GenerateComments(size_t num_comments, size_t min_length,
size_t max_length,
random::pcg32_fast& rng) {
RETURN_NOT_OK(EnsureInitialized(rng));
std::uniform_int_distribution<size_t> length_dist(min_length, max_length);
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> offset_buffer,
AllocateBuffer(sizeof(int32_t) * (num_comments + 1)));
int32_t* offsets = reinterpret_cast<int32_t*>(offset_buffer->mutable_data());
offsets[0] = 0;
for (size_t i = 1; i <= num_comments; i++)
offsets[i] = offsets[i - 1] + static_cast<int32_t>(length_dist(rng));
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> comment_buffer,
AllocateBuffer(offsets[num_comments]));
char* comments = reinterpret_cast<char*>(comment_buffer->mutable_data());
for (size_t i = 0; i < num_comments; i++) {
size_t length = offsets[i + 1] - offsets[i];
std::uniform_int_distribution<size_t> offset_dist(0, kTextBytes - length);
size_t offset_in_text = offset_dist(rng);
std::memcpy(comments + offsets[i], text_->data() + offset_in_text, length);
}
ArrayData ad(utf8(), num_comments,
{nullptr, std::move(offset_buffer), std::move(comment_buffer)});
return std::move(ad);
}
bool TpchPseudotext::GenerateWord(int64_t& offset, random::pcg32_fast& rng, char* arr,
const char** words, size_t num_choices) {
std::uniform_int_distribution<size_t> dist(0, num_choices - 1);
const char* word = words[dist(rng)];
size_t length = std::strlen(word);
if (offset + length > kChunkSize) return false;
std::memcpy(arr + offset, word, length);
offset += length;
return true;
}
bool TpchPseudotext::GenerateNoun(int64_t& offset, random::pcg32_fast& rng, char* arr) {
return GenerateWord(offset, rng, arr, Nouns, kNumNouns);
}
bool TpchPseudotext::GenerateVerb(int64_t& offset, random::pcg32_fast& rng, char* arr) {
return GenerateWord(offset, rng, arr, Verbs, kNumVerbs);
}
bool TpchPseudotext::GenerateAdjective(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
return GenerateWord(offset, rng, arr, Adjectives, kNumAdjectives);
}
bool TpchPseudotext::GenerateAdverb(int64_t& offset, random::pcg32_fast& rng, char* arr) {
return GenerateWord(offset, rng, arr, Adverbs, kNumAdverbs);
}
bool TpchPseudotext::GeneratePreposition(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
return GenerateWord(offset, rng, arr, Prepositions, kNumPrepositions);
}
bool TpchPseudotext::GenerateAuxiliary(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
return GenerateWord(offset, rng, arr, Auxiliaries, kNumAuxiliaries);
}
bool TpchPseudotext::GenerateTerminator(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
bool result = GenerateWord(offset, rng, arr, Terminators, kNumTerminators);
// Swap the space with the terminator
if (result) std::swap(*(arr + offset - 2), *(arr + offset - 1));
return result;
}
bool TpchPseudotext::GenerateNounPhrase(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
std::uniform_int_distribution<size_t> dist(0, 3);
const char* comma_space = ", ";
bool success = true;
switch (dist(rng)) {
case 0:
success &= GenerateNoun(offset, rng, arr);
break;
case 1:
success &= GenerateAdjective(offset, rng, arr);
success &= GenerateNoun(offset, rng, arr);
break;
case 2:
success &= GenerateAdjective(offset, rng, arr);
success &= GenerateWord(--offset, rng, arr, &comma_space, 1);
success &= GenerateAdjective(offset, rng, arr);
success &= GenerateNoun(offset, rng, arr);
break;
case 3:
success &= GenerateAdverb(offset, rng, arr);
success &= GenerateAdjective(offset, rng, arr);
success &= GenerateNoun(offset, rng, arr);
break;
default:
Unreachable("Random number should be between 0 and 3 inclusive");
break;
}
return success;
}
bool TpchPseudotext::GenerateVerbPhrase(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
std::uniform_int_distribution<size_t> dist(0, 3);
bool success = true;
switch (dist(rng)) {
case 0:
success &= GenerateVerb(offset, rng, arr);
break;
case 1:
success &= GenerateAuxiliary(offset, rng, arr);
success &= GenerateVerb(offset, rng, arr);
break;
case 2:
success &= GenerateVerb(offset, rng, arr);
success &= GenerateAdverb(offset, rng, arr);
break;
case 3:
success &= GenerateAuxiliary(offset, rng, arr);
success &= GenerateVerb(offset, rng, arr);
success &= GenerateAdverb(offset, rng, arr);
break;
default:
Unreachable("Random number should be between 0 and 3 inclusive");
break;
}
return success;
}
bool TpchPseudotext::GeneratePrepositionalPhrase(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
const char* the_space = "the ";
bool success = true;
success &= GeneratePreposition(offset, rng, arr);
success &= GenerateWord(offset, rng, arr, &the_space, 1);
success &= GenerateNounPhrase(offset, rng, arr);
return success;
}
bool TpchPseudotext::GenerateSentence(int64_t& offset, random::pcg32_fast& rng,
char* arr) {
std::uniform_int_distribution<size_t> dist(0, 4);
bool success = true;
switch (dist(rng)) {
case 0:
success &= GenerateNounPhrase(offset, rng, arr);
success &= GenerateVerbPhrase(offset, rng, arr);
success &= GenerateTerminator(offset, rng, arr);
break;
case 1:
success &= GenerateNounPhrase(offset, rng, arr);
success &= GenerateVerbPhrase(offset, rng, arr);
success &= GeneratePrepositionalPhrase(offset, rng, arr);
success &= GenerateTerminator(offset, rng, arr);
break;
case 2:
success &= GenerateNounPhrase(offset, rng, arr);
success &= GenerateVerbPhrase(offset, rng, arr);
success &= GenerateNounPhrase(offset, rng, arr);
success &= GenerateTerminator(offset, rng, arr);
break;
case 3:
success &= GenerateNounPhrase(offset, rng, arr);
success &= GeneratePrepositionalPhrase(offset, rng, arr);
success &= GenerateVerbPhrase(offset, rng, arr);
success &= GenerateNounPhrase(offset, rng, arr);
success &= GenerateTerminator(offset, rng, arr);
break;
case 4:
success &= GenerateNounPhrase(offset, rng, arr);
success &= GeneratePrepositionalPhrase(offset, rng, arr);
success &= GenerateVerbPhrase(offset, rng, arr);
success &= GeneratePrepositionalPhrase(offset, rng, arr);
success &= GenerateTerminator(offset, rng, arr);
break;
default:
Unreachable("Random number should be between 0 and 5 inclusive");
break;
}
return success;
}
class TpchTableGenerator {
public:
using OutputBatchCallback = std::function<Status(ExecBatch)>;
using FinishedCallback = std::function<Status(int64_t)>;
using GenerateFn = std::function<Status(size_t)>;
using ScheduleCallback = std::function<Status(GenerateFn)>;
using AbortCallback = std::function<void()>;
virtual Status Init(std::vector<std::string> columns, double scale_factor,
int64_t batch_size, int64_t seed) = 0;
virtual Status StartProducing(size_t num_threads, OutputBatchCallback output_callback,
FinishedCallback finished_callback,
ScheduleCallback schedule_callback) = 0;
bool Abort() {
bool expected = false;
return done_.compare_exchange_strong(expected, true);
}
virtual std::shared_ptr<Schema> schema() const = 0;
virtual ~TpchTableGenerator() = default;
protected:
int64_t seed_ = {0};
std::atomic<bool> done_ = {false};
std::atomic<int64_t> batches_outputted_ = {0};
};
int GetNumDigits(int64_t x) {
// This if statement chain is for MAXIMUM SPEED
// Source:
// https://stackoverflow.com/questions/1068849/how-do-i-determine-the-number-of-digits-of-an-integer-in-c
ARROW_DCHECK(x >= 0);
if (x < 10ll) return 1;
if (x < 100ll) return 2;
if (x < 1000ll) return 3;
if (x < 10000ll) return 4;
if (x < 100000ll) return 5;
if (x < 1000000ll) return 6;
if (x < 10000000ll) return 7;
if (x < 100000000ll) return 8;
if (x < 1000000000ll) return 9;
if (x < 10000000000ll) return 10;
if (x < 100000000000ll) return 11;
if (x < 1000000000000ll) return 12;
if (x < 10000000000000ll) return 13;
if (x < 100000000000000ll) return 14;
if (x < 1000000000000000ll) return 15;
if (x < 10000000000000000ll) return 16;
if (x < 100000000000000000ll) return 17;
if (x < 1000000000000000000ll) return 18;
Unreachable("Positive 64-bit integer should never have more than 18 digits");
return -1;
}
void AppendNumberPaddedToNineDigits(char* out, int64_t x) {
size_t kPad = 9;
out += std::max(kPad, static_cast<size_t>(GetNumDigits(x)));
arrow::internal::detail::FormatAllDigitsLeftPadded(x, kPad, '0', &out);
}
Result<std::shared_ptr<Schema>> SetOutputColumns(
const std::vector<std::string>& columns,
const std::vector<std::shared_ptr<DataType>>& types,
const std::unordered_map<std::string, int>& name_map, std::vector<int>& gen_list) {
gen_list.clear();
std::vector<std::shared_ptr<Field>> fields;
if (columns.empty()) {
fields.resize(name_map.size());
gen_list.resize(name_map.size());
for (auto pair : name_map) {
int col_idx = pair.second;
fields[col_idx] = field(pair.first, types[col_idx]);
gen_list[col_idx] = col_idx;
}
return schema(std::move(fields));
} else {
for (const std::string& col : columns) {
auto entry = name_map.find(col);
if (entry == name_map.end()) return Status::Invalid("Not a valid column name");
int col_idx = static_cast<int>(entry->second);
fields.push_back(field(col, types[col_idx]));
gen_list.push_back(col_idx);
}
return schema(std::move(fields));
}
}
Result<Datum> RandomVString(random::pcg32_fast& rng, int64_t num_rows, int32_t min_length,
int32_t max_length) {
std::uniform_int_distribution<int32_t> length_dist(min_length, max_length);
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> offset_buff,
AllocateBuffer((num_rows + 1) * sizeof(int32_t)));
int32_t* offsets = reinterpret_cast<int32_t*>(offset_buff->mutable_data());
offsets[0] = 0;
for (int64_t i = 1; i <= num_rows; i++) offsets[i] = offsets[i - 1] + length_dist(rng);
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> str_buff,
AllocateBuffer(offsets[num_rows]));
char* str = reinterpret_cast<char*>(str_buff->mutable_data());
// Spec says to pick random alphanumeric characters from a set of at least
// 64 symbols. Now, let's think critically here: 26 letters in the alphabet,
// so 52 total for upper and lower case, and 10 possible digits gives 62
// characters...
// dbgen solves this by including a space and a comma as well, so we'll
// copy that.
const char alpha_numerics[65] =
"0123456789abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ,";
std::uniform_int_distribution<int> char_dist(0, 63);
for (int32_t i = 0; i < offsets[num_rows]; i++) str[i] = alpha_numerics[char_dist(rng)];
ArrayData ad(utf8(), num_rows, {nullptr, std::move(offset_buff), std::move(str_buff)});
return std::move(ad);
}
void GeneratePhoneNumber(char* out, random::pcg32_fast& rng, int32_t country) {
std::uniform_int_distribution<int32_t> three_digit(100, 999);
std::uniform_int_distribution<int32_t> four_digit(1000, 9999);
int32_t country_code = country + 10;
int32_t l1 = three_digit(rng);
int32_t l2 = three_digit(rng);
int32_t l3 = four_digit(rng);
out += 15;
arrow::internal::detail::FormatAllDigits(l3, &out);
*(--out) = '-';
arrow::internal::detail::FormatAllDigits(l2, &out);
*(--out) = '-';
arrow::internal::detail::FormatAllDigits(l1, &out);
*(--out) = '-';
arrow::internal::detail::FormatTwoDigits(country_code, &out);
}
using GenerateColumnFn = std::function<Status(size_t)>;
class PartAndPartSupplierGenerator {
public:
Status Init(size_t num_threads, int64_t batch_size, double scale_factor, int64_t seed) {
if (!inited_) {
inited_ = true;
batch_size_ = batch_size;
scale_factor_ = scale_factor;
thread_local_data_.resize(num_threads);
random::pcg64_fast seed_rng(seed);
for (ThreadLocalData& tld : thread_local_data_) {
constexpr int kMaxNumDistinctStrings = 5;
tld.string_indices.resize(kMaxNumDistinctStrings * batch_size_);
tld.rng.seed(kSeedDist(seed_rng));
}
part_rows_to_generate_ = static_cast<int64_t>(scale_factor_ * 200000);
}
return Status::OK();
}
int64_t part_batches_generated() const { return part_batches_generated_.load(); }
int64_t partsupp_batches_generated() const {
return partsupp_batches_generated_.load();
}
Result<std::shared_ptr<Schema>> SetPartOutputColumns(
const std::vector<std::string>& cols) {
return SetOutputColumns(cols, kPartTypes, kPartNameMap, part_cols_);
}
Result<std::shared_ptr<Schema>> SetPartSuppOutputColumns(
const std::vector<std::string>& cols) {
return SetOutputColumns(cols, kPartsuppTypes, kPartsuppNameMap, partsupp_cols_);
}
Result<std::optional<ExecBatch>> NextPartBatch(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
{
std::lock_guard<std::mutex> lock(part_output_queue_mutex_);
if (!part_output_queue_.empty()) {
ExecBatch batch = std::move(part_output_queue_.front());
part_output_queue_.pop();
return std::move(batch);
} else if (part_rows_generated_ == part_rows_to_generate_) {
return std::nullopt;
} else {
tld.partkey_start = part_rows_generated_;
tld.part_to_generate =
std::min(batch_size_, part_rows_to_generate_ - part_rows_generated_);
part_rows_generated_ += tld.part_to_generate;
int64_t num_ps_batches = PartsuppBatchesToGenerate(thread_index);
part_batches_generated_.fetch_add(1);
partsupp_batches_generated_.fetch_add(num_ps_batches);
ARROW_DCHECK(part_rows_generated_ <= part_rows_to_generate_);
}
}
tld.part.resize(PART::kNumCols);
std::fill(tld.part.begin(), tld.part.end(), Datum());
RETURN_NOT_OK(InitPartsupp(thread_index));
for (int col : part_cols_) RETURN_NOT_OK(kPartGenerators[col](thread_index));
for (int col : partsupp_cols_) RETURN_NOT_OK(kPartsuppGenerators[col](thread_index));
std::vector<Datum> part_result(part_cols_.size());
for (size_t i = 0; i < part_cols_.size(); i++) {
int col_idx = part_cols_[i];
part_result[i] = tld.part[col_idx];
}
if (!partsupp_cols_.empty()) {
std::vector<ExecBatch> partsupp_results;
for (size_t ibatch = 0; ibatch < tld.partsupp.size(); ibatch++) {
std::vector<Datum> partsupp_result(partsupp_cols_.size());
for (size_t icol = 0; icol < partsupp_cols_.size(); icol++) {
int col_idx = partsupp_cols_[icol];
partsupp_result[icol] = tld.partsupp[ibatch][col_idx];
}
ARROW_ASSIGN_OR_RAISE(ExecBatch eb, ExecBatch::Make(std::move(partsupp_result)));
partsupp_results.emplace_back(std::move(eb));
}
{
std::lock_guard<std::mutex> guard(partsupp_output_queue_mutex_);
for (ExecBatch& eb : partsupp_results) {
partsupp_output_queue_.emplace(std::move(eb));
}
}
}
return ExecBatch::Make(std::move(part_result));
}
Result<std::optional<ExecBatch>> NextPartSuppBatch(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
{
std::lock_guard<std::mutex> lock(partsupp_output_queue_mutex_);
if (!partsupp_output_queue_.empty()) {
ExecBatch result = std::move(partsupp_output_queue_.front());
partsupp_output_queue_.pop();
return std::move(result);
}
}
{
std::lock_guard<std::mutex> lock(part_output_queue_mutex_);
if (part_rows_generated_ == part_rows_to_generate_) {
return std::nullopt;
} else {
tld.partkey_start = part_rows_generated_;
tld.part_to_generate =
std::min(batch_size_, part_rows_to_generate_ - part_rows_generated_);
part_rows_generated_ += tld.part_to_generate;
int64_t num_ps_batches = PartsuppBatchesToGenerate(thread_index);
part_batches_generated_.fetch_add(1);
partsupp_batches_generated_.fetch_add(num_ps_batches);
ARROW_DCHECK(part_rows_generated_ <= part_rows_to_generate_);
}
}
tld.part.resize(PART::kNumCols);
std::fill(tld.part.begin(), tld.part.end(), Datum());
RETURN_NOT_OK(InitPartsupp(thread_index));
for (int col : part_cols_) RETURN_NOT_OK(kPartGenerators[col](thread_index));
for (int col : partsupp_cols_) RETURN_NOT_OK(kPartsuppGenerators[col](thread_index));
if (!part_cols_.empty()) {
std::vector<Datum> part_result(part_cols_.size());
for (size_t i = 0; i < part_cols_.size(); i++) {
int col_idx = part_cols_[i];
part_result[i] = tld.part[col_idx];
}
ARROW_ASSIGN_OR_RAISE(ExecBatch part_batch,
ExecBatch::Make(std::move(part_result)));
{
std::lock_guard<std::mutex> lock(part_output_queue_mutex_);
part_output_queue_.emplace(std::move(part_batch));
}
}
std::vector<ExecBatch> partsupp_results;
for (size_t ibatch = 0; ibatch < tld.partsupp.size(); ibatch++) {
std::vector<Datum> partsupp_result(partsupp_cols_.size());
for (size_t icol = 0; icol < partsupp_cols_.size(); icol++) {
int col_idx = partsupp_cols_[icol];
partsupp_result[icol] = tld.partsupp[ibatch][col_idx];
}
ARROW_ASSIGN_OR_RAISE(ExecBatch eb, ExecBatch::Make(std::move(partsupp_result)));
partsupp_results.emplace_back(std::move(eb));
}
// Return the first batch, enqueue the rest.
{
std::lock_guard<std::mutex> lock(partsupp_output_queue_mutex_);
for (size_t i = 1; i < partsupp_results.size(); i++)
partsupp_output_queue_.emplace(std::move(partsupp_results[i]));
}
return std::move(partsupp_results[0]);
}
private:
#define FOR_EACH_PART_COLUMN(F) \
F(P_PARTKEY) \
F(P_NAME) \
F(P_MFGR) \
F(P_BRAND) \
F(P_TYPE) \
F(P_SIZE) \
F(P_CONTAINER) \
F(P_RETAILPRICE) \
F(P_COMMENT)
#define FOR_EACH_PARTSUPP_COLUMN(F) \
F(PS_PARTKEY) \
F(PS_SUPPKEY) \
F(PS_AVAILQTY) \
F(PS_SUPPLYCOST) \
F(PS_COMMENT)
#define MAKE_ENUM(col) col,
struct PART {
enum {
FOR_EACH_PART_COLUMN(MAKE_ENUM) kNumCols,
};
};
struct PARTSUPP {
enum {
FOR_EACH_PARTSUPP_COLUMN(MAKE_ENUM) kNumCols,
};
};
#define MAKE_STRING_MAP(col) {#col, PART::col},
const std::unordered_map<std::string, int> kPartNameMap = {
FOR_EACH_PART_COLUMN(MAKE_STRING_MAP)};
#undef MAKE_STRING_MAP
#define MAKE_STRING_MAP(col) {#col, PARTSUPP::col},
const std::unordered_map<std::string, int> kPartsuppNameMap = {
FOR_EACH_PARTSUPP_COLUMN(MAKE_STRING_MAP)};
#undef MAKE_STRING_MAP
#define MAKE_FN_ARRAY(col) \
[this](size_t thread_index) { return this->col(thread_index); },
std::vector<GenerateColumnFn> kPartGenerators = {FOR_EACH_PART_COLUMN(MAKE_FN_ARRAY)};
std::vector<GenerateColumnFn> kPartsuppGenerators = {
FOR_EACH_PARTSUPP_COLUMN(MAKE_FN_ARRAY)};
#undef MAKE_FN_ARRAY
#undef FOR_EACH_LINEITEM_COLUMN
#undef FOR_EACH_ORDERS_COLUMN
const std::vector<std::shared_ptr<DataType>> kPartTypes = {
int32(), utf8(), fixed_size_binary(25), fixed_size_binary(10),
utf8(), int32(), fixed_size_binary(10), decimal(12, 2),
utf8(),
};
const std::vector<std::shared_ptr<DataType>> kPartsuppTypes = {
int32(), int32(), int32(), decimal(12, 2), utf8(),
};
Status AllocatePartBatch(size_t thread_index, int column) {
ThreadLocalData& tld = thread_local_data_[thread_index];
ARROW_DCHECK(tld.part[column].kind() == Datum::NONE);
int32_t byte_width = kPartTypes[column]->byte_width();
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> buff,
AllocateBuffer(tld.part_to_generate * byte_width));
ArrayData ad(kPartTypes[column], tld.part_to_generate, {nullptr, std::move(buff)});
tld.part[column] = std::move(ad);
return Status::OK();
}
Status P_PARTKEY(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
if (tld.part[PART::P_PARTKEY].kind() == Datum::NONE) {
RETURN_NOT_OK(AllocatePartBatch(thread_index, PART::P_PARTKEY));
int32_t* p_partkey = reinterpret_cast<int32_t*>(
tld.part[PART::P_PARTKEY].array()->buffers[1]->mutable_data());
for (int64_t i = 0; i < tld.part_to_generate; i++) {
p_partkey[i] = static_cast<int32_t>(tld.partkey_start + i + 1);
ARROW_DCHECK(1 <= p_partkey[i] && p_partkey[i] <= part_rows_to_generate_);
}
}
return Status::OK();
}
Status P_NAME(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
if (tld.part[PART::P_NAME].kind() == Datum::NONE) {
std::uniform_int_distribution<int32_t> dist(
0, static_cast<uint8_t>(kNumNameParts - 1));
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> offset_buff,
AllocateBuffer((tld.part_to_generate + 1) * sizeof(int32_t)));
int32_t* offsets = reinterpret_cast<int32_t*>(offset_buff->mutable_data());
offsets[0] = 0;
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
size_t string_length = 0;
for (int ipart = 0; ipart < 5; ipart++) {
uint8_t name_part_index = static_cast<uint8_t>(dist(tld.rng));
tld.string_indices[irow * 5 + ipart] = name_part_index;
string_length += std::strlen(NameParts[name_part_index]);
}
// Add 4 because there is a space between each word (i.e. four spaces)
offsets[irow + 1] = static_cast<int32_t>(offsets[irow] + string_length + 4);
}
// Add an extra byte for the space after in the very last string.
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> string_buffer,
AllocateBuffer(offsets[tld.part_to_generate] + 1));
char* strings = reinterpret_cast<char*>(string_buffer->mutable_data());
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
char* row = strings + offsets[irow];
for (int ipart = 0; ipart < 5; ipart++) {
uint8_t name_part_index = tld.string_indices[irow * 5 + ipart];
const char* part = NameParts[name_part_index];
size_t length = std::strlen(part);
std::memcpy(row, part, length);
row += length;
*row++ = ' ';
}
}
ArrayData ad(kPartTypes[PART::P_NAME], tld.part_to_generate,
{nullptr, std::move(offset_buff), std::move(string_buffer)});
Datum datum(ad);
tld.part[PART::P_NAME] = std::move(datum);
}
return Status::OK();
}
Status P_MFGR(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
if (tld.part[PART::P_MFGR].kind() == Datum::NONE) {
std::uniform_int_distribution<int> dist(1, 5);
const char* manufacturer = "Manufacturer#";
const size_t manufacturer_length = std::strlen(manufacturer);
RETURN_NOT_OK(AllocatePartBatch(thread_index, PART::P_MFGR));
char* p_mfgr = reinterpret_cast<char*>(
tld.part[PART::P_MFGR].array()->buffers[1]->mutable_data());
int32_t byte_width = kPartTypes[PART::P_MFGR]->byte_width();
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
std::strncpy(p_mfgr + byte_width * irow, manufacturer, byte_width);
char mfgr_id = '0' + dist(tld.rng);
*(p_mfgr + byte_width * irow + manufacturer_length) = mfgr_id;
}
}
return Status::OK();
}
Status P_BRAND(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
if (tld.part[PART::P_BRAND].kind() == Datum::NONE) {
RETURN_NOT_OK(P_MFGR(thread_index));
std::uniform_int_distribution<int> dist(1, 5);
const char* brand = "Brand#";
const size_t brand_length = std::strlen(brand);
RETURN_NOT_OK(AllocatePartBatch(thread_index, PART::P_BRAND));
const char* p_mfgr = reinterpret_cast<const char*>(
tld.part[PART::P_MFGR].array()->buffers[1]->data());
char* p_brand = reinterpret_cast<char*>(
tld.part[PART::P_BRAND].array()->buffers[1]->mutable_data());
int32_t byte_width = kPartTypes[PART::P_BRAND]->byte_width();
int32_t mfgr_byte_width = kPartTypes[PART::P_MFGR]->byte_width();
const size_t mfgr_id_offset = std::strlen("Manufacturer#");
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
char* row = p_brand + byte_width * irow;
char mfgr_id = *(p_mfgr + irow * mfgr_byte_width + mfgr_id_offset);
char brand_id = '0' + dist(tld.rng);
std::strncpy(row, brand, byte_width);
*(row + brand_length) = mfgr_id;
*(row + brand_length + 1) = brand_id;
irow += 0;
}
}
return Status::OK();
}
Status P_TYPE(size_t thread_index) {
ThreadLocalData& tld = thread_local_data_[thread_index];
if (tld.part[PART::P_TYPE].kind() == Datum::NONE) {
using D = std::uniform_int_distribution<uint32_t>;
D dists[] = {
D{0, static_cast<uint8_t>(kNumTypes_1 - 1)},
D{0, static_cast<uint8_t>(kNumTypes_2 - 1)},
D{0, static_cast<uint8_t>(kNumTypes_3 - 1)},
};
const char** types[] = {Types_1, Types_2, Types_3};
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> offset_buff,
AllocateBuffer((tld.part_to_generate + 1) * sizeof(int32_t)));
int32_t* offsets = reinterpret_cast<int32_t*>(offset_buff->mutable_data());
offsets[0] = 0;
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
size_t string_length = 0;
for (int ipart = 0; ipart < 3; ipart++) {
uint8_t name_part_index = static_cast<uint8_t>(dists[ipart](tld.rng));
tld.string_indices[irow * 3 + ipart] = name_part_index;
string_length += std::strlen(types[ipart][name_part_index]);
}
offsets[irow + 1] = static_cast<int32_t>(offsets[irow] + string_length);
}
ARROW_ASSIGN_OR_RAISE(std::unique_ptr<Buffer> string_buffer,
AllocateBuffer(offsets[tld.part_to_generate]));
char* strings = reinterpret_cast<char*>(string_buffer->mutable_data());
for (int64_t irow = 0; irow < tld.part_to_generate; irow++) {
char* row = strings + offsets[irow];
for (int ipart = 0; ipart < 3; ipart++) {
uint8_t name_part_index = tld.string_indices[irow * 3 + ipart];
const char* part = types[ipart][name_part_index];
size_t length = std::strlen(part);
std::memcpy(row, part, length);
row += length;
}
}