-
Notifications
You must be signed in to change notification settings - Fork 409
/
Join.cpp
2215 lines (1965 loc) · 94.8 KB
/
Join.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 2022 PingCAP, Ltd.
//
// 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.
#include <Columns/ColumnConst.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Common/ColumnsHashing.h>
#include <Common/FailPoint.h>
#include <Common/typeid_cast.h>
#include <Core/ColumnNumbers.h>
#include <DataStreams/IProfilingBlockInputStream.h>
#include <DataStreams/materializeBlock.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypesNumber.h>
#include <Functions/FunctionHelpers.h>
#include <Interpreters/Join.h>
#include <Interpreters/NullableUtils.h>
#include <common/logger_useful.h>
namespace DB
{
namespace FailPoints
{
extern const char random_join_build_failpoint[];
extern const char random_join_prob_failpoint[];
} // namespace FailPoints
namespace ErrorCodes
{
extern const int UNKNOWN_SET_DATA_VARIANT;
extern const int LOGICAL_ERROR;
extern const int SET_SIZE_LIMIT_EXCEEDED;
extern const int TYPE_MISMATCH;
extern const int ILLEGAL_COLUMN;
} // namespace ErrorCodes
namespace
{
/// Do I need to use the hash table maps_*_full, in which we remember whether the row was joined.
bool getFullness(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Right || kind == ASTTableJoin::Kind::Cross_Right || kind == ASTTableJoin::Kind::Full;
}
bool isLeftJoin(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Left || kind == ASTTableJoin::Kind::Cross_Left;
}
bool isRightJoin(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Right || kind == ASTTableJoin::Kind::Cross_Right;
}
bool isInnerJoin(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Inner || kind == ASTTableJoin::Kind::Cross;
}
bool isAntiJoin(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Anti || kind == ASTTableJoin::Kind::Cross_Anti;
}
bool isCrossJoin(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::Cross || kind == ASTTableJoin::Kind::Cross_Left
|| kind == ASTTableJoin::Kind::Cross_Right || kind == ASTTableJoin::Kind::Cross_Anti
|| kind == ASTTableJoin::Kind::Cross_LeftSemi || kind == ASTTableJoin::Kind::Cross_LeftAnti;
}
/// (cartesian) (anti) left semi join.
bool isLeftSemiFamily(ASTTableJoin::Kind kind)
{
return kind == ASTTableJoin::Kind::LeftSemi || kind == ASTTableJoin::Kind::LeftAnti
|| kind == ASTTableJoin::Kind::Cross_LeftSemi || kind == ASTTableJoin::Kind::Cross_LeftAnti;
}
void convertColumnToNullable(ColumnWithTypeAndName & column)
{
column.type = makeNullable(column.type);
if (column.column)
column.column = makeNullable(column.column);
}
ColumnRawPtrs getKeyColumns(const Names & key_names, const Block & block)
{
size_t keys_size = key_names.size();
ColumnRawPtrs key_columns(keys_size);
for (size_t i = 0; i < keys_size; ++i)
{
key_columns[i] = block.getByName(key_names[i]).column.get();
/// We will join only keys, where all components are not NULL.
if (key_columns[i]->isColumnNullable())
key_columns[i] = &static_cast<const ColumnNullable &>(*key_columns[i]).getNestedColumn();
}
return key_columns;
}
} // namespace
const std::string Join::match_helper_prefix = "__left-semi-join-match-helper";
const DataTypePtr Join::match_helper_type = makeNullable(std::make_shared<DataTypeInt8>());
Join::Join(
const Names & key_names_left_,
const Names & key_names_right_,
bool use_nulls_,
const SizeLimits & limits,
ASTTableJoin::Kind kind_,
ASTTableJoin::Strictness strictness_,
const String & req_id,
const TiDB::TiDBCollators & collators_,
const String & left_filter_column_,
const String & right_filter_column_,
const String & other_filter_column_,
const String & other_eq_filter_from_in_column_,
ExpressionActionsPtr other_condition_ptr_,
size_t max_block_size_,
const String & match_helper_name)
: match_helper_name(match_helper_name)
, kind(kind_)
, strictness(strictness_)
, key_names_left(key_names_left_)
, key_names_right(key_names_right_)
, use_nulls(use_nulls_)
, build_concurrency(0)
, build_set_exceeded(false)
, collators(collators_)
, left_filter_column(left_filter_column_)
, right_filter_column(right_filter_column_)
, other_filter_column(other_filter_column_)
, other_eq_filter_from_in_column(other_eq_filter_from_in_column_)
, other_condition_ptr(other_condition_ptr_)
, original_strictness(strictness)
, max_block_size_for_cross_join(max_block_size_)
, build_table_state(BuildTableState::SUCCEED)
, log(Logger::get("Join", req_id))
, limits(limits)
{
if (other_condition_ptr != nullptr)
{
/// if there is other_condition, then should keep all the valid rows during probe stage
if (strictness == ASTTableJoin::Strictness::Any)
{
strictness = ASTTableJoin::Strictness::All;
}
}
if (unlikely(!left_filter_column.empty() && !isLeftJoin(kind)))
throw Exception("Not supported: non left join with left conditions");
if (unlikely(!right_filter_column.empty() && !isRightJoin(kind)))
throw Exception("Not supported: non right join with right conditions");
}
void Join::setBuildTableState(BuildTableState state_)
{
std::lock_guard lk(build_table_mutex);
build_table_state = state_;
build_table_cv.notify_all();
}
Join::Type Join::chooseMethod(const ColumnRawPtrs & key_columns, Sizes & key_sizes)
{
size_t keys_size = key_columns.size();
if (keys_size == 0)
return Type::CROSS;
bool all_fixed = true;
size_t keys_bytes = 0;
key_sizes.resize(keys_size);
for (size_t j = 0; j < keys_size; ++j)
{
if (!key_columns[j]->isFixedAndContiguous())
{
all_fixed = false;
break;
}
key_sizes[j] = key_columns[j]->sizeOfValueIfFixed();
keys_bytes += key_sizes[j];
}
/// If there is one numeric key that fits in 64 bits
if (keys_size == 1 && key_columns[0]->isNumeric())
{
size_t size_of_field = key_columns[0]->sizeOfValueIfFixed();
if (size_of_field == 1)
return Type::key8;
if (size_of_field == 2)
return Type::key16;
if (size_of_field == 4)
return Type::key32;
if (size_of_field == 8)
return Type::key64;
if (size_of_field == 16)
return Type::keys128;
throw Exception("Logical error: numeric column has sizeOfField not in 1, 2, 4, 8, 16.", ErrorCodes::LOGICAL_ERROR);
}
/// If the keys fit in N bits, we will use a hash table for N-bit-packed keys
if (all_fixed && keys_bytes <= 16)
return Type::keys128;
if (all_fixed && keys_bytes <= 32)
return Type::keys256;
/// If there is single string key, use hash table of it's values.
if (keys_size == 1
&& (typeid_cast<const ColumnString *>(key_columns[0])
|| (key_columns[0]->isColumnConst() && typeid_cast<const ColumnString *>(&static_cast<const ColumnConst *>(key_columns[0])->getDataColumn()))))
return Type::key_string;
if (keys_size == 1 && typeid_cast<const ColumnFixedString *>(key_columns[0]))
return Type::key_fixed_string;
/// Otherwise, use serialized values as the key.
return Type::serialized;
}
template <typename Maps>
static void initImpl(Maps & maps, Join::Type type, size_t build_concurrency)
{
switch (type)
{
case Join::Type::EMPTY:
break;
case Join::Type::CROSS:
break;
#define M(TYPE) \
case Join::Type::TYPE: \
maps.TYPE = std::make_unique<typename decltype(maps.TYPE)::element_type>(build_concurrency); \
break;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unknown JOIN keys variant.", ErrorCodes::UNKNOWN_SET_DATA_VARIANT);
}
}
template <typename Maps>
static size_t getTotalRowCountImpl(const Maps & maps, Join::Type type)
{
switch (type)
{
case Join::Type::EMPTY:
return 0;
case Join::Type::CROSS:
return 0;
#define M(NAME) \
case Join::Type::NAME: \
return maps.NAME ? maps.NAME->rowCount() : 0;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unknown JOIN keys variant.", ErrorCodes::UNKNOWN_SET_DATA_VARIANT);
}
}
template <typename Maps>
static size_t getTotalByteCountImpl(const Maps & maps, Join::Type type)
{
switch (type)
{
case Join::Type::EMPTY:
return 0;
case Join::Type::CROSS:
return 0;
#define M(NAME) \
case Join::Type::NAME: \
return maps.NAME ? maps.NAME->getBufferSizeInBytes() : 0;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unknown JOIN keys variant.", ErrorCodes::UNKNOWN_SET_DATA_VARIANT);
}
}
template <Join::Type type, typename Value, typename Mapped>
struct KeyGetterForTypeImpl;
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key8, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt8, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key16, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt16, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key32, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt32, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key64, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodOneNumber<Value, Mapped, UInt64, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key_string, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodString<Value, Mapped, true, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::key_fixed_string, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodFixedString<Value, Mapped, true, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::keys128, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodKeysFixed<Value, UInt128, Mapped, false, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::keys256, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodKeysFixed<Value, UInt256, Mapped, false, false>;
};
template <typename Value, typename Mapped>
struct KeyGetterForTypeImpl<Join::Type::serialized, Value, Mapped>
{
using Type = ColumnsHashing::HashMethodSerialized<Value, Mapped>;
};
template <Join::Type type, typename Data>
struct KeyGetterForType
{
using Value = typename Data::value_type;
using Mapped_t = typename Data::mapped_type;
using Mapped = std::conditional_t<std::is_const_v<Data>, const Mapped_t, Mapped_t>;
using Type = typename KeyGetterForTypeImpl<type, Value, Mapped>::Type;
};
void Join::initMapImpl(Type type_)
{
type = type_;
if (isCrossJoin(kind))
return;
if (!getFullness(kind))
{
if (strictness == ASTTableJoin::Strictness::Any)
initImpl(maps_any, type, getBuildConcurrencyInternal());
else
initImpl(maps_all, type, getBuildConcurrencyInternal());
}
else
{
if (strictness == ASTTableJoin::Strictness::Any)
initImpl(maps_any_full, type, getBuildConcurrencyInternal());
else
initImpl(maps_all_full, type, getBuildConcurrencyInternal());
}
}
size_t Join::getTotalRowCount() const
{
size_t res = 0;
if (type == Type::CROSS)
{
for (const auto & block : blocks)
res += block.rows();
}
else
{
res += getTotalRowCountImpl(maps_any, type);
res += getTotalRowCountImpl(maps_all, type);
res += getTotalRowCountImpl(maps_any_full, type);
res += getTotalRowCountImpl(maps_all_full, type);
}
return res;
}
size_t Join::getTotalByteCount() const
{
size_t res = 0;
if (type == Type::CROSS)
{
for (const auto & block : blocks)
res += block.bytes();
}
else
{
res += getTotalByteCountImpl(maps_any, type);
res += getTotalByteCountImpl(maps_all, type);
res += getTotalByteCountImpl(maps_any_full, type);
res += getTotalByteCountImpl(maps_all_full, type);
for (const auto & pool : pools)
{
/// note the return value might not be accurate since it does not use lock, but should be enough for current usage
res += pool->size();
}
}
return res;
}
void Join::setBuildConcurrencyAndInitPool(size_t build_concurrency_)
{
if (unlikely(build_concurrency > 0))
throw Exception("Logical error: `setBuildConcurrencyAndInitPool` shouldn't be called more than once", ErrorCodes::LOGICAL_ERROR);
build_concurrency = std::max(1, build_concurrency_);
for (size_t i = 0; i < getBuildConcurrencyInternal(); ++i)
pools.emplace_back(std::make_shared<Arena>());
// init for non-joined-streams.
if (getFullness(kind))
{
for (size_t i = 0; i < getNotJoinedStreamConcurrencyInternal(); ++i)
rows_not_inserted_to_map.push_back(std::make_unique<RowRefList>());
}
}
void Join::setSampleBlock(const Block & block)
{
sample_block_with_columns_to_add = materializeBlock(block);
/// Move from `sample_block_with_columns_to_add` key columns to `sample_block_with_keys`, keeping the order.
size_t pos = 0;
while (pos < sample_block_with_columns_to_add.columns())
{
const auto & name = sample_block_with_columns_to_add.getByPosition(pos).name;
if (key_names_right.end() != std::find(key_names_right.begin(), key_names_right.end(), name))
{
sample_block_with_keys.insert(sample_block_with_columns_to_add.getByPosition(pos));
sample_block_with_columns_to_add.erase(pos);
}
else
++pos;
}
size_t num_columns_to_add = sample_block_with_columns_to_add.columns();
for (size_t i = 0; i < num_columns_to_add; ++i)
{
auto & column = sample_block_with_columns_to_add.getByPosition(i);
if (!column.column)
column.column = column.type->createColumn();
}
/// In case of LEFT and FULL joins, if use_nulls, convert joined columns to Nullable.
if (use_nulls && (isLeftJoin(kind) || kind == ASTTableJoin::Kind::Full))
for (size_t i = 0; i < num_columns_to_add; ++i)
convertColumnToNullable(sample_block_with_columns_to_add.getByPosition(i));
if (isLeftSemiFamily(kind))
sample_block_with_columns_to_add.insert(ColumnWithTypeAndName(Join::match_helper_type, match_helper_name));
}
void Join::init(const Block & sample_block, size_t build_concurrency_)
{
std::unique_lock lock(rwlock);
if (unlikely(initialized))
throw Exception("Logical error: Join has been initialized", ErrorCodes::LOGICAL_ERROR);
initialized = true;
setBuildConcurrencyAndInitPool(build_concurrency_);
/// Choose data structure to use for JOIN.
initMapImpl(chooseMethod(getKeyColumns(key_names_right, sample_block), key_sizes));
setSampleBlock(sample_block);
}
namespace
{
void insertRowToList(Join::RowRefList * list, Join::RowRefList * elem, Block * stored_block, size_t index)
{
elem->next = list->next; // NOLINT(clang-analyzer-core.NullDereference)
list->next = elem;
elem->block = stored_block;
elem->row_num = index;
}
/// Inserting an element into a hash table of the form `key -> reference to a string`, which will then be used by JOIN.
template <ASTTableJoin::Strictness STRICTNESS, typename Map, typename KeyGetter>
struct Inserter
{
static void insert(Map & map, const typename Map::key_type & key, Block * stored_block, size_t i, Arena & pool, std::vector<String> & sort_key_containers);
};
template <typename Map, typename KeyGetter>
struct Inserter<ASTTableJoin::Strictness::Any, Map, KeyGetter>
{
static void insert(Map & map, KeyGetter & key_getter, Block * stored_block, size_t i, Arena & pool, std::vector<String> & sort_key_container)
{
auto emplace_result = key_getter.emplaceKey(map, i, pool, sort_key_container);
if (emplace_result.isInserted())
new (&emplace_result.getMapped()) typename Map::mapped_type(stored_block, i);
}
};
template <typename Map, typename KeyGetter>
struct Inserter<ASTTableJoin::Strictness::All, Map, KeyGetter>
{
using MappedType = typename Map::mapped_type;
static void insert(Map & map, KeyGetter & key_getter, Block * stored_block, size_t i, Arena & pool, std::vector<String> & sort_key_container)
{
auto emplace_result = key_getter.emplaceKey(map, i, pool, sort_key_container);
if (emplace_result.isInserted())
new (&emplace_result.getMapped()) typename Map::mapped_type(stored_block, i);
else
{
/** The first element of the list is stored in the value of the hash table, the rest in the pool.
* We will insert each time the element into the second place.
* That is, the former second element, if it was, will be the third, and so on.
*/
auto elem = reinterpret_cast<MappedType *>(pool.alloc(sizeof(MappedType)));
insertRowToList(&emplace_result.getMapped(), elem, stored_block, i);
}
}
};
template <ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map, bool has_null_map>
void NO_INLINE insertFromBlockImplTypeCase(
Map & map,
size_t rows,
const ColumnRawPtrs & key_columns,
const Sizes & key_sizes,
const TiDB::TiDBCollators & collators,
Block * stored_block,
ConstNullMapPtr null_map,
Join::RowRefList * rows_not_inserted_to_map,
size_t,
Arena & pool)
{
KeyGetter key_getter(key_columns, key_sizes, collators);
std::vector<std::string> sort_key_containers;
sort_key_containers.resize(key_columns.size());
for (size_t i = 0; i < rows; ++i)
{
if (has_null_map && (*null_map)[i])
{
if (rows_not_inserted_to_map)
{
/// for right/full out join, need to record the rows not inserted to map
auto * elem = reinterpret_cast<Join::RowRefList *>(pool.alloc(sizeof(Join::RowRefList)));
insertRowToList(rows_not_inserted_to_map, elem, stored_block, i);
}
continue;
}
Inserter<STRICTNESS, typename Map::SegmentType::HashTable, KeyGetter>::insert(map.getSegmentTable(0), key_getter, stored_block, i, pool, sort_key_containers);
}
}
template <ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map, bool has_null_map>
void NO_INLINE insertFromBlockImplTypeCaseWithLock(
Map & map,
size_t rows,
const ColumnRawPtrs & key_columns,
const Sizes & key_sizes,
const TiDB::TiDBCollators & collators,
Block * stored_block,
ConstNullMapPtr null_map,
Join::RowRefList * rows_not_inserted_to_map,
size_t stream_index,
Arena & pool)
{
KeyGetter key_getter(key_columns, key_sizes, collators);
std::vector<std::string> sort_key_containers;
sort_key_containers.resize(key_columns.size());
size_t segment_size = map.getSegmentSize();
/// when inserting with lock, first calculate and save the segment index for each row, then
/// insert the rows segment by segment to avoid too much conflict. This will introduce some overheads:
/// 1. key_getter.getKey will be called twice, here we do not cache key because it can not be cached
/// with relatively low cost(if key is stringRef, just cache a stringRef is meaningless, we need to cache the whole `sort_key_containers`)
/// 2. hash value is calculated twice, maybe we can refine the code to cache the hash value
/// 3. extra memory to store the segment index info
std::vector<std::vector<size_t>> segment_index_info;
if (has_null_map && rows_not_inserted_to_map)
{
segment_index_info.resize(segment_size + 1);
}
else
{
segment_index_info.resize(segment_size);
}
size_t rows_per_seg = rows / segment_index_info.size();
for (auto & segment_index : segment_index_info)
{
segment_index.reserve(rows_per_seg);
}
for (size_t i = 0; i < rows; i++)
{
if (has_null_map && (*null_map)[i])
{
if (rows_not_inserted_to_map)
segment_index_info[segment_index_info.size() - 1].push_back(i);
continue;
}
auto key_holder = key_getter.getKeyHolder(i, &pool, sort_key_containers);
auto key = keyHolderGetKey(key_holder);
size_t segment_index = 0;
size_t hash_value = 0;
if (!ZeroTraits::check(key))
{
hash_value = map.hash(key);
segment_index = hash_value % segment_size;
}
segment_index_info[segment_index].push_back(i);
keyHolderDiscardKey(key_holder);
}
for (size_t insert_index = 0; insert_index < segment_index_info.size(); insert_index++)
{
FAIL_POINT_TRIGGER_EXCEPTION(FailPoints::random_join_build_failpoint);
size_t segment_index = (insert_index + stream_index) % segment_index_info.size();
if (segment_index == segment_size)
{
/// null value
/// here ignore mutex because rows_not_inserted_to_map is privately owned by each stream thread
for (auto index : segment_index_info[segment_index])
{
/// for right/full out join, need to record the rows not inserted to map
auto * elem = reinterpret_cast<Join::RowRefList *>(pool.alloc(sizeof(Join::RowRefList)));
insertRowToList(rows_not_inserted_to_map, elem, stored_block, index);
}
}
else
{
std::lock_guard lk(map.getSegmentMutex(segment_index));
for (size_t i = 0; i < segment_index_info[segment_index].size(); i++)
{
Inserter<STRICTNESS, typename Map::SegmentType::HashTable, KeyGetter>::insert(map.getSegmentTable(segment_index), key_getter, stored_block, segment_index_info[segment_index][i], pool, sort_key_containers);
}
}
}
}
template <ASTTableJoin::Strictness STRICTNESS, typename KeyGetter, typename Map>
void insertFromBlockImplType(
Map & map,
size_t rows,
const ColumnRawPtrs & key_columns,
const Sizes & key_sizes,
const TiDB::TiDBCollators & collators,
Block * stored_block,
ConstNullMapPtr null_map,
Join::RowRefList * rows_not_inserted_to_map,
size_t stream_index,
size_t insert_concurrency,
Arena & pool)
{
if (null_map)
{
if (insert_concurrency > 1)
{
insertFromBlockImplTypeCaseWithLock<STRICTNESS, KeyGetter, Map, true>(map, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map, stream_index, pool);
}
else
{
insertFromBlockImplTypeCase<STRICTNESS, KeyGetter, Map, true>(map, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map, stream_index, pool);
}
}
else
{
if (insert_concurrency > 1)
{
insertFromBlockImplTypeCaseWithLock<STRICTNESS, KeyGetter, Map, false>(map, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map, stream_index, pool);
}
else
{
insertFromBlockImplTypeCase<STRICTNESS, KeyGetter, Map, false>(map, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map, stream_index, pool);
}
}
}
template <ASTTableJoin::Strictness STRICTNESS, typename Maps>
void insertFromBlockImpl(
Join::Type type,
Maps & maps,
size_t rows,
const ColumnRawPtrs & key_columns,
const Sizes & key_sizes,
const TiDB::TiDBCollators & collators,
Block * stored_block,
ConstNullMapPtr null_map,
Join::RowRefList * rows_not_inserted_to_map,
size_t stream_index,
size_t insert_concurrency,
Arena & pool)
{
switch (type)
{
case Join::Type::EMPTY:
break;
case Join::Type::CROSS:
break; /// Do nothing. We have already saved block, and it is enough.
#define M(TYPE) \
case Join::Type::TYPE: \
insertFromBlockImplType<STRICTNESS, typename KeyGetterForType<Join::Type::TYPE, std::remove_reference_t<decltype(*maps.TYPE)>>::Type>( \
*maps.TYPE, \
rows, \
key_columns, \
key_sizes, \
collators, \
stored_block, \
null_map, \
rows_not_inserted_to_map, \
stream_index, \
insert_concurrency, \
pool); \
break;
APPLY_FOR_JOIN_VARIANTS(M)
#undef M
default:
throw Exception("Unknown JOIN keys variant.", ErrorCodes::UNKNOWN_SET_DATA_VARIANT);
}
}
} // namespace
void recordFilteredRows(const Block & block, const String & filter_column, ColumnPtr & null_map_holder, ConstNullMapPtr & null_map)
{
if (filter_column.empty())
return;
auto column = block.getByName(filter_column).column;
if (column->isColumnConst())
column = column->convertToFullColumnIfConst();
if (column->isColumnNullable())
{
const auto & column_nullable = static_cast<const ColumnNullable &>(*column);
if (!null_map_holder)
{
null_map_holder = column_nullable.getNullMapColumnPtr();
}
else
{
MutableColumnPtr mutable_null_map_holder = (*std::move(null_map_holder)).mutate();
PaddedPODArray<UInt8> & mutable_null_map = static_cast<ColumnUInt8 &>(*mutable_null_map_holder).getData();
const PaddedPODArray<UInt8> & other_null_map = column_nullable.getNullMapData();
for (size_t i = 0, size = mutable_null_map.size(); i < size; ++i)
mutable_null_map[i] |= other_null_map[i];
null_map_holder = std::move(mutable_null_map_holder);
}
}
if (!null_map_holder)
{
null_map_holder = ColumnVector<UInt8>::create(column->size(), 0);
}
MutableColumnPtr mutable_null_map_holder = (*std::move(null_map_holder)).mutate();
PaddedPODArray<UInt8> & mutable_null_map = static_cast<ColumnUInt8 &>(*mutable_null_map_holder).getData();
const auto & nested_column = column->isColumnNullable() ? static_cast<const ColumnNullable &>(*column).getNestedColumnPtr() : column;
for (size_t i = 0, size = nested_column->size(); i < size; ++i)
mutable_null_map[i] |= (!nested_column->getInt(i));
null_map_holder = std::move(mutable_null_map_holder);
null_map = &static_cast<const ColumnUInt8 &>(*null_map_holder).getData();
}
bool Join::insertFromBlock(const Block & block)
{
std::unique_lock lock(rwlock);
if (unlikely(!initialized))
throw Exception("Logical error: Join was not initialized", ErrorCodes::LOGICAL_ERROR);
total_input_build_rows += block.rows();
blocks.push_back(block);
Block * stored_block = &blocks.back();
return insertFromBlockInternal(stored_block, 0);
}
/// the block should be valid.
void Join::insertFromBlock(const Block & block, size_t stream_index)
{
std::shared_lock lock(rwlock);
assert(stream_index < getBuildConcurrencyInternal());
assert(stream_index < getNotJoinedStreamConcurrencyInternal());
if (unlikely(!initialized))
throw Exception("Logical error: Join was not initialized", ErrorCodes::LOGICAL_ERROR);
Block * stored_block = nullptr;
{
std::lock_guard lk(blocks_lock);
total_input_build_rows += block.rows();
blocks.push_back(block);
stored_block = &blocks.back();
original_blocks.push_back(block);
}
if (build_set_exceeded.load())
return;
if (!insertFromBlockInternal(stored_block, stream_index))
{
build_set_exceeded.store(true);
}
}
bool Join::insertFromBlockInternal(Block * stored_block, size_t stream_index)
{
size_t keys_size = key_names_right.size();
ColumnRawPtrs key_columns(keys_size);
const Block & block = *stored_block;
/// Rare case, when keys are constant. To avoid code bloat, simply materialize them.
/// Note: this variable can't be removed because it will take smart pointers' lifecycle to the end of this function.
Columns materialized_columns;
/// Memoize key columns to work.
for (size_t i = 0; i < keys_size; ++i)
{
key_columns[i] = block.getByName(key_names_right[i]).column.get();
if (ColumnPtr converted = key_columns[i]->convertToFullColumnIfConst())
{
materialized_columns.emplace_back(converted);
key_columns[i] = materialized_columns.back().get();
}
}
/// We will insert to the map only keys, where all components are not NULL.
ColumnPtr null_map_holder;
ConstNullMapPtr null_map{};
extractNestedColumnsAndNullMap(key_columns, null_map_holder, null_map);
/// reuse null_map to record the filtered rows, the rows contains NULL or does not
/// match the join filter will not insert to the maps
recordFilteredRows(block, right_filter_column, null_map_holder, null_map);
size_t rows = block.rows();
if (getFullness(kind))
{
/** Move the key columns to the beginning of the block.
* This is where NonJoinedBlockInputStream will expect.
*/
size_t key_num = 0;
for (const auto & name : key_names_right)
{
size_t pos = stored_block->getPositionByName(name);
ColumnWithTypeAndName col = stored_block->safeGetByPosition(pos);
stored_block->erase(pos);
stored_block->insert(key_num, std::move(col));
++key_num;
}
}
else
{
/// Remove the key columns from stored_block, as they are not needed.
for (const auto & name : key_names_right)
stored_block->erase(stored_block->getPositionByName(name));
}
size_t size = stored_block->columns();
/// Rare case, when joined columns are constant. To avoid code bloat, simply materialize them.
for (size_t i = 0; i < size; ++i)
{
ColumnPtr col = stored_block->safeGetByPosition(i).column;
if (ColumnPtr converted = col->convertToFullColumnIfConst())
stored_block->safeGetByPosition(i).column = converted;
}
/// In case of LEFT and FULL joins, if use_nulls, convert joined columns to Nullable.
if (use_nulls && (isLeftJoin(kind) || kind == ASTTableJoin::Kind::Full))
{
for (size_t i = getFullness(kind) ? keys_size : 0; i < size; ++i)
{
convertColumnToNullable(stored_block->getByPosition(i));
}
}
if (!isCrossJoin(kind))
{
/// Fill the hash table.
if (!getFullness(kind))
{
if (strictness == ASTTableJoin::Strictness::Any)
insertFromBlockImpl<ASTTableJoin::Strictness::Any>(type, maps_any, rows, key_columns, key_sizes, collators, stored_block, null_map, nullptr, stream_index, getBuildConcurrencyInternal(), *pools[stream_index]);
else
insertFromBlockImpl<ASTTableJoin::Strictness::All>(type, maps_all, rows, key_columns, key_sizes, collators, stored_block, null_map, nullptr, stream_index, getBuildConcurrencyInternal(), *pools[stream_index]);
}
else
{
if (strictness == ASTTableJoin::Strictness::Any)
insertFromBlockImpl<ASTTableJoin::Strictness::Any>(type, maps_any_full, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map[stream_index].get(), stream_index, getBuildConcurrencyInternal(), *pools[stream_index]);
else
insertFromBlockImpl<ASTTableJoin::Strictness::All>(type, maps_all_full, rows, key_columns, key_sizes, collators, stored_block, null_map, rows_not_inserted_to_map[stream_index].get(), stream_index, getBuildConcurrencyInternal(), *pools[stream_index]);
}
}
return limits.check(getTotalRowCount(), getTotalByteCount(), "JOIN", ErrorCodes::SET_SIZE_LIMIT_EXCEEDED);
}
namespace
{
template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename Map>
struct Adder;
template <typename Map>
struct Adder<ASTTableJoin::Kind::Left, ASTTableJoin::Strictness::Any, Map>
{
static void addFound(const typename Map::SegmentType::HashTable::ConstLookupResult & it, size_t num_columns_to_add, MutableColumns & added_columns, size_t /*i*/, IColumn::Filter * /*filter*/, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/, const std::vector<size_t> & right_indexes)
{
for (size_t j = 0; j < num_columns_to_add; ++j)
added_columns[j]->insertFrom(*it->getMapped().block->getByPosition(right_indexes[j]).column.get(), it->getMapped().row_num);
}
static void addNotFound(size_t num_columns_to_add, MutableColumns & added_columns, size_t /*i*/, IColumn::Filter * /*filter*/, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/)
{
for (size_t j = 0; j < num_columns_to_add; ++j)
added_columns[j]->insertDefault();
}
};
template <typename Map>
struct Adder<ASTTableJoin::Kind::Inner, ASTTableJoin::Strictness::Any, Map>
{
static void addFound(const typename Map::SegmentType::HashTable::ConstLookupResult & it, size_t num_columns_to_add, MutableColumns & added_columns, size_t i, IColumn::Filter * filter, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/, const std::vector<size_t> & right_indexes)
{
(*filter)[i] = 1;
for (size_t j = 0; j < num_columns_to_add; ++j)
added_columns[j]->insertFrom(*it->getMapped().block->getByPosition(right_indexes[j]).column.get(), it->getMapped().row_num);
}
static void addNotFound(size_t /*num_columns_to_add*/, MutableColumns & /*added_columns*/, size_t i, IColumn::Filter * filter, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/)
{
(*filter)[i] = 0;
}
};
template <typename Map>
struct Adder<ASTTableJoin::Kind::Anti, ASTTableJoin::Strictness::Any, Map>
{
static void addFound(const typename Map::SegmentType::HashTable::ConstLookupResult & /*it*/, size_t /*num_columns_to_add*/, MutableColumns & /*added_columns*/, size_t i, IColumn::Filter * filter, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/, const std::vector<size_t> & /*right_indexes*/)
{
(*filter)[i] = 0;
}
static void addNotFound(size_t num_columns_to_add, MutableColumns & added_columns, size_t i, IColumn::Filter * filter, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/)
{
(*filter)[i] = 1;
for (size_t j = 0; j < num_columns_to_add; ++j)
added_columns[j]->insertDefault();
}
};
template <typename Map>
struct Adder<ASTTableJoin::Kind::LeftSemi, ASTTableJoin::Strictness::Any, Map>
{
static void addFound(const typename Map::SegmentType::HashTable::ConstLookupResult & /*it*/, size_t num_columns_to_add, MutableColumns & added_columns, size_t /*i*/, IColumn::Filter * /*filter*/, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/, const std::vector<size_t> & /*right_indexes*/)
{
for (size_t j = 0; j < num_columns_to_add - 1; ++j)
added_columns[j]->insertDefault();
added_columns[num_columns_to_add - 1]->insert(FIELD_INT8_1);
}
static void addNotFound(size_t num_columns_to_add, MutableColumns & added_columns, size_t /*i*/, IColumn::Filter * /*filter*/, IColumn::Offset & /*current_offset*/, IColumn::Offsets * /*offsets*/)
{
for (size_t j = 0; j < num_columns_to_add - 1; ++j)
added_columns[j]->insertDefault();
added_columns[num_columns_to_add - 1]->insert(FIELD_INT8_0);
}
};
template <typename Map>
struct Adder<ASTTableJoin::Kind::LeftSemi, ASTTableJoin::Strictness::All, Map>
{
static void addFound(const typename Map::SegmentType::HashTable::ConstLookupResult & it, size_t num_columns_to_add, MutableColumns & added_columns, size_t i, IColumn::Filter * /*filter*/, IColumn::Offset & current_offset, IColumn::Offsets * offsets, const std::vector<size_t> & right_indexes)
{
for (auto current = &static_cast<const typename Map::mapped_type::Base_t &>(it->getMapped()); current != nullptr; current = current->next)
{
for (size_t j = 0; j < num_columns_to_add - 1; ++j)
added_columns[j]->insertFrom(*current->block->getByPosition(right_indexes[j]).column.get(), current->row_num);
++current_offset;