forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBlock.cpp
More file actions
1246 lines (1000 loc) · 40.2 KB
/
Copy pathBlock.cpp
File metadata and controls
1246 lines (1000 loc) · 40.2 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
#include <AggregateFunctions/IAggregateFunction.h>
#include <Columns/ColumnAggregateFunction.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnConst.h>
#include <Columns/ColumnMap.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnSparse.h>
#include <Columns/ColumnReplicated.h>
#include <Columns/ColumnTuple.h>
#include <Columns/ColumnVariant.h>
#include <Core/Block.h>
#include <Core/UUID.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/IDataType.h>
#include <DataTypes/NestedUtils.h>
#include <DataTypes/Serializations/SerializationInfo.h>
#include <IO/Operators.h>
#include <IO/WriteBufferFromString.h>
#include <base/sort.h>
#include <Common/Exception.h>
#include <Common/FieldVisitorToString.h>
#include <Common/assert_cast.h>
#include <iterator>
#include <ranges>
#include <boost/algorithm/string.hpp>
#include <fmt/ranges.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int POSITION_OUT_OF_BOUND;
extern const int NOT_FOUND_COLUMN_IN_BLOCK;
extern const int SIZES_OF_COLUMNS_DOESNT_MATCH;
extern const int AMBIGUOUS_COLUMN_NAME;
}
template <typename ReturnType, typename... FmtArgs>
static ReturnType onError(int code [[maybe_unused]],
FormatStringHelper<FmtArgs...> fmt_string [[maybe_unused]],
FmtArgs && ...fmt_args [[maybe_unused]])
{
if constexpr (std::is_same_v<ReturnType, void>)
throw Exception(code, std::move(fmt_string), std::forward<FmtArgs>(fmt_args)...);
else
return false;
}
/// Omit Const, Sparse and Replicated and get actual column.
static const IColumn * getActualColumn(const IColumn * column)
{
const IColumn * actual_column = column;
if (const auto * column_const = typeid_cast<const ColumnConst *>(column))
return getActualColumn(&column_const->getDataColumn());
if (const auto * column_replicated = typeid_cast<const ColumnReplicated *>(column))
return getActualColumn(column_replicated->getNestedColumn().get());
if (const auto * column_sparse = typeid_cast<const ColumnSparse *>(column))
return getActualColumn(&column_sparse->getValuesColumn());
return actual_column;
}
/// Compares the structure of two columns. Aggregate-state columns whose functions have the same
/// state representation (e.g. `quantileState` and `quantilesState(0.9)`) are compatible even
/// though their names differ, and this relaxation must apply at any nesting depth: an expression
/// over a `UNION` of such states can wrap them into another column (e.g. into a `Tuple`), and the
/// per-branch headers then differ only by the aggregate function nested inside. For all other
/// columns the comparison is as strict as comparing full column names.
static bool haveCompatibleColumnStructure(const IColumn & actual, const IColumn & expected)
{
/// A `Sparse` column is structurally interchangeable with the full column of the same type it
/// wraps, and this holds at any depth, not only at the top level: one branch can materialize a
/// nested subcolumn (`recursiveRemoveSparse`) while another keeps it sparse. Unwrap `Sparse` on
/// either side independently, mirroring the top-level unwrap in `checkColumnStructure`.
if (const auto * actual_sparse = typeid_cast<const ColumnSparse *>(&actual))
return haveCompatibleColumnStructure(actual_sparse->getValuesColumn(), expected);
if (const auto * expected_sparse = typeid_cast<const ColumnSparse *>(&expected))
return haveCompatibleColumnStructure(actual, expected_sparse->getValuesColumn());
const auto * actual_agg = typeid_cast<const ColumnAggregateFunction *>(&actual);
const auto * expected_agg = typeid_cast<const ColumnAggregateFunction *>(&expected);
if (actual_agg && expected_agg)
return actual_agg->getAggregateFunction()->haveSameStateRepresentation(*expected_agg->getAggregateFunction());
if (typeid(actual) != typeid(expected))
return false;
/// `Variant` is compositional too: its type equality (checked before this point) already
/// fixes the set and the global order of alternatives, so the only thing that can differ
/// between two structurally-equal-typed `Variant` columns is an aggregate state nested
/// inside an alternative, which is exactly what we want to relax. But the local order of
/// the nested variant columns (the order `forEachSubcolumn` iterates them in) is a property
/// of a particular column, not of the type, and `getName` lists the variants in the global
/// order — so compare the alternatives pairwise by global discriminator, like `getName` does.
if (const auto * actual_variant = typeid_cast<const ColumnVariant *>(&actual))
{
const auto & expected_variant = assert_cast<const ColumnVariant &>(expected);
const size_t num_variants = actual_variant->getNumVariants();
if (num_variants != expected_variant.getNumVariants())
return false;
for (size_t global_discr = 0; global_discr < num_variants; ++global_discr)
if (!haveCompatibleColumnStructure(
actual_variant->getVariantByGlobalDiscriminator(global_discr),
expected_variant.getVariantByGlobalDiscriminator(global_discr)))
return false;
return true;
}
/// `Replicated` is compositional too, but only its nested column is structural: the internal
/// indexes column is a variable-width encoding detail (`UInt8` .. `UInt64`, widened lazily)
/// that `getName` does not include, yet `forEachSubcolumn` exposes — so descending into all
/// subcolumns would make the check stricter than the name comparison and reject a valid
/// runtime block against its header. Compare only the nested column, like
/// `ColumnReplicated::structureEquals` does.
if (const auto * actual_replicated = typeid_cast<const ColumnReplicated *>(&actual))
{
const auto & expected_replicated = assert_cast<const ColumnReplicated &>(expected);
return haveCompatibleColumnStructure(*actual_replicated->getNestedColumn(), *expected_replicated.getNestedColumn());
}
/// Descend only into the plain container columns whose name is a pure composition of the
/// nested column names, so that for everything else the comparison stays exactly as strict
/// as comparing full column names. `Dynamic`/`Object` are deliberately left strict because
/// their nested structure is not fixed by the type.
const bool is_compositional = typeid_cast<const ColumnTuple *>(&actual) || typeid_cast<const ColumnArray *>(&actual)
|| typeid_cast<const ColumnMap *>(&actual) || typeid_cast<const ColumnNullable *>(&actual)
|| typeid_cast<const ColumnConst *>(&actual);
if (!is_compositional)
return actual.getName() == expected.getName();
std::vector<const IColumn *> actual_children;
std::vector<const IColumn *> expected_children;
actual.forEachSubcolumn([&](const auto & subcolumn) { actual_children.push_back(subcolumn.get()); });
expected.forEachSubcolumn([&](const auto & subcolumn) { expected_children.push_back(subcolumn.get()); });
if (actual_children.size() != expected_children.size())
return false;
for (size_t i = 0; i < actual_children.size(); ++i)
if (!haveCompatibleColumnStructure(*actual_children[i], *expected_children[i]))
return false;
return true;
}
static bool haveCompatibleConstantValues(const Field & actual, const Field & expected, bool strict_aggregate_states);
static bool haveCompatibleConstantValueVectors(const FieldVector & actual, const FieldVector & expected, bool strict_aggregate_states)
{
if (actual.size() != expected.size())
return false;
for (size_t i = 0; i < actual.size(); ++i)
if (!haveCompatibleConstantValues(actual[i], expected[i], strict_aggregate_states))
return false;
return true;
}
/// Compares two constant values, relaxing only the aggregate-state leaves: the `Field` comparison
/// of aggregate states throws when the aggregate function type names differ, even when the states
/// are compatible by `haveSameStateRepresentation` (which the type and column structure checks
/// have already established at this point). For such leaves compare only the serialized state, so
/// that genuinely different constants — including a differing non-aggregate element next to a
/// compatible aggregate state inside the same `Tuple` — are still reported as a mismatch.
///
/// The relaxation is only sound while the type of a value is fully determined by the column type,
/// which is not the case under `Variant`, `Dynamic` and `JSON` — see `typeCanHideTheValueType`.
/// For those, `strict_aggregate_states` also requires the aggregate function names to be equal
/// (compared field by field, because `Field::operator ==` throws for differing names).
static bool haveCompatibleConstantValues(const Field & actual, const Field & expected, bool strict_aggregate_states)
{
if (actual.getType() != expected.getType())
return false;
switch (actual.getType())
{
case Field::Types::AggregateFunctionState:
{
const auto & actual_state = actual.safeGet<AggregateFunctionStateData>();
const auto & expected_state = expected.safeGet<AggregateFunctionStateData>();
if (strict_aggregate_states && actual_state.name != expected_state.name)
return false;
return actual_state.data == expected_state.data;
}
case Field::Types::Array:
return haveCompatibleConstantValueVectors(actual.safeGet<Array>(), expected.safeGet<Array>(), strict_aggregate_states);
case Field::Types::Tuple:
return haveCompatibleConstantValueVectors(actual.safeGet<Tuple>(), expected.safeGet<Tuple>(), strict_aggregate_states);
case Field::Types::Map:
return haveCompatibleConstantValueVectors(actual.safeGet<Map>(), expected.safeGet<Map>(), strict_aggregate_states);
default:
return actual == expected;
}
}
/// Whether a value of this type is converted to a `Field` that no longer tells which type the
/// value actually has. A `Variant` flattens a row to the `Field` of its active alternative
/// (`ColumnVariant::operator []`) and `DataTypeVariant::equals` allows several aggregate-state
/// alternatives that are compatible by state representation; `Dynamic` and `JSON` similarly store
/// values of types that are not fixed by the column type. Two values on different alternatives can
/// then produce equal `Field`s although the alternative itself is a part of the value and is
/// observable (e.g. by `variantType`), so the aggregate-state relaxation must not apply inside them.
///
/// Only these three types are checked, not `IDataType::hasDynamicSubcolumns`: the latter is also
/// true for a plain `Map`, which merely exposes the `m.keys` and `m.values` virtual subcolumns while
/// the type of every value it holds is still fixed by the declared `Map(K, V)`.
static bool typeCanHideTheValueType(const IDataType & type)
{
if (isVariant(type) || isDynamic(type) || isObject(type))
return true;
bool result = false;
type.forEachChild([&](const IDataType & child)
{
result = result || typeCanHideTheValueType(child);
});
return result;
}
template <typename ReturnType>
static ReturnType checkColumnStructure(const ColumnWithTypeAndName & actual, const ColumnWithTypeAndName & expected,
std::string_view context_description, bool allow_materialize, int code)
{
if (actual.name != expected.name)
return onError<ReturnType>(code, "Block structure mismatch in {} stream: different names of columns:\n{}\n{}",
context_description, actual.dumpStructure(), expected.dumpStructure());
if ((actual.type && !expected.type) || (!actual.type && expected.type)
|| (actual.type && expected.type && !actual.type->equals(*expected.type)))
return onError<ReturnType>(code, "Block structure mismatch in {} stream: different types:\n{}\n{}",
context_description, actual.dumpStructure(), expected.dumpStructure());
if (!actual.column || !expected.column)
return ReturnType(true);
const IColumn * actual_column = actual.column.get();
const IColumn * expected_column = expected.column.get();
/// A Sparse column is structurally equal to the full column of the same type it wraps, and every
/// consumer can process sparse, so it must compare equal to a non-sparse column even in the
/// strict path. Unwrap Sparse on both sides here; Const and Replicated stay strict unless
/// allow_materialize.
if (const auto * actual_sparse = typeid_cast<const ColumnSparse *>(actual_column))
actual_column = &actual_sparse->getValuesColumn();
if (const auto * expected_sparse = typeid_cast<const ColumnSparse *>(expected_column))
expected_column = &expected_sparse->getValuesColumn();
/// If we allow to materialize columns, omit Const and Replicated columns too.
if (allow_materialize)
{
actual_column = getActualColumn(actual_column);
expected_column = getActualColumn(expected_column);
}
if (!haveCompatibleColumnStructure(*actual_column, *expected_column))
{
return onError<ReturnType>(code,
"Block structure mismatch in {} stream: different columns:\n{}\n{}",
context_description,
actual.dumpStructure(),
expected.dumpStructure());
}
if (isColumnConst(*actual.column) && isColumnConst(*expected.column)
&& !actual.column->empty() && !expected.column->empty()) /// don't check values in empty columns
{
Field actual_value = assert_cast<const ColumnConst &>(*actual.column).getField();
Field expected_value = assert_cast<const ColumnConst &>(*expected.column).getField();
/// The types are already checked to be equal at this point.
const bool strict_aggregate_states = actual.type && typeCanHideTheValueType(*actual.type);
if (!haveCompatibleConstantValues(actual_value, expected_value, strict_aggregate_states))
return onError<ReturnType>(code,
"Block structure mismatch in {} stream: different values of constants in column '{}': actual: {}, expected: {}",
context_description,
actual.name,
applyVisitor(FieldVisitorToString(), actual_value),
applyVisitor(FieldVisitorToString(), expected_value));
}
return ReturnType(true);
}
template <typename ReturnType>
static ReturnType checkBlockStructure(const Block & lhs, const Block & rhs, std::string_view context_description, bool allow_materialize)
{
/// It's common to have common SharedHeaders in the pipeline
if (&lhs == &rhs)
return ReturnType(true);
size_t columns = rhs.columns();
if (lhs.columns() != columns)
return onError<ReturnType>(ErrorCodes::LOGICAL_ERROR, "Block structure mismatch in {} stream: different number of columns:\n{}\n{}",
context_description, lhs.dumpStructure(), rhs.dumpStructure());
for (size_t i = 0; i < columns; ++i)
{
const auto & actual = lhs.getByPosition(i);
const auto & expected = rhs.getByPosition(i);
if constexpr (std::is_same_v<ReturnType, bool>)
{
if (!checkColumnStructure<ReturnType>(actual, expected, context_description, allow_materialize, ErrorCodes::LOGICAL_ERROR))
return false;
}
else
checkColumnStructure<ReturnType>(actual, expected, context_description, allow_materialize, ErrorCodes::LOGICAL_ERROR);
}
return ReturnType(true);
}
Block::Block(std::initializer_list<ColumnWithTypeAndName> il) : data{il}
{
initializeIndexByName();
}
Block::Block(const ColumnsWithTypeAndName & data_) : data{data_}
{
initializeIndexByName();
}
Block::Block(ColumnsWithTypeAndName && data_) : data{std::move(data_)}
{
initializeIndexByName();
}
void Block::initializeIndexByName()
{
for (size_t i = 0, size = data.size(); i < size; ++i)
index_by_name.emplace(data[i].name, i);
}
void Block::reserve(size_t count)
{
index_by_name.reserve(count);
data.reserve(count);
}
void Block::insert(size_t position, ColumnWithTypeAndName elem)
{
if (position > data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position out of bound in Block::insert(), max position = {}",
data.size());
if (elem.name.empty())
throw Exception(ErrorCodes::AMBIGUOUS_COLUMN_NAME, "Column name in Block cannot be empty");
auto [new_it, inserted] = index_by_name.emplace(elem.name, position);
if (!inserted)
checkColumnStructure<void>(data[new_it->second], elem,
"(columns with identical name must have identical structure)", true, ErrorCodes::AMBIGUOUS_COLUMN_NAME);
for (auto it = index_by_name.begin(); it != index_by_name.end(); ++it)
{
if (it->second >= position && (!inserted || it != new_it))
++it->second;
}
data.emplace(data.begin() + position, std::move(elem));
}
void Block::insert(ColumnWithTypeAndName elem)
{
if (elem.name.empty())
throw Exception(ErrorCodes::AMBIGUOUS_COLUMN_NAME, "Column name in Block cannot be empty");
auto [it, inserted] = index_by_name.emplace(elem.name, data.size());
if (!inserted)
checkColumnStructure<void>(data[it->second], elem,
"(columns with identical name must have identical structure)", true, ErrorCodes::AMBIGUOUS_COLUMN_NAME);
data.emplace_back(std::move(elem));
}
void Block::insertUnique(ColumnWithTypeAndName elem)
{
if (elem.name.empty())
throw Exception(ErrorCodes::AMBIGUOUS_COLUMN_NAME, "Column name in Block cannot be empty");
if (!index_by_name.contains(elem.name))
insert(std::move(elem));
}
void Block::erase(const std::set<size_t> & positions)
{
if (positions.empty())
return;
if (*positions.rbegin() >= data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position out of bound in Block::erase(), max position = {}",
data.empty() ? 0 : data.size() - 1);
/// Compact `data` in a single pass, dropping the erased positions, then rebuild the name index once.
/// This is O(columns) instead of O(columns * erased) that repeated single-position erases would cost.
size_t next = 0;
auto pos_it = positions.begin();
for (size_t i = 0; i < data.size(); ++i)
{
if (pos_it != positions.end() && *pos_it == i)
{
++pos_it;
continue;
}
if (next != i)
data[next] = std::move(data[i]);
++next;
}
data.resize(next);
index_by_name.clear();
for (size_t i = 0; i < data.size(); ++i)
index_by_name.emplace(data[i].name, i);
}
void Block::erase(size_t position)
{
if (data.empty())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Block is empty");
if (position >= data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position out of bound in Block::erase(), max position = {}",
data.size() - 1);
eraseImpl(position);
}
void Block::eraseImpl(size_t position)
{
data.erase(data.begin() + position);
for (auto it = index_by_name.begin(); it != index_by_name.end();)
{
if (it->second == position)
it = index_by_name.erase(it);
else
{
if (it->second > position)
--it->second;
++it;
}
}
}
void Block::erase(const String & name)
{
auto index_it = index_by_name.find(name);
if (index_it == index_by_name.end())
throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "No such name in Block::erase(): '{}'", name);
eraseImpl(index_it->second);
}
ColumnWithTypeAndName & Block::safeGetByPosition(size_t position)
{
if (data.empty())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Block is empty");
if (position >= data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position {} is out of bound in Block::safeGetByPosition(), "
"max position = {}, there are columns: {}", toString(position), toString(data.size() - 1), dumpNames());
return data[position];
}
const ColumnWithTypeAndName & Block::safeGetByPosition(size_t position) const
{
if (data.empty())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Block is empty");
if (position >= data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position {} is out of bound in Block::safeGetByPosition(), "
"max position = {}, there are columns: {}", toString(position), toString(data.size() - 1), dumpNames());
return data[position];
}
const ColumnWithTypeAndName * Block::findByName(std::string_view name, bool case_insensitive) const
{
const auto pos = findPositionByName(name, case_insensitive);
return pos.has_value() ? &data[pos.value()] : nullptr;
}
const ColumnWithTypeAndName * Block::findByName(const std::string & name, bool case_insensitive) const
{
return findByName(std::string_view{name}, case_insensitive);
}
std::optional<ColumnWithTypeAndName> Block::findSubcolumnByName(const std::string & name) const
{
for (auto [column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name))
{
const auto * column = findByName(column_name, false);
if (!column)
continue;
auto subcolumn_type = column->type->tryGetSubcolumnType(subcolumn_name);
auto subcolumn = column->type->tryGetSubcolumn(subcolumn_name, column->column);
if (subcolumn_type && subcolumn)
return ColumnWithTypeAndName(subcolumn, subcolumn_type, name);
}
return std::nullopt;
}
std::optional<ColumnWithTypeAndName> Block::findColumnOrSubcolumnByName(const std::string & name) const
{
if (const auto * column = findByName(name, false))
return *column;
return findSubcolumnByName(name);
}
const ColumnWithTypeAndName & Block::getByName(const std::string & name, bool case_insensitive) const
{
size_t pos = getPositionByName(name, case_insensitive);
return data[pos];
}
ColumnWithTypeAndName Block::getSubcolumnByName(const std::string & name) const
{
auto result = findSubcolumnByName(name);
if (!result)
throw Exception(
ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK,
"Not found subcolumn {} in block. There are only columns: {}",
name,
dumpNames());
return *result;
}
ColumnWithTypeAndName Block::getColumnOrSubcolumnByName(const std::string & name) const
{
auto result = findColumnOrSubcolumnByName(name);
if (!result)
throw Exception(
ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK,
"Not found column or subcolumn {} in block. There are only columns: {}",
name,
dumpNames());
return *result;
}
bool Block::has(const std::string & name, bool case_insensitive) const
{
return findPositionByName(name, case_insensitive).has_value();
}
std::optional<size_t> Block::findPositionByName(std::string_view name, bool case_insensitive) const
{
if (case_insensitive)
{
auto found = std::find_if(data.begin(), data.end(), [&](const auto & column) { return boost::iequals(column.name, name); });
if (found == data.end())
{
return std::nullopt;
}
return found - data.begin();
}
auto it = index_by_name.find(name);
if (index_by_name.end() == it)
{
return std::nullopt;
}
return it->second;
}
size_t Block::getPositionByName(const std::string & name, bool case_insensitive) const
{
const auto pos = findPositionByName(name, case_insensitive);
if (!pos.has_value())
throw Exception(
ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Not found column {} in block. There are only columns: {}", name, dumpNames());
return pos.value();
}
void Block::checkNumberOfRows(bool allow_null_columns) const
{
ssize_t rows = -1;
for (const auto & elem : data)
{
if (!elem.column && allow_null_columns)
continue;
if (!elem.column)
throw Exception(ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH, "Column {} in block is nullptr, in method checkNumberOfRows." , elem.name);
ssize_t size = elem.column->size();
if (rows == -1)
rows = size;
else if (rows != size)
throw Exception(ErrorCodes::SIZES_OF_COLUMNS_DOESNT_MATCH, "Sizes of columns doesn't match: {}: {}, {}: {}",
data.front().name, rows, elem.name, toString(size));
}
}
size_t Block::rows() const
{
for (const auto & elem : data)
if (elem.column)
return elem.column->size();
return 0;
}
size_t Block::bytes() const
{
size_t res = 0;
for (const auto & elem : data)
if (elem.column)
res += elem.column->byteSize();
return res;
}
size_t Block::allocatedBytes() const
{
size_t res = 0;
for (const auto & elem : data)
if (elem.column)
res += elem.column->allocatedBytes();
return res;
}
std::string Block::dumpNames() const
{
WriteBufferFromOwnString out;
for (auto it = data.begin(); it != data.end(); ++it)
{
if (it != data.begin())
out << ", ";
out << it->name;
}
return out.str();
}
std::string Block::dumpStructure() const
{
WriteBufferFromOwnString out;
for (auto it = data.begin(); it != data.end(); ++it)
{
if (it != data.begin())
out << ", ";
it->dumpStructure(out);
}
return out.str();
}
std::string Block::dumpIndex() const
{
WriteBufferFromOwnString out;
bool first = true;
for (const auto & [name, pos] : index_by_name)
{
if (!first)
out << ", ";
first = false;
out << name << ' ' << pos;
}
return out.str();
}
Block Block::cloneEmpty() const
{
Block res;
res.reserve(data.size());
for (const auto & elem : data)
res.insert(elem.cloneEmpty());
return res;
}
MutableColumns Block::cloneEmptyColumns() const
{
size_t num_columns = data.size();
MutableColumns columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
columns[i] = data[i].column ? data[i].column->cloneEmpty() : data[i].type->createColumn();
return columns;
}
MutableColumns Block::cloneEmptyColumns(const Serializations & serializations) const
{
size_t num_columns = data.size();
MutableColumns columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
columns[i] = data[i].type->createColumn(*serializations[i]);
return columns;
}
Columns Block::getColumns() const
{
size_t num_columns = data.size();
Columns columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
columns[i] = data[i].column;
return columns;
}
MutableColumns Block::mutateColumns()
{
size_t num_columns = data.size();
MutableColumns columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
columns[i] = data[i].column ? IColumn::mutate(std::move(data[i].column)) : data[i].type->createColumn();
return columns;
}
Columns Block::detachColumns()
{
size_t num_columns = data.size();
Columns columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
columns[i] = data[i].column ? std::move(data[i].column) : data[i].type->createColumn();
return columns;
}
void Block::setColumns(MutableColumns && columns)
{
/// TODO: assert if |columns| doesn't match |data|!
size_t num_columns = data.size();
for (size_t i = 0; i < num_columns; ++i)
data[i].column = std::move(columns[i]);
}
void Block::setColumns(const Columns & columns)
{
/// TODO: assert if |columns| doesn't match |data|!
size_t num_columns = data.size();
for (size_t i = 0; i < num_columns; ++i)
data[i].column = columns[i];
}
void Block::setColumn(size_t position, ColumnWithTypeAndName column)
{
if (position >= data.size())
throw Exception(ErrorCodes::POSITION_OUT_OF_BOUND, "Position {} out of bound in Block::setColumn(), max position {}",
position, data.size());
if (data[position].name != column.name)
{
index_by_name.erase(data[position].name);
index_by_name.emplace(column.name, position);
}
data[position] = std::move(column);
}
Block Block::cloneWithColumns(MutableColumns && columns) const
{
Block res;
size_t num_columns = data.size();
if (num_columns != columns.size())
{
auto dump_columns = std::views::transform([](const auto & col) { return col->dumpStructure(); });
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot clone block with columns because block [{}] has {} columns, but {} columns given [{}]",
dumpStructure(), num_columns,
columns.size(), fmt::join(columns | dump_columns, ", "));
}
res.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i)
res.insert({ std::move(columns[i]), data[i].type, data[i].name });
return res;
}
Block Block::cloneWithColumns(const Columns & columns) const
{
Block res;
size_t num_columns = data.size();
if (num_columns != columns.size())
{
auto dump_columns = std::views::transform([](const auto & col) { return col->dumpStructure(); });
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot clone block with columns because block [{}] has {} columns, but {} columns given [{}]",
dumpStructure(), num_columns,
columns.size(), fmt::join(columns | dump_columns, ", "));
}
res.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i)
res.insert({ columns[i], data[i].type, data[i].name });
return res;
}
Block Block::cloneWithoutColumns() const
{
Block res;
size_t num_columns = data.size();
res.reserve(num_columns);
for (size_t i = 0; i < num_columns; ++i)
res.insert({ nullptr, data[i].type, data[i].name });
return res;
}
Block Block::cloneWithCutColumns(size_t start, size_t length) const
{
Block copy = *this;
for (auto & column_to_cut : copy.data)
column_to_cut.column = column_to_cut.column->cut(start, length);
return copy;
}
Block Block::sortColumns() const
{
Block sorted_block;
/// std::unordered_map (index_by_name) cannot be used to guarantee the sort order
VectorWithMemoryTracking<IndexByName::const_iterator> sorted_index_by_name(index_by_name.size());
{
size_t i = 0;
for (auto it = index_by_name.begin(); it != index_by_name.end(); ++it)
sorted_index_by_name[i++] = it;
}
::sort(sorted_index_by_name.begin(), sorted_index_by_name.end(), [](const auto & lhs, const auto & rhs)
{
return lhs->first < rhs->first;
});
for (const auto & it : sorted_index_by_name)
sorted_block.insert(data[it->second]);
return sorted_block;
}
Block Block::shrinkToFit() const
{
Columns new_columns(data.size(), nullptr);
for (size_t i = 0; i < data.size(); ++i)
new_columns[i] = data[i].column->cloneResized(data[i].column->size());
return cloneWithColumns(new_columns);
}
Block Block::compress() const
{
size_t num_columns = data.size();
Columns new_columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
new_columns[i] = data[i].column->compress(/*force_compression=*/false);
return cloneWithColumns(new_columns);
}
Block Block::decompress() const
{
size_t num_columns = data.size();
Columns new_columns(num_columns);
for (size_t i = 0; i < num_columns; ++i)
new_columns[i] = data[i].column->decompress();
return cloneWithColumns(new_columns);
}
const ColumnsWithTypeAndName & Block::getColumnsWithTypeAndName() const
{
return data;
}
NamesAndTypesList Block::getNamesAndTypesList() const
{
NamesAndTypesList res;
for (const auto & elem : data)
res.emplace_back(elem.name, elem.type);
return res;
}
NamesAndTypes Block::getNamesAndTypes() const
{
NamesAndTypes res;
res.reserve(columns());
for (const auto & elem : data)
res.emplace_back(elem.name, elem.type);
return res;
}
Names Block::getNames() const
{
Names res;
res.reserve(columns());
for (const auto & elem : data)
res.push_back(elem.name);
return res;
}
NameSet Block::getNameSet() const
{
NameSet res;
res.reserve(columns());
for (const auto & elem : data)
res.insert(elem.name);
return res;
}
DataTypes Block::getDataTypes() const
{
DataTypes res;
res.reserve(columns());
for (const auto & elem : data)
res.push_back(elem.type);
return res;
}
Names Block::getDataTypeNames() const
{
Names res;
res.reserve(columns());
for (const auto & elem : data)
res.push_back(elem.type->getName());
return res;
}
bool blocksHaveEqualStructure(const Block & lhs, const Block & rhs)
{
return checkBlockStructure<bool>(lhs, rhs, "", false);
}
void assertBlocksHaveEqualStructure(const Block & lhs, const Block & rhs, std::string_view context_description)
{
checkBlockStructure<void>(lhs, rhs, context_description, false);
}