-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathFunctionVariantAdaptor.cpp
More file actions
884 lines (791 loc) · 38.5 KB
/
Copy pathFunctionVariantAdaptor.cpp
File metadata and controls
884 lines (791 loc) · 38.5 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
#include <Common/CurrentThread.h>
#include <Common/Exception.h>
#include <Common/UnorderedSetWithMemoryTracking.h>
#include <Common/VectorWithMemoryTracking.h>
#include <DataTypes/DataTypeLowCardinality.h>
#include <DataTypes/DataTypeNothing.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeVariant.h>
#include <Functions/FunctionVariantAdaptor.h>
#include <Functions/TypeMismatchStrictness.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnVariant.h>
#include <Interpreters/castColumn.h>
#include <Interpreters/Context.h>
#include <Interpreters/ProcessList.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int ILLEGAL_TYPE_OF_ARGUMENT;
extern const int TYPE_MISMATCH;
extern const int CANNOT_CONVERT_TYPE;
extern const int NO_COMMON_TYPE;
extern const int TIMEOUT_EXCEEDED;
}
/// `checkTimeLimit` throws for `KILL QUERY` and the 'throw' overflow mode and returns false under
/// 'break'; a partially resolved alternative list is a wrong result type rather than a smaller one, so
/// the false return becomes a throw too.
static void checkQueryTimeLimit(const QueryStatusPtr & process_list_element, const String & function_name)
{
if (process_list_element && !process_list_element->checkTimeLimit())
throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Timeout exceeded: elapsed time limit reached in function {}", function_name);
}
/// Resolved from the executing thread rather than captured: an adaptor instance can be reused by a
/// later query.
static QueryStatusPtr tryGetProcessListElement()
{
if (auto query_context = CurrentThread::tryGetQueryContext())
return query_context->getProcessListElementSafe();
return {};
}
ExecutableFunctionVariantAdaptor::ExecutableFunctionVariantAdaptor(
std::shared_ptr<const IFunctionOverloadResolver> function_overload_resolver_,
size_t variant_argument_index_)
: function_overload_resolver(std::move(function_overload_resolver_))
, variant_argument_index(variant_argument_index_)
, throw_on_type_mismatch(shouldThrowOnVariantTypeMismatch())
{
}
/// Strip LowCardinality wrapper from nested function result if present.
/// This is needed because the FunctionBaseVariantAdaptor constructor computes result types
/// using nullptr columns (treated as non-const by getReturnType), while executeImpl uses
/// actual ColumnConst (from scatter/filter of constant arguments). The difference in const-ness
/// changes the LowCardinality heuristic in getReturnType, potentially wrapping the result
/// in LowCardinality during execution but not during type computation.
static void removeLowCardinalityFromResult(DataTypePtr & result_type, ColumnPtr & result_column)
{
if (typeid_cast<const DataTypeLowCardinality *>(result_type.get()))
{
result_type = removeLowCardinality(result_type);
result_column = result_column->convertToFullColumnIfLowCardinality();
}
}
/// Expand a function result back to pre-filter size. The nested function may return an input column
/// unchanged (e.g. concat of one String arg), so `column` can alias the input variant subcolumn;
/// mutate() clones it when shared, unlike assumeMutable() which would expand it in place.
static ColumnPtr expandColumnByFilter(ColumnPtr column, const PaddedPODArray<UInt8> & filter)
{
auto mutable_column = IColumn::mutate(std::move(column));
mutable_column->expand(filter, false);
return mutable_column;
}
ColumnPtr ExecutableFunctionVariantAdaptor::executeImpl(
const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t, bool dry_run) const
{
auto column = arguments[variant_argument_index].column->convertToFullColumnIfConst();
const auto & variant_column = assert_cast<const ColumnVariant &>(*column);
if (variant_column.empty())
return result_type->createColumn();
const auto & variant_type = assert_cast<const DataTypeVariant &>(*arguments[variant_argument_index].type);
const auto & variant_types = variant_type.getVariants();
/// Helper: build function base for the given arguments, respecting throw_on_type_mismatch.
/// Returns nullptr if the type is incompatible and throwing is disabled; otherwise throws.
auto try_build = [&](const ColumnsWithTypeAndName & args) -> FunctionBasePtr
{
if (throw_on_type_mismatch)
return function_overload_resolver->build(args);
try
{
return function_overload_resolver->build(args);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
return nullptr;
}
};
/// Helper: execute function, respecting throw_on_type_mismatch.
/// Some functions (e.g. comparisons) pass build() but throw during execute()
/// because executeGeneric calls getLeastSupertype which can throw NO_COMMON_TYPE.
/// Returns nullptr if execution fails with a type-related error and throwing is disabled.
auto try_execute = [&](const FunctionBasePtr & func_base, const ColumnsWithTypeAndName & args,
const DataTypePtr & res_type, size_t rows, bool is_dry_run) -> ColumnPtr
{
if (throw_on_type_mismatch)
return func_base->execute(args, res_type, rows, is_dry_run);
try
{
return func_base->execute(args, res_type, rows, is_dry_run);
}
catch (const Exception & e)
{
/// Only suppress NO_COMMON_TYPE, which is what getLeastSupertype throws when the
/// alternative type is incompatible with the other argument (e.g. comparison functions
/// calling executeGeneric). All other errors (including ILLEGAL_TYPE_OF_ARGUMENT) are
/// value-dependent and must propagate — for example, geoToS2 throws ILLEGAL_TYPE_OF_ARGUMENT
/// for NaN coordinates after build() has already succeeded for a Float64 alternative.
if (e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
return nullptr;
}
};
/// We use default implementation for Variant type only when default implementation for NULLs is used.
/// If current column contains only NULLs, result column will also contain only NULLs.
if (variant_column.hasOnlyNulls())
{
auto result = result_type->createColumn();
result->insertManyDefaults(variant_column.size());
return result;
}
/// Check if this Variant column contains only values of one type and no NULLs.
/// In this case we can replace argument with this variant and execute the function without changing all other arguments.
if (auto non_empty_variant_discr_no_nulls = variant_column.getGlobalDiscriminatorOfOneNoneEmptyVariantNoNulls())
{
/// Create new arguments and replace our Variant column with the single variant.
auto global_discr = *non_empty_variant_discr_no_nulls;
ColumnsWithTypeAndName new_arguments;
new_arguments.reserve(arguments.size());
for (size_t i = 0; i != arguments.size(); ++i)
{
if (i == variant_argument_index)
{
ColumnWithTypeAndName arg{
variant_column.getVariantPtrByGlobalDiscriminator(global_discr),
variant_types[global_discr],
arguments[i].name,
};
new_arguments.push_back(std::move(arg));
}
else
{
new_arguments.push_back(arguments[i]);
}
}
/// Execute function on new arguments.
auto func_base = try_build(new_arguments);
if (!func_base)
{
/// Type is incompatible and throw_on_type_mismatch is false — return NULLs for all rows.
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
DataTypePtr nested_result_type = func_base->getResultType();
ColumnPtr nested_result = try_execute(func_base, new_arguments, nested_result_type, variant_column.size(), dry_run);
if (!nested_result)
{
/// execute() failed with a type-related error and throw_on_type_mismatch is false — return NULLs for all rows.
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
removeLowCardinalityFromResult(nested_result_type, nested_result);
/// If result is Nullable(Nothing) or Nothing, just return column filled with NULLs/defaults.
/// Nothing can appear when the function is executed on an empty type (e.g. arrayElement on Array(Nothing)).
if (nested_result_type->onlyNull() || isNothing(nested_result_type))
{
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
/// If the result of the function is not Variant, it means that this function returns the same
/// type for all argument types (or similar types like FixedString or String).
/// In this case we return Nullable of this type (because Variant can contain NULLs).
if (!isVariant(result_type))
{
/// If return types are not the same, they must be convertible to each other (like FixedString/String).
if (!removeNullable(result_type)->equals(*removeNullable(nested_result_type)))
{
try
{
return castColumn(
ColumnWithTypeAndName{makeNullableSafe(nested_result), makeNullableSafe(nested_result_type), ""}, result_type);
}
catch (const Exception & e)
{
/// Only wrap type-conversion errors as LOGICAL_ERROR.
/// Other exceptions (e.g. MEMORY_LIMIT_EXCEEDED) should propagate as-is.
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
removeNullable(result_type)->getName(),
removeNullable(nested_result_type)->getName(),
e.message());
}
}
return makeNullableSafe(nested_result);
}
/// Result is Variant - use castColumn to handle the conversion.
/// If nested result type is one of the variant types or a Variant type with a subset of resulting variants,
/// castColumn will handle it correctly.
try
{
return castColumn(ColumnWithTypeAndName{nested_result, nested_result_type, ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
nested_result_type->getName(),
result_type->getName(),
e.message());
}
}
/// Second, check if this Variant column contains only 1 variant and NULLs.
/// In this case we can create a null-mask, filter all arguments by it and execute function
/// on this variant and filtered arguments.
if (auto non_empty_variant_discr = variant_column.getGlobalDiscriminatorOfOneNoneEmptyVariant())
{
auto global_discr = *non_empty_variant_discr;
/// Create filter for rows containing our variant.
PaddedPODArray<UInt8> filter;
filter.reserve(variant_column.size());
const auto & local_discriminators = variant_column.getLocalDiscriminators();
auto local_discr = variant_column.localDiscriminatorByGlobal(global_discr);
for (const auto & discr : local_discriminators)
filter.push_back(discr == local_discr);
/// Filter all other arguments using created filter.
ColumnsWithTypeAndName new_arguments;
new_arguments.reserve(arguments.size());
size_t result_size_hint = variant_column.getVariantPtrByGlobalDiscriminator(global_discr)->size();
for (size_t i = 0; i != arguments.size(); ++i)
{
if (i == variant_argument_index)
{
ColumnWithTypeAndName arg{
variant_column.getVariantPtrByGlobalDiscriminator(global_discr),
variant_types[global_discr],
arguments[i].name,
};
new_arguments.push_back(std::move(arg));
}
else
{
ColumnWithTypeAndName arg{arguments[i].column->filter(filter, result_size_hint), arguments[i].type, arguments[i].name};
new_arguments.push_back(std::move(arg));
}
}
/// Execute function on new arguments.
auto func_base = try_build(new_arguments);
if (!func_base)
{
/// Type is incompatible and throw_on_type_mismatch is false — return NULLs for all rows.
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
DataTypePtr nested_result_type = func_base->getResultType();
ColumnPtr nested_result = try_execute(func_base, new_arguments, nested_result_type, new_arguments[0].column->size(), dry_run);
if (!nested_result)
{
/// execute() failed with a type-related error and throw_on_type_mismatch is false — return NULLs for all rows.
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
nested_result = nested_result->convertToFullColumnIfConst();
removeLowCardinalityFromResult(nested_result_type, nested_result);
/// If result is Nullable(Nothing) or Nothing, just return column filled with NULLs/defaults.
if (nested_result_type->onlyNull() || isNothing(nested_result_type))
{
auto res = result_type->createColumn();
res->insertManyDefaults(variant_column.size());
return res;
}
/// If the result of the function is not Variant, it means that this function returns the same
/// type for all argument types (or similar types like FixedString or String).
/// In this case we return Nullable of this type (because Variant can contain NULLs).
if (!isVariant(result_type))
{
/// Expand filtered result. If it's already Nullable, it will be filled with NULLs.
nested_result = expandColumnByFilter(std::move(nested_result), filter);
/// If result wasn't Nullable, create null-mask from filter and make it Nullable.
if (!nested_result_type->isNullable() && nested_result_type->canBeInsideNullable())
{
for (auto & byte : filter)
byte = !byte;
auto null_map_column = ColumnUInt8::create();
null_map_column->getData() = std::move(filter);
nested_result = ColumnNullable::create(nested_result, std::move(null_map_column));
nested_result_type = makeNullable(nested_result_type);
}
/// If return types are not the same, they must be convertible to each other (like FixedString/String).
if (!result_type->equals(*nested_result_type))
{
try
{
return castColumn(ColumnWithTypeAndName{nested_result, nested_result_type, ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
result_type->getName(),
nested_result_type->getName(),
e.message());
}
}
return nested_result;
}
/// If the result of nested function is Variant type, expand it and cast to result type
/// The nested Variant may have a subset of types compared to the result Variant
if (isVariant(nested_result_type))
{
nested_result = expandColumnByFilter(std::move(nested_result), filter);
/// Cast to result type (handles case where nested Variant is a subset)
try
{
return castColumn(ColumnWithTypeAndName{nested_result, nested_result_type, ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
nested_result_type->getName(),
result_type->getName(),
e.message());
}
}
/// If the result of nested function is not Variant, cast it to result Variant type and expand
/// This handles both regular types and Nullable types automatically
ColumnPtr result;
try
{
result = castColumn(ColumnWithTypeAndName{nested_result, nested_result_type, ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
nested_result_type->getName(),
result_type->getName(),
e.message());
}
/// Expand to match the original column size (filling filtered-out rows with NULLs)
result = expandColumnByFilter(std::move(result), filter);
return result;
}
/// In general case with several variants we create a selector from discriminators
/// and use it to create a set of filtered arguments for each variant.
/// Then we will execute our function over all these arguments and construct the resulting column
/// from all results based on created selector.
const auto & local_discriminators = variant_column.getLocalDiscriminators();
const auto & offsets = variant_column.getOffsets();
size_t num_variants = variant_types.size();
/// We use an array where index is the global discriminator.
/// Variants that don't appear in the data will have null column pointers.
/// Index num_variants is reserved for NULL values.
ColumnsWithTypeAndName variants;
variants.resize(num_variants + 1);
/// Create selector using global discriminators as indexes.
/// Populate variants array only for discriminators that appear in the data.
IColumn::Selector selector;
selector.reserve(variant_column.size());
for (char8_t local_discr : local_discriminators)
{
if (local_discr == ColumnVariant::NULL_DISCRIMINATOR)
{
selector.push_back(num_variants);
}
else
{
auto global_discr = variant_column.globalDiscriminatorByLocal(local_discr);
/// Add this variant to the array if not already present.
if (!variants[global_discr].column)
{
variants[global_discr] = ColumnWithTypeAndName{
variant_column.getVariantPtrByGlobalDiscriminator(global_discr),
variant_types[global_discr],
""
};
}
selector.push_back(global_discr);
}
}
/// Create set of arguments for each variant using selector.
VectorWithMemoryTracking<ColumnsWithTypeAndName> variants_arguments;
variants_arguments.resize(variants.size());
for (size_t i = 0; i != arguments.size(); ++i)
{
if (i == variant_argument_index)
{
/// Add variant arguments for variants that exist in the data (0 to num_variants-1).
for (size_t j = 0; j < num_variants; ++j)
{
if (variants[j].column)
variants_arguments[j].push_back(variants[j]);
}
}
else
{
auto columns = arguments[i].column->scatter(variants.size(), selector);
for (size_t j = 0; j != variants_arguments.size(); ++j)
variants_arguments[j].emplace_back(std::move(columns[j]), arguments[i].type, arguments[i].name);
}
}
/// Execute function over all created sets of arguments and remember all results.
VectorWithMemoryTracking<ColumnPtr> variants_results;
VectorWithMemoryTracking<DataTypePtr> variants_result_types;
variants_results.resize(variants.size());
variants_result_types.resize(variants.size());
/// Index num_variants is allocated for rows with NULL values, it doesn't have any result,
/// we will insert NULL values in these rows.
const auto process_list_element = tryGetProcessListElement();
const auto function_name = getName();
for (size_t i = 0; i < num_variants; ++i)
{
/// Skip variants that don't exist in the data.
if (!variants[i].column)
continue;
checkQueryTimeLimit(process_list_element, function_name);
auto func_base = try_build(variants_arguments[i]);
if (!func_base)
{
/// Type is incompatible and throw_on_type_mismatch is false — treat as NULL result.
variants_results[i] = nullptr;
continue;
}
auto nested_result_type = func_base->getResultType();
auto nested_result
= try_execute(func_base, variants_arguments[i], nested_result_type, variants_arguments[i][0].column->size(), dry_run);
if (!nested_result)
{
/// execute() failed with a type-related error and throw_on_type_mismatch is false — treat as NULL result.
variants_results[i] = nullptr;
continue;
}
nested_result = nested_result->convertToFullColumnIfConst();
removeLowCardinalityFromResult(nested_result_type, nested_result);
variants_result_types[i] = nested_result_type;
/// Set nullptr in case of only NULL or Nothing values, we will insert NULL for rows of this selector.
if (nested_result_type->onlyNull() || isNothing(nested_result_type))
{
variants_results[i] = nullptr;
}
/// If the result of the function is not Variant, it means that this function returns the same
/// type for all argument types (or similar types like FixedString or String).
/// In this case we return Nullable of this type (because Variant can contain NULLs).
else if (!isVariant(result_type))
{
/// If return types are not the same, they must be convertible to each other (like FixedString/String).
if (!removeNullable(result_type)->equals(*removeNullable(nested_result_type)))
{
try
{
variants_results[i] = castColumn(
ColumnWithTypeAndName{makeNullableSafe(nested_result), makeNullableSafe(nested_result_type), ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
result_type->getName(),
nested_result_type->getName(),
e.message());
}
}
else
{
variants_results[i] = makeNullableSafe(nested_result);
}
}
/// Result is Variant - keep the individual result columns, we'll build Variant manually
else
{
variants_results[i] = nested_result;
}
}
/// Construct resulting column
if (!isVariant(result_type))
{
/// Non-Variant result: assemble from nullable results
auto result = result_type->createColumn();
result->reserve(variant_column.size());
for (size_t i = 0; i != selector.size(); ++i)
{
if (selector[i] == num_variants || !variants_results[selector[i]])
result->insertDefault();
else
result->insertFrom(*variants_results[selector[i]], offsets[i]);
}
return result;
}
/// Variant result: check if we can use optimized direct construction
/// or need to use general approach with casting.
const auto & result_variant_type = assert_cast<const DataTypeVariant &>(*result_type);
/// Check if we can use optimized direct construction:
/// 1. All result types must be different (no duplicates)
/// 2. None of the result types should be a nested Variant
/// 3. None of the result types should be Nullable or LowCardinality(Nullable)
/// (casting handles NULL extraction automatically)
bool can_use_direct_construction = true;
UnorderedSetWithMemoryTracking<String> result_type_names;
for (size_t i = 0; i < num_variants; ++i)
{
if (!variants[i].column || !variants_results[i])
continue;
const auto & variant_result_type = variants_result_types[i];
/// Check if this result type is a Variant, Nullable, or LowCardinality(Nullable)
/// Nullable results need casting to handle NULL values properly in the Variant
/// This is done automatically during casts
if (isVariant(variant_result_type) || variant_result_type->isNullable() || variant_result_type->isLowCardinalityNullable())
{
can_use_direct_construction = false;
break;
}
/// Check for duplicate result types
if (!result_type_names.insert(variant_result_type->getName()).second)
{
can_use_direct_construction = false;
break;
}
}
if (can_use_direct_construction)
{
/// Optimized path: build Variant directly from individual variant columns
auto result = result_type->createColumn();
auto & result_variant = assert_cast<ColumnVariant &>(*result);
/// Map each variant result to its discriminator in the result Variant
VectorWithMemoryTracking<std::optional<ColumnVariant::Discriminator>> result_discriminators(variants_results.size());
for (size_t i = 0; i < num_variants; ++i)
{
/// Skip variants that don't exist in the data or have no result.
if (!variants[i].column || !variants_results[i])
continue;
const auto & variant_result_type = variants_result_types[i];
/// Find discriminator for this result type in the result Variant
/// Remove Nullable wrapper since flattened types don't have it
result_discriminators[i] = result_variant_type.tryGetVariantDiscriminator(removeNullable(variant_result_type)->getName());
if (!result_discriminators[i])
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot find variant type {} in result Variant type {} during execution of {}",
removeNullable(variant_result_type)->getName(),
result_type->getName(),
getName());
}
/// Set variant columns in the result
for (size_t i = 0; i < num_variants; ++i)
{
if (variants[i].column && variants_results[i] && result_discriminators[i])
{
auto global_discr = *result_discriminators[i];
auto local_discr = result_variant.localDiscriminatorByGlobal(global_discr);
result_variant.getVariantPtrByLocalDiscriminator(local_discr) = variants_results[i];
}
}
/// Build discriminators and offsets
auto & result_discriminators_col = result_variant.getLocalDiscriminators();
auto & result_offsets = result_variant.getOffsets();
result_discriminators_col.reserve(variant_column.size());
result_offsets.reserve(variant_column.size());
for (size_t i = 0; i != selector.size(); ++i)
{
if (selector[i] == num_variants || !variants_results[selector[i]])
{
result_discriminators_col.push_back(ColumnVariant::NULL_DISCRIMINATOR);
result_offsets.emplace_back();
}
else
{
auto global_discr = *result_discriminators[selector[i]];
auto local_discr = result_variant.localDiscriminatorByGlobal(global_discr);
result_discriminators_col.push_back(local_discr);
result_offsets.push_back(offsets[i]);
}
}
return result;
}
/// General path: cast each result to final Variant type to handle
/// duplicate result types and nested Variants correctly
VectorWithMemoryTracking<ColumnPtr> casted_results(variants_results.size());
for (size_t i = 0; i < num_variants; ++i)
{
if (!variants[i].column || !variants_results[i])
continue;
const auto & variant_result_type = variants_result_types[i];
/// Cast this result to the final Variant type
try
{
casted_results[i] = castColumn(ColumnWithTypeAndName{variants_results[i], variant_result_type, ""}, result_type);
}
catch (const Exception & e)
{
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Cannot convert nested result of function {} with type {} to the expected result type {}: {}",
getName(),
variant_result_type->getName(),
result_type->getName(),
e.message());
}
}
/// Build result column row by row using selector and casted results
auto result = result_type->createColumn();
result->reserve(variant_column.size());
for (size_t i = 0; i != selector.size(); ++i)
{
if (selector[i] == num_variants || !variants_results[selector[i]])
result->insertDefault();
else
result->insertFrom(*casted_results[selector[i]], offsets[i]);
}
return result;
}
ColumnPtr ExecutableFunctionVariantAdaptor::executeImpl(
const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const
{
return executeImpl(arguments, result_type, input_rows_count, false);
}
ColumnPtr ExecutableFunctionVariantAdaptor::executeDryRunImpl(
const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const
{
return executeImpl(arguments, result_type, input_rows_count, true);
}
FunctionBaseVariantAdaptor::FunctionBaseVariantAdaptor(
std::shared_ptr<const IFunctionOverloadResolver> function_overload_resolver_,
ColumnsWithTypeAndName arguments_with_type_,
size_t variant_argument_index_)
: function_overload_resolver(std::move(function_overload_resolver_))
, variant_argument_index(variant_argument_index_)
{
arguments.reserve(arguments_with_type_.size());
for (const auto & arg : arguments_with_type_)
arguments.push_back(arg.type);
if (variant_argument_index >= arguments.size())
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Variant argument index {} is out of range for {} with {} arguments",
variant_argument_index,
function_overload_resolver->getName(),
arguments.size());
/// Get the Variant argument type and its alternatives.
const auto * variant_type = typeid_cast<const DataTypeVariant *>(arguments[variant_argument_index].get());
if (!variant_type)
throw Exception(ErrorCodes::LOGICAL_ERROR, "Expected Variant type at position {}", variant_argument_index);
const auto & variant_alternatives = variant_type->getVariants();
/// For each alternative in the Variant, build the function and get the actual result type.
DataTypes result_types;
result_types.reserve(variant_alternatives.size());
const auto process_list_element = tryGetProcessListElement();
const auto function_name = function_overload_resolver->getName();
for (const auto & alternative : variant_alternatives)
{
checkQueryTimeLimit(process_list_element, function_name);
/// Create arguments with this alternative instead of the Variant.
/// Preserve original columns (especially ColumnConst) for non-Variant arguments.
ColumnsWithTypeAndName alt_columns_with_type = arguments_with_type_;
alt_columns_with_type[variant_argument_index].type = alternative;
/// Important: don't pass the original ColumnVariant with a non-Variant type
alt_columns_with_type[variant_argument_index].column = nullptr;
/// Get the return type for this alternative.
/// Wrap in try-catch to handle incompatible type combinations gracefully.
DataTypePtr alt_return_type;
try
{
const auto func_base = function_overload_resolver->build(alt_columns_with_type);
/// Strip LowCardinality from result type for consistency with executeImpl,
/// where we also strip LC from nested function results.
result_types.push_back(removeLowCardinality(func_base->getResultType()));
}
catch (const Exception & e)
{
/// If this combination of types is incompatible (e.g., Array(UInt32) vs UInt64),
/// skip this alternative and treat it as if it doesn't participate in the result type.
/// Only catch type-related errors - re-throw everything else.
if (e.code() != ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT && e.code() != ErrorCodes::TYPE_MISMATCH
&& e.code() != ErrorCodes::CANNOT_CONVERT_TYPE && e.code() != ErrorCodes::NO_COMMON_TYPE)
throw;
/// Otherwise, skip this alternative
}
}
/// If no valid result types were found, all Variant alternatives are incompatible with the function.
/// When variant_throw_on_type_mismatch is enabled (the default), throw a clear error rather than
/// silently returning Nullable(Nothing), which would cause WHERE clauses to return 0 rows with no
/// diagnostic. When the setting is disabled, fall back to Nullable(Nothing) so that executeImpl
/// returns NULL rows (consistent with the per-row mismatch behaviour).
if (result_types.empty())
{
if (!shouldThrowOnVariantTypeMismatch())
{
return_type = makeNullable(std::make_shared<DataTypeNothing>());
return;
}
String alt_names;
for (const auto & alt : variant_alternatives)
{
if (!alt_names.empty())
alt_names += ", ";
alt_names += alt->getName();
}
throw Exception(
ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT,
"None of the Variant alternatives ({}) are compatible with function '{}'",
alt_names,
function_overload_resolver->getName());
}
/// If all result types are the same (ignoring Nullable), return Nullable(common).
/// Otherwise, return Variant(R0, R1, ...) in the same order.
/// Compare by name to handle custom types correctly (like Geometry subtypes)
bool all_same = true;
DataTypePtr common_type = removeNullable(result_types[0]);
for (size_t i = 1; i < result_types.size(); ++i)
{
DataTypePtr current_type = removeNullable(result_types[i]);
if (common_type->getName() != current_type->getName())
{
all_same = false;
break;
}
}
if (all_same)
{
return_type = makeNullableSafe(common_type);
}
else
{
/// If we have Variant types in result_types, we need to flatten them
/// because Variant inside Variant is not supported.
/// We also need to remove Nullability from types because Nullable types are not allowed inside Variant.
DataTypes flattened_types;
for (const auto & type : result_types)
{
if (const auto * vt = typeid_cast<const DataTypeVariant *>(type.get()))
{
/// Extract inner variants and add them to flattened list
const auto & inner_variants = vt->getVariants();
flattened_types.insert(flattened_types.end(), inner_variants.begin(), inner_variants.end());
}
else
flattened_types.push_back(removeNullable(type));
}
return_type = std::make_shared<DataTypeVariant>(flattened_types);
}
}
}