-
Notifications
You must be signed in to change notification settings - Fork 412
/
FunctionsTiDBConversion.h
2584 lines (2400 loc) · 104 KB
/
FunctionsTiDBConversion.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <Columns/ColumnConst.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnsCommon.h>
#include <Common/FieldVisitors.h>
#include <Common/MyDuration.h>
#include <Common/MyTime.h>
#include <DataTypes/DataTypeArray.h>
#include <DataTypes/DataTypeDate.h>
#include <DataTypes/DataTypeDateTime.h>
#include <DataTypes/DataTypeEnum.h>
#include <DataTypes/DataTypeFactory.h>
#include <DataTypes/DataTypeFixedString.h>
#include <DataTypes/DataTypeInterval.h>
#include <DataTypes/DataTypeMyDate.h>
#include <DataTypes/DataTypeMyDateTime.h>
#include <DataTypes/DataTypeMyDuration.h>
#include <DataTypes/DataTypeNothing.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypeUUID.h>
#include <DataTypes/DataTypesNumber.h>
#include <Flash/Coprocessor/DAGContext.h>
#include <Flash/Coprocessor/DAGUtils.h>
#include <Functions/FunctionFactory.h>
#include <Functions/FunctionHelpers.h>
#include <Functions/FunctionsConversion.h>
#include <Functions/FunctionsDateTime.h>
#include <Functions/FunctionsMiscellaneous.h>
#include <Functions/IFunction.h>
#include <Functions/castTypeToEither.h>
#include <IO/Buffer/ReadBufferFromMemory.h>
#include <IO/Buffer/WriteBufferFromVector.h>
#include <IO/Util/Operators.h>
#include <IO/parseDateTimeBestEffort.h>
#include <Interpreters/Context_fwd.h>
#include <Interpreters/ExpressionActions.h>
#include <TiDB/Collation/Collator.h>
#include <ext/collection_cast.h>
#include <ext/enumerate.h>
#include <ext/range.h>
#include <type_traits>
namespace DB
{
String trim(const StringRef & value);
enum CastError
{
NONE = 0,
TRUNCATED_ERR,
OVERFLOW_ERR,
};
namespace
{
constexpr static Int64 pow10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
}
ALWAYS_INLINE inline size_t charLengthToByteLengthFromUTF8(const char * data, size_t length, size_t char_length)
{
size_t ret = 0;
for (size_t char_index = 0; char_index < char_length && ret < length; ++char_index)
{
uint8_t c = data[ret];
if (c < 0x80)
ret += 1;
else if (c < 0xE0)
ret += 2;
else if (c < 0xF0)
ret += 3;
else
ret += 4;
}
if unlikely (ret > length)
{
throw Exception(
fmt::format(
"Illegal utf8 byte sequence bytes: {} result_length: {} char_length: {}",
length,
ret,
char_length),
ErrorCodes::ILLEGAL_COLUMN);
}
return ret;
}
/// cast int/real/decimal/time as string
template <typename FromDataType, bool return_nullable>
struct TiDBConvertToString
{
using FromFieldType = typename FromDataType::FieldType;
static void execute(
Block & block,
const ColumnNumbers & arguments,
size_t result,
bool,
const tipb::FieldType & tp,
const Context & context)
{
size_t size = block.getByPosition(arguments[0]).column->size();
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container * vec_null_map_to [[maybe_unused]] = nullptr;
if constexpr (return_nullable)
{
col_null_map_to = ColumnUInt8::create(size, 0);
vec_null_map_to = &col_null_map_to->getData();
}
bool need_padding = tp.tp() == TiDB::TypeString && tp.flen() > 0 && tp.collate() == TiDB::ITiDBCollator::BINARY;
String padding_string;
if (need_padding)
padding_string.resize(tp.flen(), 0);
const auto & col_with_type_and_name = block.getByPosition(arguments[0]);
const auto & type = static_cast<const FromDataType &>(*col_with_type_and_name.type);
auto col_to = ColumnString::create();
ColumnString::Chars_t & data_to = col_to->getChars();
ColumnString::Offsets & offsets_to = col_to->getOffsets();
if constexpr (std::is_same_v<FromDataType, DataTypeString>)
{
/// cast string as string
const IColumn * col_from = block.getByPosition(arguments[0]).column.get();
const auto * col_from_string = checkAndGetColumn<ColumnString>(col_from);
const ColumnString::Chars_t * data_from = &col_from_string->getChars();
const IColumn::Offsets * offsets_from = &col_from_string->getOffsets();
offsets_to.resize(size);
WriteBufferFromVector<ColumnString::Chars_t> write_buffer(data_to);
size_t current_offset = 0;
for (size_t i = 0; i < size; i++)
{
size_t next_offset = (*offsets_from)[i];
size_t org_length = next_offset - current_offset - 1;
size_t byte_length = org_length;
if (tp.flen() >= 0)
{
byte_length = tp.flen();
if (tp.charset() == "utf8" || tp.charset() == "utf8mb4")
byte_length = charLengthToByteLengthFromUTF8(
reinterpret_cast<const char *>(&(*data_from)[current_offset]),
org_length,
byte_length);
byte_length = std::min(byte_length, org_length);
}
if (byte_length < org_length)
context.getDAGContext()->handleTruncateError("Data Too Long");
write_buffer.write(reinterpret_cast<const char *>(&(*data_from)[current_offset]), byte_length);
if (need_padding && byte_length < static_cast<size_t>(tp.flen()))
write_buffer.write(padding_string.data(), tp.flen() - byte_length);
writeChar(0, write_buffer);
offsets_to[i] = write_buffer.count();
current_offset = next_offset;
}
data_to.resize(write_buffer.count());
}
else if constexpr (IsDecimal<FromFieldType>)
{
/// cast decimal as string
const auto * col_from
= checkAndGetColumn<ColumnDecimal<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
const typename ColumnDecimal<FromFieldType>::Container & vec_from = col_from->getData();
ColumnString::Chars_t container_per_element;
data_to.resize(size * decimal_max_prec + size);
container_per_element.resize(decimal_max_prec);
offsets_to.resize(size);
WriteBufferFromVector<ColumnString::Chars_t> write_buffer(data_to);
for (size_t i = 0; i < size; ++i)
{
WriteBufferFromVector<ColumnString::Chars_t> element_write_buffer(container_per_element);
FormatImpl<FromDataType>::execute(vec_from[i], element_write_buffer, &type, nullptr);
size_t byte_length = element_write_buffer.count();
if (tp.flen() >= 0)
byte_length = std::min(byte_length, tp.flen());
if (byte_length < element_write_buffer.count())
context.getDAGContext()->handleTruncateError("Data Too Long");
write_buffer.write(reinterpret_cast<char *>(container_per_element.data()), byte_length);
if (need_padding && byte_length < static_cast<size_t>(tp.flen()))
write_buffer.write(padding_string.data(), tp.flen() - byte_length);
writeChar(0, write_buffer);
offsets_to[i] = write_buffer.count();
}
data_to.resize(write_buffer.count());
}
else if (
const auto col_from = checkAndGetColumn<ColumnVector<FromFieldType>>(col_with_type_and_name.column.get()))
{
/// cast int/real/time as string
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
ColumnString::Chars_t container_per_element;
if constexpr (std::is_same_v<FromDataType, DataTypeMyDate>)
{
auto length = strlen("YYYY-MM-DD") + 1;
data_to.resize(size * length);
container_per_element.resize(length);
}
if constexpr (std::is_same_v<FromDataType, DataTypeMyDateTime>)
{
auto length = strlen("YYYY-MM-DD hh:mm:ss") + 1 + (type.getFraction() ? 0 : 1 + type.getFraction());
data_to.resize(size * length);
container_per_element.resize(length);
}
else
{
data_to.resize(size * 3);
container_per_element.resize(3);
}
offsets_to.resize(size);
WriteBufferFromVector<ColumnString::Chars_t> write_buffer(data_to);
for (size_t i = 0; i < size; ++i)
{
WriteBufferFromVector<ColumnString::Chars_t> element_write_buffer(container_per_element);
FormatImpl<FromDataType>::execute(vec_from[i], element_write_buffer, &type, nullptr);
size_t byte_length = element_write_buffer.count();
if (tp.flen() >= 0)
byte_length = std::min(byte_length, tp.flen());
if (byte_length < element_write_buffer.count())
context.getDAGContext()->handleTruncateError("Data Too Long");
write_buffer.write(reinterpret_cast<char *>(container_per_element.data()), byte_length);
if (need_padding && byte_length < static_cast<size_t>(tp.flen()))
write_buffer.write(padding_string.data(), tp.flen() - byte_length);
writeChar(0, write_buffer);
offsets_to[i] = write_buffer.count();
}
data_to.resize(write_buffer.count());
}
else
throw Exception(
"Illegal column " + block.getByPosition(arguments[0]).column->getName()
+ " of first argument of function tidb_cast",
ErrorCodes::ILLEGAL_COLUMN);
if constexpr (return_nullable)
block.getByPosition(result).column = ColumnNullable::create(std::move(col_to), std::move(col_null_map_to));
else
block.getByPosition(result).column = std::move(col_to);
}
};
/// cast int/real/decimal/time/string as int
template <typename FromDataType, typename ToDataType, bool return_nullable>
struct TiDBConvertToInteger
{
using FromFieldType = typename FromDataType::FieldType;
using ToFieldType = typename ToDataType::FieldType;
static constexpr bool to_unsigned = std::is_unsigned_v<ToFieldType>;
template <typename T, typename ToFieldType>
static std::enable_if_t<std::is_floating_point_v<T>, ToFieldType> toUInt(const T & value, const Context & context)
{
T rounded_value = std::round(value);
if (rounded_value < 0)
{
context.getDAGContext()->handleOverflowError("Cast real as integer", Errors::Types::Truncated);
if (context.getDAGContext()->shouldClipToZero())
return static_cast<ToFieldType>(0);
return static_cast<ToFieldType>(rounded_value);
}
auto field_max = static_cast<T>(std::numeric_limits<ToFieldType>::max());
if (rounded_value > field_max)
{
context.getDAGContext()->handleOverflowError("Cast real as integer", Errors::Types::Truncated);
return std::numeric_limits<ToFieldType>::max();
}
else if (rounded_value == field_max)
{
context.getDAGContext()->handleOverflowError("cast real as int", Errors::Types::Truncated);
return std::numeric_limits<ToFieldType>::max();
}
else
return static_cast<ToFieldType>(rounded_value);
}
template <typename T, typename ToFieldType>
static std::enable_if_t<std::is_floating_point_v<T>, ToFieldType> toInt(const T & value, const Context & context)
{
T rounded_value = std::round(value);
auto field_min = static_cast<T>(std::numeric_limits<ToFieldType>::min());
auto field_max = static_cast<T>(std::numeric_limits<ToFieldType>::max());
if (rounded_value < field_min)
{
context.getDAGContext()->handleOverflowError("cast real as int", Errors::Types::Truncated);
return std::numeric_limits<ToFieldType>::min();
}
if (rounded_value >= field_max)
{
context.getDAGContext()->handleOverflowError("cast real as int", Errors::Types::Truncated);
return std::numeric_limits<ToFieldType>::max();
}
return static_cast<ToFieldType>(rounded_value);
}
template <typename T, typename ToFieldType>
static ToFieldType decToUInt(const DecimalField<T> & value, const Context & context)
{
auto v = value.getValue().value;
if (v < 0)
{
context.getDAGContext()->handleOverflowError("cast decimal as int", Errors::Types::Truncated);
return static_cast<ToFieldType>(0);
}
ScaleType scale = value.getScale();
for (ScaleType i = 0; i < scale; i++)
{
v = v / 10 + (i + 1 == scale && v % 10 >= 5);
}
Int128 max_value = std::numeric_limits<ToFieldType>::max();
if (v > max_value)
{
context.getDAGContext()->handleOverflowError("cast decimal as int", Errors::Types::Truncated);
return max_value;
}
return static_cast<ToFieldType>(v);
}
template <typename T, typename ToFieldType>
static ToFieldType decToInt(const DecimalField<T> & value, const Context & context)
{
auto v = value.getValue().value;
ScaleType scale = value.getScale();
for (ScaleType i = 0; i < scale; i++)
{
v = v / 10 + (i + 1 == scale && v % 10 >= 5);
}
if (v > std::numeric_limits<ToFieldType>::max() || v < std::numeric_limits<ToFieldType>::min())
{
context.getDAGContext()->handleOverflowError("cast decimal as int", Errors::Types::Truncated);
if (v > 0)
return std::numeric_limits<ToFieldType>::max();
return std::numeric_limits<ToFieldType>::min();
}
return static_cast<ToFieldType>(v);
}
static StringRef getValidIntPrefix(const StringRef & value)
{
StringRef ret;
ret.data = value.data;
ret.size = 0;
for (; ret.size < value.size; ret.size++)
{
char current = value.data[ret.size];
if ((current >= '0' && current <= '9') || (ret.size == 0 && (current == '+' || current == '-')))
continue;
break;
}
return ret;
}
template <typename T>
static std::tuple<T, CastError> toUInt(const StringRef & value)
{
static const T cut_off = std::numeric_limits<T>::max() / 10;
if (value.data[0] == '-')
return std::make_tuple(0, OVERFLOW_ERR);
size_t pos = value.data[0] == '+' ? 1 : 0;
T ret = 0;
for (; pos < value.size; pos++)
{
if (ret > cut_off)
/// overflow
return std::make_tuple(std::numeric_limits<T>::max(), OVERFLOW_ERR);
int next = value.data[pos] - '0';
if (static_cast<T>(ret * 10 + next) < ret)
/// overflow
return std::make_tuple(std::numeric_limits<T>::max(), OVERFLOW_ERR);
ret = ret * 10 + next;
}
return std::make_tuple(ret, NONE);
}
template <typename T>
static std::tuple<T, CastError> toInt(const StringRef & value)
{
bool is_negative = false;
UInt64 uint_value = 0;
CastError err = NONE;
if (value.data[0] == '-')
{
is_negative = true;
StringRef uint_string(value.data + 1, value.size - 1);
std::tie(uint_value, err) = toUInt<std::make_unsigned_t<T>>(uint_string);
}
else
{
std::tie(uint_value, err) = toUInt<std::make_unsigned_t<T>>(value);
}
if (err == OVERFLOW_ERR)
return std::make_tuple(is_negative ? std::numeric_limits<T>::min() : std::numeric_limits<T>::max(), err);
// todo handle truncate error
if (is_negative)
{
if (uint_value > std::numeric_limits<std::make_unsigned_t<T>>::max() / 2 + 1)
return std::make_tuple(std::numeric_limits<T>::min(), OVERFLOW_ERR);
return std::make_tuple(static_cast<T>(-uint_value), NONE);
}
else
{
if (uint_value > std::numeric_limits<T>::max())
return std::make_tuple(std::numeric_limits<T>::max(), OVERFLOW_ERR);
return std::make_tuple(static_cast<T>(uint_value), NONE);
}
}
template <typename T>
static T strToInt(const StringRef & value, const Context & context)
{
// trim space
String trim_string = trim(value);
if (trim_string.empty())
{
if (value.size != 0)
context.getDAGContext()->handleTruncateError("cast str as int");
return static_cast<T>(0);
}
StringRef int_string = getValidIntPrefix(StringRef(trim_string));
if (int_string.size == 0)
{
if (value.size != 0)
context.getDAGContext()->handleTruncateError("cast str as int");
return static_cast<T>(0);
}
bool is_negative = false;
if (int_string.data[0] == '-')
{
is_negative = true;
}
if (!is_negative)
{
auto [value, err] = toUInt<T>(int_string);
if (err == OVERFLOW_ERR)
context.getDAGContext()->handleOverflowError("cast str as int", Errors::Types::Truncated);
return static_cast<T>(value);
}
else
{
/// TODO: append warning CastAsSignedOverflow if try to cast negative value to unsigned
auto [value, err] = toInt<T>(int_string);
if (err == OVERFLOW_ERR)
context.getDAGContext()->handleOverflowError("cast str as int", Errors::Types::Truncated);
return static_cast<T>(value);
}
}
static void execute(
Block & block,
const ColumnNumbers & arguments,
size_t result,
bool,
const tipb::FieldType &,
const Context & context)
{
size_t size = block.getByPosition(arguments[0]).column->size();
auto col_to = ColumnVector<ToFieldType>::create(size, 0);
typename ColumnVector<ToFieldType>::Container & vec_to = col_to->getData();
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container * vec_null_map_to [[maybe_unused]] = nullptr;
if constexpr (return_nullable)
{
col_null_map_to = ColumnUInt8::create(size, 0);
vec_null_map_to = &col_null_map_to->getData();
}
if constexpr (IsDecimal<FromFieldType>)
{
/// cast decimal as int
const auto * col_from
= checkAndGetColumn<ColumnDecimal<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
for (size_t i = 0; i < size; ++i)
{
auto field = (*col_from)[i].template safeGet<DecimalField<FromFieldType>>();
if constexpr (to_unsigned)
{
vec_to[i] = decToUInt<FromFieldType, ToFieldType>(field, context);
}
else
{
vec_to[i] = decToInt<FromFieldType, ToFieldType>(field, context);
}
}
}
else if constexpr (
std::is_same_v<FromDataType, DataTypeMyDateTime> || std::is_same_v<FromDataType, DataTypeMyDate>)
{
/// cast time as int
const auto & col_with_type_and_name = block.getByPosition(arguments[0]);
const ColumnVector<FromFieldType> * col_from
= checkAndGetColumn<ColumnVector<FromFieldType>>(col_with_type_and_name.column.get());
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
for (size_t i = 0; i < size; i++)
{
if constexpr (std::is_same_v<DataTypeMyDate, FromDataType>)
{
MyDate date(vec_from[i]);
vec_to[i] = date.year * 10000 + date.month * 100 + date.day;
}
else
{
MyDateTime date_time(vec_from[i]);
vec_to[i] = date_time.year * 10000000000ULL + date_time.month * 100000000ULL
+ date_time.day * 1000000 + date_time.hour * 10000 + date_time.minute * 100 + date_time.second;
}
}
}
else if constexpr (std::is_same_v<FromDataType, DataTypeString>)
{
/// cast string as int
const IColumn * col_from = block.getByPosition(arguments[0]).column.get();
const auto * col_from_string = checkAndGetColumn<ColumnString>(col_from);
const ColumnString::Chars_t * chars = &col_from_string->getChars();
const IColumn::Offsets * offsets = &col_from_string->getOffsets();
size_t current_offset = 0;
for (size_t i = 0; i < size; i++)
{
size_t next_offset = (*offsets)[i];
size_t string_size = next_offset - current_offset - 1;
StringRef string_value(&(*chars)[current_offset], string_size);
vec_to[i] = strToInt<ToFieldType>(string_value, context);
current_offset = next_offset;
}
}
else if constexpr (std::is_integral_v<FromFieldType>)
{
/// cast enum/int as int
const ColumnVector<FromFieldType> * col_from
= checkAndGetColumn<ColumnVector<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
for (size_t i = 0; i < size; i++)
vec_to[i] = static_cast<ToFieldType>(vec_from[i]);
}
else if constexpr (std::is_floating_point_v<FromFieldType>)
{
/// cast real as int
const ColumnVector<FromFieldType> * col_from
= checkAndGetColumn<ColumnVector<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
if constexpr (to_unsigned)
{
for (size_t i = 0; i < size; i++)
vec_to[i] = toUInt<FromFieldType, ToFieldType>(vec_from[i], context);
}
else
{
for (size_t i = 0; i < size; i++)
vec_to[i] = toInt<FromFieldType, ToFieldType>(vec_from[i], context);
}
}
else
{
throw Exception(
"Illegal column " + block.getByPosition(arguments[0]).column->getName()
+ " of first argument of function tidb_cast",
ErrorCodes::ILLEGAL_COLUMN);
}
if constexpr (return_nullable)
block.getByPosition(result).column = ColumnNullable::create(std::move(col_to), std::move(col_null_map_to));
else
block.getByPosition(result).column = std::move(col_to);
}
};
/// cast int/real/decimal/time/string as real
template <typename FromDataType, typename ToDataType, bool return_nullable, bool to_unsigned>
struct TiDBConvertToFloat
{
static_assert(std::is_same_v<ToDataType, DataTypeFloat32> || std::is_same_v<ToDataType, DataTypeFloat64>);
using FromFieldType = typename FromDataType::FieldType;
using ToFieldType = typename ToDataType::FieldType;
static Float64 produceTargetFloat64(
Float64 value,
bool need_truncate,
Float64 shift,
Float64 max_f,
const Context & context)
{
if (need_truncate)
{
value *= shift;
value = std::round(value) / shift;
if (value > max_f)
{
context.getDAGContext()->handleOverflowError("cast as real", Errors::Types::Truncated);
value = max_f;
}
if (value < -max_f)
{
context.getDAGContext()->handleOverflowError("cast as real", Errors::Types::Truncated);
value = -max_f;
}
}
if constexpr (to_unsigned)
{
if (value < 0)
{
context.getDAGContext()->handleOverflowError("cast as real", Errors::Types::Truncated);
value = 0;
}
}
return value;
}
template <typename T>
static std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, Float64> toFloat(
const T & value,
bool need_truncate,
Float64 shift,
Float64 max_f,
const Context & context)
{
auto float_value = static_cast<Float64>(value);
return produceTargetFloat64(float_value, need_truncate, shift, max_f, context);
}
template <typename T>
static std::enable_if_t<std::is_floating_point_v<T> || std::is_integral_v<T>, Float64> toFloat(const T & value)
{
return static_cast<Float64>(value);
}
template <typename T>
static Float64 toFloat(const DecimalField<T> & value)
{
return static_cast<Float64>(value);
}
static StringRef getValidFloatPrefix(const StringRef & value)
{
StringRef ret;
ret.data = value.data;
ret.size = 0;
bool saw_dot = false;
bool saw_digit = false;
int e_idx = -1;
int i = 0;
for (; i < static_cast<int>(value.size); i++)
{
char c = ret.data[i];
if (c == '+' || c == '-')
{
if (i != 0 && i != e_idx + 1)
// "1e+1" is valid.
break;
}
else if (c == '.')
{
if (saw_dot || e_idx > 0)
// "1.1." or "1e1.1"
break;
saw_dot = true;
}
else if (c == 'e' || c == 'E')
{
if (!saw_digit)
// "+.e"
break;
if (e_idx != -1)
// "1e5e"
break;
e_idx = i;
}
else if (c < '0' || c > '9')
{
break;
}
else
{
saw_digit = true;
}
}
ret.size = i;
return ret;
}
static Float64 strToFloat(
const StringRef & value,
bool need_truncate,
Float64 shift,
Float64 max_f,
const Context & context)
{
String trim_string = trim(value);
StringRef float_string = getValidFloatPrefix(StringRef(trim_string));
if (trim_string.empty() && value.size != 0)
{
context.getDAGContext()->handleTruncateError("Truncated incorrect DOUBLE value");
return 0.0;
}
if (float_string.size < trim_string.size())
trim_string[float_string.size] = '\0';
Float64 f = strtod(float_string.data, nullptr);
if (f == std::numeric_limits<Float64>::infinity())
{
context.getDAGContext()->handleOverflowError("Truncated incorrect DOUBLE value", Errors::Types::Truncated);
return std::numeric_limits<Float64>::max();
}
if (f == -std::numeric_limits<double>::infinity())
{
context.getDAGContext()->handleOverflowError("Truncated incorrect DOUBLE value", Errors::Types::Truncated);
return -std::numeric_limits<Float64>::max();
}
return produceTargetFloat64(f, need_truncate, shift, max_f, context);
}
static void execute(
Block & block,
const ColumnNumbers & arguments,
size_t result,
bool,
const tipb::FieldType & tp,
const Context & context)
{
size_t size = block.getByPosition(arguments[0]).column->size();
/// NOTICE: Since ToFieldType only can be Float32 or Float64, convert from_value to Float64 and then implicitly cast to ToFieldType is fine.
auto col_to = ColumnVector<ToFieldType>::create(size, 0);
typename ColumnVector<ToFieldType>::Container & vec_to = col_to->getData();
ColumnUInt8::MutablePtr col_null_map_to;
ColumnUInt8::Container * vec_null_map_to [[maybe_unused]] = nullptr;
if constexpr (return_nullable)
{
col_null_map_to = ColumnUInt8::create(size, 0);
vec_null_map_to = &col_null_map_to->getData();
}
if constexpr (IsDecimal<FromFieldType>)
{
/// cast decimal as real
const auto * col_from
= checkAndGetColumn<ColumnDecimal<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
for (size_t i = 0; i < size; ++i)
{
auto & field = (*col_from)[i].template safeGet<DecimalField<FromFieldType>>();
vec_to[i] = toFloat(field);
}
}
else if constexpr (
std::is_same_v<FromDataType, DataTypeMyDateTime> || std::is_same_v<FromDataType, DataTypeMyDate>)
{
/// cast time as real
const auto & col_with_type_and_name = block.getByPosition(arguments[0]);
const auto & type = static_cast<const FromDataType &>(*col_with_type_and_name.type);
const ColumnVector<FromFieldType> * col_from
= checkAndGetColumn<ColumnVector<FromFieldType>>(col_with_type_and_name.column.get());
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
for (size_t i = 0; i < size; i++)
{
if constexpr (std::is_same_v<DataTypeMyDate, FromDataType>)
{
MyDate date(vec_from[i]);
vec_to[i] = toFloat(date.year * 10000 + date.month * 100 + date.day);
}
else
{
MyDateTime date_time(vec_from[i]);
if (type.getFraction() > 0)
vec_to[i] = toFloat(
date_time.year * 10000000000ULL + date_time.month * 100000000ULL + date_time.day * 1000000
+ date_time.hour * 10000 + date_time.minute * 100 + date_time.second
+ date_time.micro_second / 1000000.0);
else
vec_to[i] = toFloat(
date_time.year * 10000000000ULL + date_time.month * 100000000ULL + date_time.day * 1000000
+ date_time.hour * 10000 + date_time.minute * 100 + date_time.second);
}
}
}
else if constexpr (std::is_same_v<FromDataType, DataTypeString>)
{
/// cast string as real
const IColumn * col_from = block.getByPosition(arguments[0]).column.get();
const auto * col_from_string = checkAndGetColumn<ColumnString>(col_from);
const ColumnString::Chars_t * chars = &col_from_string->getChars();
const IColumn::Offsets * offsets = &col_from_string->getOffsets();
size_t current_offset = 0;
bool need_truncate = tp.flen() != -1 && tp.decimal() != -1 && tp.flen() >= tp.decimal();
Float64 shift = 0;
Float64 max_f = 0;
if (need_truncate)
{
shift = std::pow(static_cast<Float64>(10), tp.flen());
max_f = std::pow(static_cast<Float64>(10), tp.flen() - tp.decimal()) - 1.0 / shift;
}
for (size_t i = 0; i < size; i++)
{
size_t next_offset = (*offsets)[i];
size_t string_size = next_offset - current_offset - 1;
StringRef string_value(&(*chars)[current_offset], string_size);
vec_to[i] = strToFloat(string_value, need_truncate, shift, max_f, context);
current_offset = next_offset;
}
}
else if constexpr (std::is_integral_v<FromFieldType> || std::is_floating_point_v<FromFieldType>)
{
/// cast enum/int/real as real
const ColumnVector<FromFieldType> * col_from
= checkAndGetColumn<ColumnVector<FromFieldType>>(block.getByPosition(arguments[0]).column.get());
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();
for (size_t i = 0; i < size; i++)
vec_to[i] = toFloat(vec_from[i]);
}
else
{
throw Exception(
"Illegal column " + block.getByPosition(arguments[0]).column->getName()
+ " for first argument of function tidb_cast",
ErrorCodes::ILLEGAL_COLUMN);
}
if constexpr (return_nullable)
block.getByPosition(result).column = ColumnNullable::create(std::move(col_to), std::move(col_null_map_to));
else
block.getByPosition(result).column = std::move(col_to);
}
};
/// cast int/real/decimal/enum/string/time/string as decimal
// todo TiKV does not check unsigned flag but TiDB checks, currently follow TiKV's code, maybe changed latter
// There are two optimizations in TiDBConvertToDecimal:
// 1. Skip overflow check if possible, such as cast(tiny_int_val as decimal(10, 0)),
// we can skip check overflow, because max_tiny_int(127) < to_max_val(10^9).
// 2. Use appropriate type for multiplication of from_int_val and scale_mul(which is 10^abs(scale_diff)).
// The original implementation always uses Int256, which is very slow.
// The general idea is:
// 1. If from_type_prec + scale_diff <= to_type_prec, we can skip overflow check.
// Because the max value of from type is less than the max value of to type, so no overflow will happen.
// 2. CastInternalType is the int type with minimum prec which satisfies: from_type_prec + scale_diff <= IntPrec<CastInternalType>::prec - 1.
// So on the one hand CastInternalType can hold both from_int_value and the result of multiplication of from_int_val and scale_mul,
// on the other hand the multiplication is as fast as possible.
// NOTE: scale_diff = to_type_scale - from_type_scale.
// NOTE: The above two optimizations only take effects when from type is int/decimal/date/dateimte.
// The logic of cast doesn't care about CastInternalType(Int512) and can_skip_check_overflow(false) at all when from_type is real or string.
template <
typename FromDataType,
typename ToFieldType,
bool return_nullable,
bool can_skip_check_overflow,
typename CastInternalType>
struct TiDBConvertToDecimal
{
using FromFieldType = typename FromDataType::FieldType;
template <typename T, typename U>
static U toTiDBDecimalInternal(
T int_value,
const CastInternalType & max_value,
const CastInternalType & scale_mul,
const Context & context)
{
// int_value is the value that exposes to user. Such as cast(val to decimal), val is the int_value which used by user.
// And val * scale_mul is the scaled_value, which is stored in ColumnDecimal internally.
static_assert(std::is_integral_v<T>);
using UType = typename U::NativeType;
CastInternalType scaled_value = static_cast<CastInternalType>(int_value) * scale_mul;
return handleOverflowErrorForIntAndDecimal<UType>(context, scaled_value, max_value, "cast to decimal");
}
template <typename U>
static U toTiDBDecimal(
MyDateTime & date_time,
const CastInternalType & max_value,
ScaleType from_scale,
ScaleType to_scale,
const CastInternalType & scale_mul,
int fsp,
const Context & context)
{
UInt64 value_without_fsp = date_time.year * 10000000000ULL + date_time.month * 100000000ULL
+ date_time.day * 1000000ULL + date_time.hour * 10000ULL + date_time.minute * 100ULL + date_time.second;
if (fsp > 0)
{
Int128 value = static_cast<Int128>(value_without_fsp) * 1000000 + date_time.micro_second;
Decimal128 decimal(value);
return toTiDBDecimal<Decimal128, U>(decimal, from_scale, max_value, to_scale, scale_mul, context);
}
else
{
return toTiDBDecimalInternal<UInt64, U>(value_without_fsp, max_value, scale_mul, context);
}
}
template <typename U>
static U toTiDBDecimal(
MyDate & date,
const CastInternalType & max_value,
const CastInternalType & scale_mul,
const Context & context)
{
UInt64 value = date.year * 10000 + date.month * 100 + date.day;
return toTiDBDecimalInternal<UInt64, U>(value, max_value, scale_mul, context);
}
template <typename T, typename U>
static std::enable_if_t<std::is_integral_v<T>, U> toTiDBDecimal(
T value,
const CastInternalType & max_value,
const CastInternalType & scale_mul,
const Context & context)
{
if constexpr (std::is_signed_v<T>)
return toTiDBDecimalInternal<T, U>(value, max_value, scale_mul, context);
else
return toTiDBDecimalInternal<UInt64, U>(static_cast<UInt64>(value), max_value, scale_mul, context);
}
template <typename T, typename U>
static std::enable_if_t<std::is_floating_point_v<T>, U> toTiDBDecimal(
T value,
PrecType prec,
ScaleType scale,
const Context & context)
{
using UType = typename U::NativeType;
bool neg = false;
if (value < 0)
{
neg = true;
value = -value;
}
for (ScaleType i = 0; i < scale; i++)
{
value *= 10;
}
auto max_value = DecimalMaxValue::get(prec);
if (value > static_cast<Float64>(max_value))
{
context.getDAGContext()->handleOverflowError("cast real to decimal", Errors::Types::Truncated);
if (!neg)
return static_cast<UType>(max_value);
else
return static_cast<UType>(-max_value);
}
// rounding
T ten_times_value = value * 10;
UType v(value);
Int32 remain = static_cast<Int32>(Int256(ten_times_value) % 10);
if (remain != 0)
context.getDAGContext()->handleTruncateError("cast real as decimal");
if (remain % 10 >= 5)
{
v++;
}
if (neg)
{
v = -v;
}
return v;
}
template <typename T, typename U>
static std::enable_if_t<IsDecimal<T>, U> toTiDBDecimal(
const T & v,
ScaleType v_scale,
const CastInternalType & max_value,