-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathNestedUtils.cpp
More file actions
852 lines (725 loc) · 32.4 KB
/
Copy pathNestedUtils.cpp
File metadata and controls
852 lines (725 loc) · 32.4 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
#include <algorithm>
#include <cstring>
#include <memory>
#include <Columns/IColumn.h>
#include <Common/StringUtils.h>
#include <Common/assert_cast.h>
#include <Common/typeid_cast.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeMap.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/NestedUtils.h>
#include <DataTypes/DataTypeNested.h>
#include <Columns/ColumnArray.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnsCommon.h>
#include <Columns/ColumnTuple.h>
#include <Columns/ColumnConst.h>
#include <Parsers/IAST.h>
#include <Storages/ColumnsDescription.h>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_COLUMN;
extern const int LOGICAL_ERROR;
extern const int SIZES_OF_ARRAYS_DONT_MATCH;
extern const int BAD_ARGUMENTS;
}
namespace Nested
{
std::string concatenateName(const std::string & nested_table_name, const std::string & nested_field_name)
{
if (nested_table_name.empty())
return nested_field_name;
if (nested_field_name.empty())
return nested_table_name;
return nested_table_name + "." + nested_field_name;
}
/** Name can be treated as compound if it contains dot (.) in the middle.
*/
std::pair<std::string, std::string> splitName(const std::string & name, bool reverse)
{
auto res = splitName(std::string_view(name), reverse);
return {std::string(res.first), std::string(res.second)};
}
std::pair<std::string_view, std::string_view> splitName(std::string_view name, bool reverse)
{
auto idx = (reverse ? name.find_last_of('.') : name.find_first_of('.'));
if (idx == std::string::npos || idx == 0 || idx + 1 == name.size())
return {name, {}};
return {name.substr(0, idx), name.substr(idx + 1)};
}
std::vector<std::pair<std::string_view, std::string_view>> getAllColumnAndSubcolumnPairs(std::string_view name)
{
std::vector<std::pair<std::string_view, std::string_view>> pairs;
auto idx = name.find_first_of('.');
while (idx != std::string::npos)
{
std::string_view column_name = name.substr(0, idx);
std::string_view subcolumn_name = name.substr(idx + 1);
if (!column_name.empty() && !subcolumn_name.empty())
pairs.emplace_back(column_name, subcolumn_name);
idx = name.find_first_of('.', idx + 1);
}
return pairs;
}
std::pair<std::string_view, std::string_view> getColumnAndSubcolumnPair(std::string_view name, const NameSet & storage_columns)
{
for (auto [storage_column_name, subcolumn_name] : Nested::getAllColumnAndSubcolumnPairs(name))
{
if (storage_columns.contains(String(storage_column_name)))
return {storage_column_name, subcolumn_name};
}
throw Exception(
ErrorCodes::BAD_ARGUMENTS,
"Column or subcolumn '{}' is not found, there are only columns: {}",
name,
boost::join(storage_columns, ", "));
}
std::string_view getColumnFromSubcolumn(std::string_view name, const NameSet & storage_columns)
{
return getColumnAndSubcolumnPair(name, storage_columns).first;
}
std::optional<String> tryGetColumnNameInStorage(const String & name, const NameSet & storage_columns)
{
if (storage_columns.contains(name))
return name;
auto subcolumn_pairs = Nested::getAllColumnAndSubcolumnPairs(name);
for (const auto & [column_name, _] : subcolumn_pairs)
{
if (storage_columns.contains(String(column_name)))
return String(column_name);
}
return std::nullopt;
}
std::string extractTableName(const std::string & nested_name)
{
auto split = splitName(nested_name);
return split.first;
}
ColumnWithTypeAndName unwrapNullableTuple(const ColumnWithTypeAndName & column)
{
const auto * type_nullable = typeid_cast<const DataTypeNullable *>(column.type.get());
if (!type_nullable)
return column;
const auto * tuple_type = typeid_cast<const DataTypeTuple *>(type_nullable->getNestedType().get());
if (!tuple_type)
return column;
const auto & col_nullable = assert_cast<const ColumnNullable &>(*column.column);
const auto & null_map_data = col_nullable.getNullMapData();
bool has_nulls = !memoryIsZero(null_map_data.data(), 0, null_map_data.size());
if (!has_nulls)
{
/// No actual nulls — just strip the Nullable wrapper.
return {col_nullable.getNestedColumnPtr(), type_nullable->getNestedType(), column.name};
}
/// Propagate the struct null map to each Tuple element.
const auto & inner_tuple = assert_cast<const ColumnTuple &>(col_nullable.getNestedColumn());
const auto & null_map_ptr = col_nullable.getNullMapColumnPtr();
Columns new_elements;
DataTypes new_types;
for (size_t i = 0; i < tuple_type->getElements().size(); ++i)
{
auto elem_col = inner_tuple.getColumnPtr(i);
auto elem_type = tuple_type->getElement(i);
if (elem_type->isNullable())
{
/// Element already Nullable — merge null maps (struct null OR element null).
const auto & existing = assert_cast<const ColumnNullable &>(*elem_col);
auto merged = ColumnUInt8::create(null_map_ptr->size());
const auto & s = assert_cast<const ColumnUInt8 &>(*null_map_ptr).getData();
const auto & e = existing.getNullMapData();
auto & m = merged->getData();
for (size_t j = 0; j < s.size(); ++j)
m[j] = s[j] | e[j];
new_elements.push_back(ColumnNullable::create(existing.getNestedColumnPtr(), std::move(merged)));
new_types.push_back(elem_type);
}
else if (elem_type->canBeInsideNullable())
{
new_elements.push_back(ColumnNullable::create(elem_col, null_map_ptr));
new_types.push_back(std::make_shared<DataTypeNullable>(elem_type));
}
else
{
/// Array, Map, etc. — replace values at null positions with type defaults.
const auto & nm = col_nullable.getNullMapData();
auto mutable_col = elem_col->cloneEmpty();
for (size_t j = 0; j < elem_col->size(); ++j)
{
if (nm[j])
mutable_col->insertDefault();
else
mutable_col->insertFrom(*elem_col, j);
}
new_elements.push_back(std::move(mutable_col));
new_types.push_back(elem_type);
}
}
auto result_type = tuple_type->hasExplicitNames() ? std::make_shared<DataTypeTuple>(std::move(new_types), tuple_type->getElementNames())
: std::make_shared<DataTypeTuple>(std::move(new_types));
return {ColumnTuple::create(std::move(new_elements)), result_type, column.name};
}
static Block flattenImpl(const Block & block, bool flatten_named_tuple)
{
Block res;
for (const auto & elem : block)
{
if (isNested(elem.type))
{
const DataTypeArray * type_arr = assert_cast<const DataTypeArray *>(elem.type.get());
const DataTypeTuple * type_tuple = assert_cast<const DataTypeTuple *>(type_arr->getNestedType().get());
if (type_tuple->hasExplicitNames())
{
const DataTypes & element_types = type_tuple->getElements();
const Strings & names = type_tuple->getElementNames();
size_t tuple_size = element_types.size();
bool is_const = isColumnConst(*elem.column);
const ColumnArray * column_array = nullptr;
if (is_const)
column_array = typeid_cast<const ColumnArray *>(&assert_cast<const ColumnConst &>(*elem.column).getDataColumn());
else
column_array = typeid_cast<const ColumnArray *>(elem.column.get());
const ColumnPtr & column_offsets = column_array->getOffsetsPtr();
const ColumnTuple & column_tuple = typeid_cast<const ColumnTuple &>(column_array->getData());
const auto & element_columns = column_tuple.getColumns();
for (size_t i = 0; i < tuple_size; ++i)
{
String nested_name = concatenateName(elem.name, names[i]);
ColumnPtr column_array_of_element = ColumnArray::create(element_columns[i], column_offsets);
res.insert(ColumnWithTypeAndName(
is_const
? ColumnConst::create(column_array_of_element, block.rows())
: column_array_of_element,
std::make_shared<DataTypeArray>(element_types[i]),
nested_name));
}
}
else
res.insert(elem);
}
else if (const DataTypeTuple * type_tuple = typeid_cast<const DataTypeTuple *>(elem.type.get()); type_tuple && flatten_named_tuple)
{
if (type_tuple->hasExplicitNames())
{
const DataTypes & element_types = type_tuple->getElements();
const Strings & names = type_tuple->getElementNames();
const ColumnTuple * column_tuple = nullptr;
if (isColumnConst(*elem.column))
column_tuple = typeid_cast<const ColumnTuple *>(&assert_cast<const ColumnConst &>(*elem.column).getDataColumn());
else
column_tuple = typeid_cast<const ColumnTuple *>(elem.column.get());
size_t tuple_size = column_tuple->tupleSize();
for (size_t i = 0; i < tuple_size; ++i)
{
const auto & element_column = column_tuple->getColumn(i);
String nested_name = concatenateName(elem.name, names[i]);
res.insert(ColumnWithTypeAndName(element_column.getPtr(), element_types[i], nested_name));
}
}
else
res.insert(elem);
}
else
res.insert(elem);
}
return res;
}
Block flatten(const Block & block)
{
return flattenImpl(block, true);
}
Block flattenNested(const Block & block)
{
return flattenImpl(block, false);
}
const DataTypeTuple * tryGetFlattenableTuple(const DataTypePtr & type)
{
const auto * tuple_type = typeid_cast<const DataTypeTuple *>(type.get());
if (tuple_type && !tuple_type->getElements().empty() && !type->hasCustomName())
return tuple_type;
return nullptr;
}
/// Recursively flattens one (column, type) into its leaf columns, calling
/// `emit_leaf(column, type, name, ancestors)` once per leaf. A leaf is anything
/// `tryGetFlattenableTuple` does not expand (a non-tuple, or an empty/custom-named tuple);
/// flattenable tuples are descended into. `name` is the leaf's full dotted path; `ancestors`
/// are the tuple paths it descends from (the root column plus every intermediate tuple node).
///
/// Example — a column `t` of type `Tuple(a UInt64, inner Tuple(c UInt64, d UInt64))`, called with
/// name_prefix = "t", emits three leaves:
/// emit_leaf(col, UInt64, "t.a", ["t"])
/// emit_leaf(col, UInt64, "t.inner.c", ["t", "t.inner"])
/// emit_leaf(col, UInt64, "t.inner.d", ["t", "t.inner"])
///
/// Names and ancestors are built from real element boundaries, so an element whose own name
/// contains a dot (e.g. `p.x` in tuple `t`) is not a problem and gives the single leaf `t.p.x`
/// with the sole ancestor `t`, never the unrelated path `t.p`.
template <typename LeafCallback>
static void flattenTupleRecursiveImpl(
const ColumnPtr & column,
const DataTypePtr & data_type,
LeafCallback && emit_leaf,
const String & name_prefix,
const Strings & ancestors)
{
const auto * tuple_type = tryGetFlattenableTuple(data_type);
if (!tuple_type)
{
emit_leaf(column, data_type, name_prefix, ancestors);
return;
}
/// If the column is ColumnConst, expand it to a full column first,
/// so that all leaf columns are always non-const after flattening.
ColumnPtr materialized_column = column->convertToFullColumnIfConst();
const auto * column_tuple = assert_cast<const ColumnTuple *>(materialized_column.get());
const DataTypes & element_types = tuple_type->getElements();
const Strings & element_names = tuple_type->getElementNames();
const auto & sub_columns = column_tuple->getColumns();
/// `name_prefix` is empty only on the column-only flattening path (flattenTupleColumnsRecursive),
/// where leaf names and ancestors are unused, so skip building them there.
const bool build_metadata = !name_prefix.empty();
Strings element_ancestors = ancestors;
if (build_metadata)
element_ancestors.push_back(name_prefix);
for (size_t i = 0; i < element_types.size(); ++i)
{
String element_name = build_metadata ? concatenateName(name_prefix, element_names[i]) : String{};
flattenTupleRecursiveImpl(sub_columns[i], element_types[i], emit_leaf, element_name, element_ancestors);
}
}
Block flattenTupleRecursive(const Block & block, std::vector<Strings> * flattened_ancestors)
{
Block result;
if (flattened_ancestors)
flattened_ancestors->clear();
for (const auto & elem : block)
{
flattenTupleRecursiveImpl(
elem.column, elem.type,
[&](const ColumnPtr & col, const DataTypePtr & type, const String & name, const Strings & ancestors)
{
result.insert(ColumnWithTypeAndName(col, type, name));
if (flattened_ancestors)
flattened_ancestors->push_back(ancestors);
},
elem.name, {});
}
return result;
}
void flattenTupleLeafNames(const String & name, const DataTypePtr & type, Names & out)
{
/// Mirrors the name generation of `flattenTupleRecursiveImpl`: descend only into flattenable
/// tuples, joining each element name onto the prefix, and emit non-tuple types as leaves.
const auto * tuple_type = tryGetFlattenableTuple(type);
if (!tuple_type)
{
out.push_back(name);
return;
}
const DataTypes & element_types = tuple_type->getElements();
const Strings & element_names = tuple_type->getElementNames();
for (size_t i = 0; i < element_types.size(); ++i)
flattenTupleLeafNames(concatenateName(name, element_names[i]), element_types[i], out);
}
/// Flatten tuple columns: input a vector of columns, return a new vector with all tuples expanded
/// All tuples are flattened recursively
Columns flattenTupleColumnsRecursive(const Block & header, const Columns & columns)
{
if (header.columns() != columns.size())
{
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Header columns count ({}) does not match columns count ({}) in flattenTupleColumns",
header.columns(),
columns.size());
}
Columns result;
result.reserve(columns.size()); /// Lower bound: every column flattens to at least one leaf.
for (size_t i = 0; i < columns.size(); ++i)
{
const auto & header_col = header.getByPosition(i);
flattenTupleRecursiveImpl(
columns[i], header_col.type,
[&result](const ColumnPtr & col, const DataTypePtr &, const String &, const Strings &)
{
result.push_back(col);
},
{}, {});
}
return result;
}
static ColumnPtr reconstructTupleColumnImpl(const DataTypePtr & data_type, const Columns & flattened_columns, size_t & flattened_idx)
{
if (const auto * tuple_type = tryGetFlattenableTuple(data_type))
{
const auto & element_types = tuple_type->getElements();
Columns tuple_columns;
tuple_columns.reserve(element_types.size());
for (const auto & element_type : element_types)
tuple_columns.push_back(reconstructTupleColumnImpl(element_type, flattened_columns, flattened_idx));
return ColumnTuple::create(tuple_columns);
}
/// For non-tuple types, take as-is from flattened columns
if (flattened_idx >= flattened_columns.size())
{
throw Exception(ErrorCodes::LOGICAL_ERROR, "flattened_idx out of range in reconstructTupleColumns");
}
return flattened_columns[flattened_idx++];
}
/// Reconstruct tuple columns: input header and flattened columns, return a new vector with tuples reconstructed
Columns reconstructTupleColumnsRecursive(const Block & header, const Columns & flattened_columns)
{
Columns result;
result.reserve(header.columns());
size_t flattened_idx = 0;
for (size_t i = 0; i < header.columns(); ++i)
{
const auto & header_col = header.getByPosition(i);
result.push_back(reconstructTupleColumnImpl(header_col.type, flattened_columns, flattened_idx));
}
if (flattened_idx != flattened_columns.size())
{
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"reconstructTupleColumnsRecursive: consumed {} flattened columns, but total flattened columns count is {}",
flattened_idx,
flattened_columns.size());
}
return result;
}
namespace
{
using NameToDataType = std::map<String, DataTypePtr>;
NameToDataType getSubcolumnsOfNested(const NamesAndTypesList & names_and_types)
{
std::unordered_map<String, NamesAndTypesList> nested;
/// A subcolumn entry's `type_in_storage` is the type in metadata, while a plain entry carries the
/// type its caller resolved, which for a part being read is the part's own (possibly older) type.
std::unordered_map<String, NameSet> contributed_by_subcolumn;
for (const auto & name_type : names_and_types)
{
/// Group by the column in storage so a subcolumn contributes its member and never itself:
/// `c2.null` as an element name would build an invalid Nested type.
auto name_in_storage = name_type.getNameInStorage();
const auto & type_in_storage = name_type.getTypeInStorage();
const auto * type_arr = typeid_cast<const DataTypeArray *>(type_in_storage.get());
/// Ignore true Nested type, but try to unite flatten arrays to Nested type.
if (!isNested(type_in_storage) && type_arr)
{
auto split = splitName(name_in_storage);
if (split.second.empty())
continue;
auto & elems = nested[split.first];
/// A member is contributed once even if both it and its subcolumns are requested.
if (!elems.contains(split.second))
{
elems.emplace_back(split.second, type_arr->getNestedType());
if (name_type.isSubcolumn())
contributed_by_subcolumn[split.first].insert(split.second);
}
/// A plain entry replaces a subcolumn entry's contribution, never the other way round, so
/// the element type describes the same data the columns in this list carry.
else if (!name_type.isSubcolumn() && contributed_by_subcolumn[split.first].erase(split.second))
{
for (auto & elem : elems)
{
if (elem.name == split.second)
{
elem = NameAndTypePair{split.second, type_arr->getNestedType()};
break;
}
}
}
}
}
std::map<String, DataTypePtr> nested_types;
for (const auto & [name, elems] : nested)
nested_types.emplace(name, createNested(elems.getTypes(), elems.getNames()));
return nested_types;
}
}
NamesAndTypesList collect(const NamesAndTypesList & names_and_types)
{
NamesAndTypesList res;
auto nested_types = getSubcolumnsOfNested(names_and_types);
for (const auto & name_type : names_and_types)
{
auto split = splitName(name_type.name);
if (!isArray(name_type.type) || split.second.empty() || !nested_types.contains(split.first))
res.push_back(name_type);
}
for (const auto & name_type : nested_types)
res.emplace_back(name_type.first, name_type.second);
return res;
}
NamesAndTypesList convertToSubcolumns(const NamesAndTypesList & names_and_types)
{
auto nested_types = getSubcolumnsOfNested(names_and_types);
auto res = names_and_types;
for (auto & name_type : res)
{
if (!isArray(name_type.type))
continue;
auto split = splitName(name_type.name);
if (split.second.empty())
continue;
if (name_type.isSubcolumn())
{
/// If this is a subcolumn (e.g. `c0.c2.null` — subcolumn `null` of `c0.c2`)
/// and its parent column is part of a Nested group, remap it to be a subcolumn
/// of the Nested type (e.g. subcolumn `c2.null` of Nested `c0`).
/// This ensures the Nested serialization is used, which handles shared offsets correctly.
auto name_in_storage = name_type.getNameInStorage();
auto storage_split = splitName(name_in_storage);
if (!storage_split.second.empty())
{
auto it = nested_types.find(storage_split.first);
if (it != nested_types.end())
{
auto new_subcolumn = concatenateName(storage_split.second, name_type.getSubcolumnName());
if (auto subcolumn_type = it->second->tryGetSubcolumnType(new_subcolumn))
name_type = NameAndTypePair{storage_split.first, new_subcolumn, it->second, subcolumn_type};
}
}
continue;
}
auto it = nested_types.find(split.first);
if (it != nested_types.end())
name_type = NameAndTypePair{split.first, split.second, it->second, it->second->getSubcolumnType(split.second)};
}
return res;
}
void validateArraySizes(const Block & block)
{
/// Nested prefix -> position of first column in block.
std::map<std::string, size_t> nested;
for (size_t i = 0, size = block.columns(); i < size; ++i)
{
const auto & elem = block.getByPosition(i);
if (isArray(elem.type))
{
if (!typeid_cast<const ColumnArray *>(elem.column.get()))
throw Exception(ErrorCodes::ILLEGAL_COLUMN,
"Column with Array type is not represented by ColumnArray column: {}",
elem.column->dumpStructure());
auto split = splitName(elem.name);
/// Is it really a column of Nested data structure.
if (!split.second.empty())
{
auto [it, inserted] = nested.emplace(split.first, i);
/// It's not the first column of Nested data structure.
if (!inserted)
{
const ColumnArray & first_array_column = assert_cast<const ColumnArray &>(*block.getByPosition(it->second).column);
const ColumnArray & another_array_column = assert_cast<const ColumnArray &>(*elem.column);
if (!first_array_column.hasEqualOffsets(another_array_column))
throw Exception(ErrorCodes::SIZES_OF_ARRAYS_DONT_MATCH,
"Elements '{}' and '{}' "
"of Nested data structure '{}' (Array columns) have different array sizes.",
block.getByPosition(it->second).name, elem.name, split.first);
}
}
}
}
}
std::unordered_set<String> getAllTableNames(const Block & block, bool to_lower_case)
{
std::unordered_set<String> nested_table_names;
for (const auto & name : block.getNames())
{
auto nested_table_name = Nested::extractTableName(name);
if (to_lower_case)
boost::to_lower(nested_table_name);
if (!nested_table_name.empty())
nested_table_names.insert(std::move(nested_table_name));
}
return nested_table_names;
}
Names getAllNestedColumnsForTable(const Block & block, const std::string & table_name)
{
Names names;
for (const auto & name: block.getNames())
{
if (extractTableName(name) == table_name)
names.push_back(name);
}
return names;
}
bool isSubcolumnOfNested(const String & column_name, const ColumnsDescription & columns)
{
auto nested_subcolumn = columns.tryGetColumnOrSubcolumn(GetColumnsOptions::AllPhysical, column_name);
return nested_subcolumn && isNested(nested_subcolumn->getTypeInStorage()) && nested_subcolumn->isSubcolumn() && isArray(nested_subcolumn->type);
}
}
NestedColumnExtractHelper::NestedColumnExtractHelper(const Block & block_, bool case_insentive_)
: block(block_)
, case_insentive(case_insentive_)
{}
const NestedColumnExtractHelper::Subcolumns & NestedColumnExtractHelper::subcolumnsOf(const ColumnWithTypeAndName & root)
{
auto [it, inserted] = subcolumns_by_root.try_emplace(root.name);
auto & subcolumns = it->second;
if (!inserted)
return subcolumns;
/// A dynamic subcolumn (a JSON path, a Dynamic variant) is materialized from the requested name,
/// and a constant column is resolved through the column it wraps, so neither set can be listed here.
if (root.type->hasDynamicSubcolumns() || isColumnConst(*root.column))
return subcolumns;
const auto root_data = ISerialization::SubstreamData(root.type->getSerialization(*root.type->getSerializationInfo(*root.column)))
.withType(root.type)
.withColumn(root.column);
/// Same walk `IDataType::getSubcolumnData` makes for one name, stopping at each subcolumn's path.
ISerialization::EnumerateStreamsSettings settings;
settings.position_independent_encoding = false;
settings.enumerate_dynamic_streams = false;
settings.enumerate_virtual_streams = true;
root_data.serialization->enumerateStreams(
settings,
[&](const auto & substream_path)
{
for (size_t i = 0; i < substream_path.size(); ++i)
{
const size_t prefix_len = i + 1;
if (!substream_path[i].visited && ISerialization::hasSubcolumnForPath(substream_path, prefix_len))
{
auto name = ISerialization::getSubcolumnNameForStream(substream_path, prefix_len);
auto path = substream_path;
path.resize(prefix_len);
/// The first spelling wins, as it does in `IDataType::getSubcolumnData`.
subcolumns.path_by_name.try_emplace(name, std::move(path));
if (case_insentive)
subcolumns.name_by_lowercase.try_emplace(boost::to_lower_copy(name), name);
}
substream_path[i].visited = true;
}
},
root_data);
subcolumns.complete = true;
return subcolumns;
}
std::optional<ColumnWithTypeAndName> NestedColumnExtractHelper::resolveSubcolumn(
const ColumnWithTypeAndName & root, const String & subcolumn_name, const String & result_name) const
{
String declared_name = subcolumn_name;
if (case_insentive)
{
/// Match the listed spellings before resolving the request itself, since a root that accepts
/// any path answers every spelling: a JSON path absent from the listing is a `Dynamic` of
/// NULLs, which would shadow a declared path differing only by case. A declared spelling is
/// its own match; anything else folds onto one in listing order.
const auto declared_names = root.type->getSubcolumnNames();
if (std::find(declared_names.begin(), declared_names.end(), subcolumn_name) == declared_names.end())
{
const auto declared_it = std::find_if(
declared_names.begin(),
declared_names.end(),
[&](const auto & candidate) { return boost::iequals(candidate, subcolumn_name); });
if (declared_it != declared_names.end())
declared_name = *declared_it;
}
}
const auto subcolumn_type = root.type->tryGetSubcolumnType(declared_name);
if (!subcolumn_type)
return {};
return ColumnWithTypeAndName{root.type->getSubcolumn(declared_name, root.column), subcolumn_type, result_name};
}
std::optional<ColumnWithTypeAndName> NestedColumnExtractHelper::extractColumn(const String & column_name)
{
if (block.has(column_name, case_insentive))
return {block.getByName(column_name, case_insentive)};
const auto nested_names = Nested::splitName(column_name);
const auto * root = block.findByName(nested_names.first, case_insentive);
if (!root)
return {};
const auto & subcolumns = subcolumnsOf(*root);
if (!subcolumns.complete)
return resolveSubcolumn(*root, nested_names.second, column_name);
/// A spelling that is itself a subcolumn name resolves to it, as it does in
/// `IDataType::getSubcolumnData`; only one that names none is matched case-insensitively.
auto it = subcolumns.path_by_name.find(nested_names.second);
if (it == subcolumns.path_by_name.end() && case_insentive)
{
const auto folded = subcolumns.name_by_lowercase.find(boost::to_lower_copy(nested_names.second));
if (folded != subcolumns.name_by_lowercase.end())
it = subcolumns.path_by_name.find(folded->second);
}
if (it == subcolumns.path_by_name.end())
return {};
const auto subcolumn_data = ISerialization::createFromPath(it->second, it->second.size());
return ColumnWithTypeAndName{subcolumn_data.column, subcolumn_data.type, column_name};
}
DataTypePtr getBaseTypeOfArray(DataTypePtr type, const Names & tuple_elements)
{
auto it = tuple_elements.begin();
/// Get underlying type for array, but w/o processing tuple elements that are not part of the nested, so it is done in 3 steps:
/// 1. Find Nested type (since it can be part of Tuple/Array)
/// 2. Process all Nested types (this is Array(Tuple()), it is responsibility of the caller to re-create proper Array nesting)
/// 3. Strip all nested arrays (it is responsibility of the caller to re-create proper Array nesting)
/// 1. Find Nested type (since it can be part of Tuple/Array)
while (true)
{
if (type->hasCustomName())
break;
else if (const auto * type_array = typeid_cast<const DataTypeArray *>(type.get()))
type = type_array->getNestedType();
else if (const auto * type_tuple = typeid_cast<const DataTypeTuple *>(type.get()))
{
if (it == tuple_elements.end())
break;
auto pos = type_tuple->tryGetPositionByName(*it);
if (!pos)
break;
++it;
type = type_tuple->getElement(*pos);
}
else if (const auto * type_map = typeid_cast<const DataTypeMap *>(type.get()))
{
/// `keys` and `values` are tuple elements of the Map's nested type, so they are on the
/// path like any other tuple element. Their array level is re-created by the caller.
if (it == tuple_elements.end())
break;
const auto & nested_tuple = assert_cast<const DataTypeTuple &>(*type_map->getNestedDataType());
auto pos = nested_tuple.tryGetPositionByName(*it);
if (!pos)
break;
++it;
type = nested_tuple.getElement(*pos);
}
else
break;
}
/// 2. Process all Nested types (this is Array(Tuple()), it is responsibility of the caller to re-create proper Array nesting)
while (type->hasCustomName())
{
if (const auto * type_nested = typeid_cast<const DataTypeNestedCustomName *>(type->getCustomName()))
{
if (it == tuple_elements.end())
break;
const auto & names = type_nested->getNames();
auto pos = std::find(names.begin(), names.end(), *it);
if (pos == names.end())
break;
++it;
type = type_nested->getElements().at(std::distance(names.begin(), pos));
}
else
break;
}
/// 3. Strip all nested arrays (it is responsibility of the caller to re-create proper Array nesting)
while (const auto * type_array = typeid_cast<const DataTypeArray *>(type.get()))
type = type_array->getNestedType();
return type;
}
DataTypePtr createArrayOfType(DataTypePtr type, size_t num_dimensions)
{
for (size_t i = 0; i < num_dimensions; ++i)
type = std::make_shared<DataTypeArray>(std::move(type));
return type;
}
}