forked from pingcap/tiflash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTiDB.cpp
More file actions
1521 lines (1376 loc) · 47.5 KB
/
TiDB.cpp
File metadata and controls
1521 lines (1376 loc) · 47.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
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.
#include <Common/Decimal.h>
#include <Common/Exception.h>
#include <Common/MyTime.h>
#include <Common/config.h> // For ENABLE_CLARA
#include <Core/Types.h>
#include <DataTypes/DataTypeDecimal.h>
#include <DataTypes/FieldToDataType.h>
#include <IO/Buffer/ReadBufferFromString.h>
#include <Poco/Base64Decoder.h>
#include <Poco/Dynamic/Var.h>
#include <Poco/MemoryStream.h>
#include <Poco/StreamCopier.h>
#include <Poco/StringTokenizer.h>
#include <Storages/MutableSupport.h>
#include <TiDB/Collation/Collator.h>
#include <TiDB/Decode/DatumCodec.h>
#include <TiDB/Decode/JsonBinary.h>
#include <TiDB/Decode/Vector.h>
#include <TiDB/Schema/FullTextIndex.h>
#include <TiDB/Schema/SchemaNameMapper.h>
#include <TiDB/Schema/TiDB.h>
#include <TiDB/Schema/VectorIndex.h>
#include <common/logger_useful.h>
#include <fmt/format.h>
#include <tipb/executor.pb.h>
#include <algorithm>
#include <cmath>
#include <magic_enum.hpp>
#include <string>
#if ENABLE_CLARA
#include <clara_fts/src/tokenizer/mod.rs.h>
#endif
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int INCORRECT_DATA;
} // namespace ErrorCodes
extern const UInt8 TYPE_CODE_LITERAL;
extern const UInt8 LITERAL_NIL;
Field GenDefaultField(const TiDB::ColumnInfo & col_info)
{
switch (col_info.getCodecFlag())
{
case TiDB::CodecFlagNil:
return Field();
case TiDB::CodecFlagBytes:
return Field(String());
case TiDB::CodecFlagDecimal:
{
auto type = createDecimal(col_info.flen, col_info.decimal);
if (checkDecimal<Decimal32>(*type))
return Field(DecimalField<Decimal32>(Decimal32(), col_info.decimal));
else if (checkDecimal<Decimal64>(*type))
return Field(DecimalField<Decimal64>(Decimal64(), col_info.decimal));
else if (checkDecimal<Decimal128>(*type))
return Field(DecimalField<Decimal128>(Decimal128(), col_info.decimal));
else
return Field(DecimalField<Decimal256>(Decimal256(), col_info.decimal));
}
break;
case TiDB::CodecFlagCompactBytes:
return Field(String());
case TiDB::CodecFlagFloat:
return Field(static_cast<Float64>(0));
case TiDB::CodecFlagUInt:
return Field(static_cast<UInt64>(0));
case TiDB::CodecFlagInt:
return Field(static_cast<Int64>(0));
case TiDB::CodecFlagVarInt:
return Field(static_cast<Int64>(0));
case TiDB::CodecFlagVarUInt:
return Field(static_cast<UInt64>(0));
case TiDB::CodecFlagJson:
return TiDB::genJsonNull();
case TiDB::CodecFlagVectorFloat32:
return Field(Array(0));
case TiDB::CodecFlagDuration:
return Field(static_cast<Int64>(0));
default:
throw Exception(
ErrorCodes::LOGICAL_ERROR,
"Not implemented codec flag: {}",
fmt::underlying(col_info.getCodecFlag()));
}
}
} // namespace DB
namespace TiDB
{
using DB::Decimal128;
using DB::Decimal256;
using DB::Decimal32;
using DB::Decimal64;
using DB::DecimalField;
using DB::Exception;
using DB::Field;
using DB::SchemaNameMapper;
// The IndexType defined in TiDB
// https://github.com/pingcap/tidb/blob/84492a9a1e5bff0b4a4256955ab8231975c2dde1/pkg/parser/ast/model.go#L217-L226
enum class IndexType
{
INVALID = 0,
BTREE = 1,
HASH = 2,
RTREE = 3,
HYPO = 4,
VECTOR = 5,
INVERTED = 6,
// Note: HNSW here only for complementary purpose.
// It shall never be used, because TiDB only use it as a parser token and will
// never leak it to the outside.
// HNSW = 7,
};
#if ENABLE_CLARA
FullTextIndexDefinitionPtr parseFullTextIndexFromJSON(const Poco::JSON::Object::Ptr & json)
{
RUNTIME_CHECK(json); // not nullptr
RUNTIME_CHECK_MSG(json->has("parser_type"), "Invalid FullTextIndex definition, missing parser_type");
auto parser_type_field = json->getValue<String>("parser_type");
RUNTIME_CHECK_MSG(
ClaraFTS::supports_tokenizer(parser_type_field),
"Invalid FullTextIndex definition, unsupported parser_type `{}`",
parser_type_field);
return std::make_shared<const FullTextIndexDefinition>(FullTextIndexDefinition{
.parser_type = parser_type_field,
});
}
Poco::JSON::Object::Ptr fullTextIndexToJSON(const FullTextIndexDefinitionPtr & full_text_index)
{
RUNTIME_CHECK(full_text_index != nullptr);
RUNTIME_CHECK(ClaraFTS::supports_tokenizer(full_text_index->parser_type));
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("parser_type", full_text_index->parser_type);
return json;
}
#endif
VectorIndexDefinitionPtr parseVectorIndexFromJSON(const Poco::JSON::Object::Ptr & json)
{
assert(json); // not nullptr
auto dimension = json->getValue<UInt64>("dimension");
RUNTIME_CHECK(dimension > 0 && dimension <= TiDB::MAX_VECTOR_DIMENSION, dimension); // Just a protection
tipb::VectorDistanceMetric distance_metric = tipb::VectorDistanceMetric::INVALID_DISTANCE_METRIC;
auto distance_metric_field = json->getValue<String>("distance_metric");
RUNTIME_CHECK_MSG(
tipb::VectorDistanceMetric_Parse(distance_metric_field, &distance_metric),
"invalid distance_metric of vector index, {}",
distance_metric_field);
RUNTIME_CHECK(distance_metric != tipb::VectorDistanceMetric::INVALID_DISTANCE_METRIC);
return std::make_shared<const VectorIndexDefinition>(VectorIndexDefinition{
// TODO: To be removed. We will not expose real algorithm in future.
.kind = tipb::VectorIndexKind::HNSW,
.dimension = dimension,
.distance_metric = distance_metric,
});
}
Poco::JSON::Object::Ptr vectorIndexToJSON(const VectorIndexDefinitionPtr & vector_index)
{
assert(vector_index != nullptr);
RUNTIME_CHECK(vector_index->kind != tipb::VectorIndexKind::INVALID_INDEX_KIND);
RUNTIME_CHECK(vector_index->distance_metric != tipb::VectorDistanceMetric::INVALID_DISTANCE_METRIC);
Poco::JSON::Object::Ptr vector_index_json = new Poco::JSON::Object();
vector_index_json->set("kind", tipb::VectorIndexKind_Name(vector_index->kind));
vector_index_json->set("dimension", vector_index->dimension);
vector_index_json->set("distance_metric", tipb::VectorDistanceMetric_Name(vector_index->distance_metric));
return vector_index_json;
}
InvertedIndexDefinitionPtr parseInvertedIndexFromJSON(IndexType index_type, const Poco::JSON::Object::Ptr & json)
{
assert(json); // not nullptr
RUNTIME_CHECK(index_type == IndexType::INVERTED);
bool is_signed = json->getValue<bool>("is_signed");
auto type_size = json->getValue<UInt8>("type_size");
RUNTIME_CHECK(type_size > 0 && type_size <= sizeof(UInt64), type_size); // Just a protection
return std::make_shared<const InvertedIndexDefinition>(InvertedIndexDefinition{
.is_signed = is_signed,
.type_size = type_size,
});
}
Poco::JSON::Object::Ptr invertedIndexToJSON(const InvertedIndexDefinitionPtr & inverted_index)
{
assert(inverted_index != nullptr);
RUNTIME_CHECK(inverted_index->type_size > 0 && inverted_index->type_size <= sizeof(UInt64));
Poco::JSON::Object::Ptr inverted_index_json = new Poco::JSON::Object();
inverted_index_json->set("is_signed", inverted_index->is_signed);
inverted_index_json->set("type_size", inverted_index->type_size);
return inverted_index_json;
}
////////////////////////
////// ColumnInfo //////
////////////////////////
ColumnInfo::ColumnInfo(Poco::JSON::Object::Ptr json)
{
deserialize(json);
}
#define TRY_CATCH_DEFAULT_VALUE_TO_FIELD(try_block) \
try \
{ \
try_block \
} \
catch (...) \
{ \
return DB::GenDefaultField(*this); \
}
bool ColumnInfo::hasOriDefaultValue() const
{
return !origin_default_value.isEmpty() || !origin_default_bit_value.isEmpty();
}
Field ColumnInfo::defaultValueToField() const
{
const auto & value = origin_default_value;
const auto & bit_value = origin_default_bit_value;
if (value.isEmpty() && bit_value.isEmpty())
{
if (hasNotNullFlag())
return DB::GenDefaultField(*this);
return Field();
}
switch (tp)
{
// Integer Type.
// In c++, cast a unsigned integer to signed integer will not change the value.
// like 9223372036854775808 which is larger than the maximum value of Int64,
// static_cast<UInt64>(static_cast<Int64>(9223372036854775808)) == 9223372036854775808
// so we don't need consider unsigned here.
case TypeTiny:
case TypeShort:
case TypeLong:
case TypeLongLong:
case TypeInt24:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
try
{
return value.convert<Int64>();
}
catch (...)
{
// due to https://github.com/pingcap/tidb/issues/34881
// we do this to avoid exception in older version of TiDB.
return static_cast<Int64>(std::llround(value.convert<double>()));
}
});
case TypeBit:
{
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
// When we got bit_value from tipb, we have decoded it.
if (auto is_int = bit_value.isInteger(); is_int)
return bit_value.convert<UInt64>();
return getBitValue(bit_value.convert<String>());
});
}
// Floating type.
case TypeFloat:
case TypeDouble:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({ return value.convert<double>(); });
case TypeDate:
case TypeDatetime:
case TypeTimestamp:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
// When we got value from tipb, we have decoded it.
if (auto is_int = value.isInteger(); is_int)
return value.convert<UInt64>();
return DB::parseMyDateTime(value.convert<String>());
});
case TypeVarchar:
case TypeTinyBlob:
case TypeMediumBlob:
case TypeLongBlob:
case TypeBlob:
case TypeVarString:
case TypeString:
{
auto v = value.convert<String>();
if (hasBinaryFlag())
{
// For some binary column(like varchar(20)), we have to pad trailing zeros according to the specified type length.
// User may define default value `0x1234` for a `BINARY(4)` column, TiDB stores it in a string "\u12\u34" (sized 2).
// But it actually means `0x12340000`.
// And for some binary column(like longblob), we do not need to pad trailing zeros.
// And the `Flen` is set to -1, therefore we need to check `Flen >= 0` here.
if (Int32 vlen = v.length(); flen >= 0 && vlen < flen)
v.append(flen - vlen, '\0');
}
return v;
}
case TypeJSON:
// JSON can't have a default value
return genJsonNull();
case TypeEnum:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({ return getEnumIndex(value.convert<String>()); });
case TypeNull:
return Field();
case TypeDecimal:
case TypeNewDecimal:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
auto text = value.convert<String>();
if (text.empty())
return DB::GenDefaultField(*this);
return getDecimalValue(text);
});
case TypeTime:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
// When we got value from tipb, we have decoded it.
if (auto is_int = value.isInteger(); is_int)
return value.convert<UInt64>();
return getTimeValue(value.convert<String>());
});
case TypeYear:
// Never throw exception here, do not use TRY_CATCH_DEFAULT_VALUE_TO_FIELD
return getYearValue(value.convert<String>());
case TypeSet:
TRY_CATCH_DEFAULT_VALUE_TO_FIELD({
// When we got value from tipb, we have decoded it.
if (auto is_int = value.isInteger(); is_int)
return value.convert<UInt64>();
return getSetValue(value.convert<String>());
});
case TypeTiDBVectorFloat32:
return genVectorFloat32Empty();
default:
throw Exception("Have not processed type: " + std::to_string(tp));
}
return Field();
}
#undef TRY_CATCH_DEFAULT_VALUE_TO_FIELD
DB::Field ColumnInfo::getDecimalValue(const String & decimal_text) const
{
DB::ReadBufferFromString buffer(decimal_text);
auto precision = flen;
auto scale = decimal;
auto type = DB::createDecimal(precision, scale);
if (DB::checkDecimal<Decimal32>(*type))
{
DB::Decimal32 result;
DB::readDecimalText(result, buffer, precision, scale);
return DecimalField<Decimal32>(result, scale);
}
else if (DB::checkDecimal<Decimal64>(*type))
{
DB::Decimal64 result;
DB::readDecimalText(result, buffer, precision, scale);
return DecimalField<Decimal64>(result, scale);
}
else if (DB::checkDecimal<Decimal128>(*type))
{
DB::Decimal128 result;
DB::readDecimalText(result, buffer, precision, scale);
return DecimalField<Decimal128>(result, scale);
}
else
{
DB::Decimal256 result;
DB::readDecimalText(result, buffer, precision, scale);
return DecimalField<Decimal256>(result, scale);
}
}
// FIXME it still has bug: https://github.com/pingcap/tidb/issues/11435
Int64 ColumnInfo::getEnumIndex(const String & enum_id_or_text) const
{
const auto * collator = ITiDBCollator::getCollator(collate.isEmpty() ? "binary" : collate.convert<String>());
if (!collator)
// TODO: if new collation is enabled, should use "utf8mb4_bin"
collator = ITiDBCollator::getCollator("binary");
for (const auto & elem : elems)
{
if (collator->compareFastPath(
elem.first.data(),
elem.first.size(),
enum_id_or_text.data(),
enum_id_or_text.size()) //
== 0)
{
return elem.second;
}
}
return std::stoi(enum_id_or_text);
}
UInt64 ColumnInfo::getSetValue(const String & set_str) const
{
const auto * collator = ITiDBCollator::getCollator(collate.isEmpty() ? "binary" : collate.convert<String>());
if (!collator)
// TODO: if new collation is enabled, should use "utf8mb4_bin"
collator = ITiDBCollator::getCollator("binary");
std::string sort_key_container;
Poco::StringTokenizer string_tokens(set_str, ",");
std::set<String> marked;
for (const auto & s : string_tokens)
marked.insert(collator->sortKeyFastPath(s.data(), s.length(), sort_key_container).toString());
UInt64 value = 0;
for (size_t i = 0; i < elems.size(); i++)
{
String key = collator->sortKeyFastPath(elems.at(i).first.data(), elems.at(i).first.length(), sort_key_container)
.toString();
auto it = marked.find(key);
if (it != marked.end())
{
value |= 1ULL << i;
marked.erase(it);
}
}
if (marked.empty())
return value;
return 0;
}
Int64 ColumnInfo::getTimeValue(const String & time_str)
{
const static int64_t fractional_seconds_multiplier[]
= {1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1};
bool negative = time_str[0] == '-';
Poco::StringTokenizer second_and_fsp(time_str, ".");
Poco::StringTokenizer string_tokens(second_and_fsp[0], ":");
Int64 ret = 0;
for (auto const & s : string_tokens)
ret = ret * 60 + std::abs(std::stoi(s));
Int32 fs_length = 0;
Int64 fs_value = 0;
if (second_and_fsp.count() == 2)
{
fs_length = second_and_fsp[1].length();
fs_value = std::stol(second_and_fsp[1]);
}
ret = ret * fractional_seconds_multiplier[0] + fs_value * fractional_seconds_multiplier[fs_length];
return negative ? -ret : ret;
}
Int64 ColumnInfo::getYearValue(const String & val)
{
// make sure the year is non-negative integer
if (val.empty() || !std::all_of(val.begin(), val.end(), ::isdigit))
return 0;
Int64 year = std::stol(val);
if (0 < year && year < 70)
return 2000 + year;
if (70 <= year && year < 100)
return 1900 + year;
if (year == 0 && val.length() <= 2)
return 2000;
return year;
}
UInt64 ColumnInfo::getBitValue(const String & val)
{
// The `default_bit` is a base64 encoded, big endian byte array.
Poco::MemoryInputStream istr(val.data(), val.size());
Poco::Base64Decoder decoder(istr);
std::string decoded;
Poco::StreamCopier::copyToString(decoder, decoded);
UInt64 result = 0;
for (auto c : decoded)
{
result = result << 8 | c;
}
return result;
}
Poco::JSON::Object::Ptr ColumnInfo::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("id", id);
Poco::JSON::Object::Ptr name_json = new Poco::JSON::Object();
name_json->set("O", name);
name_json->set("L", name);
json->set("name", name_json);
json->set("offset", offset);
if (!origin_default_value.isEmpty())
json->set("origin_default", origin_default_value);
if (!default_value.isEmpty())
json->set("default", default_value);
if (!default_bit_value.isEmpty())
json->set("default_bit", default_bit_value);
if (!origin_default_bit_value.isEmpty())
json->set("origin_default_bit", origin_default_bit_value);
{
// "type" field
Poco::JSON::Object::Ptr tp_json = new Poco::JSON::Object();
tp_json->set("Tp", static_cast<Int32>(tp));
tp_json->set("Flag", flag);
tp_json->set("Flen", flen);
tp_json->set("Decimal", decimal);
if (!charset.isEmpty())
tp_json->set("Charset", charset);
if (!collate.isEmpty())
tp_json->set("Collate", collate);
if (!elems.empty())
{
Poco::JSON::Array::Ptr elem_arr = new Poco::JSON::Array();
for (const auto & elem : elems)
elem_arr->add(elem.first);
tp_json->set("Elems", elem_arr);
}
json->set("type", tp_json);
}
json->set("state", static_cast<Int32>(state));
#ifndef NDEBUG
// Check stringify in Debug mode
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (ColumnInfo): " + e.displayText(),
DB::Exception(e));
}
void ColumnInfo::deserialize(Poco::JSON::Object::Ptr json)
try
{
id = json->getValue<ColumnID>("id");
name = json->getObject("name")->getValue<String>("L");
offset = json->getValue<Int32>("offset");
if (!json->isNull("origin_default"))
origin_default_value = json->get("origin_default");
if (!json->isNull("default"))
default_value = json->get("default");
if (!json->isNull("default_bit"))
default_bit_value = json->get("default_bit");
if (!json->isNull("origin_default_bit"))
origin_default_bit_value = json->get("origin_default_bit");
{
// type
auto type_json = json->getObject("type");
tp = static_cast<TP>(type_json->getValue<Int32>("Tp"));
flag = type_json->getValue<UInt32>("Flag");
flen = type_json->getValue<Int64>("Flen");
decimal = type_json->getValue<Int64>("Decimal");
if (!type_json->isNull("Elems"))
{
auto elems_arr = type_json->getArray("Elems");
size_t elems_size = elems_arr->size();
for (size_t i = 1; i <= elems_size; i++)
{
elems.push_back(std::make_pair(elems_arr->getElement<String>(i - 1), static_cast<Int16>(i)));
}
}
/// need to do this check for forward compatibility
if (!type_json->isNull("Charset"))
charset = type_json->get("Charset");
/// need to do this check for forward compatibility
if (!type_json->isNull("Collate"))
collate = type_json->get("Collate");
}
state = static_cast<SchemaState>(json->getValue<Int32>("state"));
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (ColumnInfo): " + e.displayText(),
DB::Exception(e));
}
///////////////////////////
////// PartitionInfo //////
///////////////////////////
PartitionDefinition::PartitionDefinition(Poco::JSON::Object::Ptr json)
{
deserialize(json);
}
Poco::JSON::Object::Ptr PartitionDefinition::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("id", id);
Poco::JSON::Object::Ptr name_json = new Poco::JSON::Object();
name_json->set("O", name);
name_json->set("L", name);
json->set("name", name_json);
#ifndef NDEBUG
// Check stringify in Debug mode
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (PartitionDef): " + e.displayText(),
DB::Exception(e));
}
void PartitionDefinition::deserialize(Poco::JSON::Object::Ptr json)
try
{
id = json->getValue<TableID>("id");
name = json->getObject("name")->getValue<String>("L");
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (PartitionDefinition): " + e.displayText(),
DB::Exception(e));
}
PartitionInfo::PartitionInfo(Poco::JSON::Object::Ptr json)
{
deserialize(json);
}
Poco::JSON::Object::Ptr PartitionInfo::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("type", static_cast<Int32>(type));
json->set("expr", expr);
json->set("enable", enable);
json->set("num", num);
Poco::JSON::Array::Ptr def_arr = new Poco::JSON::Array();
for (const auto & part_def : definitions)
{
def_arr->add(part_def.getJSONObject());
}
json->set("definitions", def_arr);
#ifndef NDEBUG
// Check stringify in Debug mode
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (PartitionInfo): " + e.displayText(),
DB::Exception(e));
}
void PartitionInfo::deserialize(Poco::JSON::Object::Ptr json)
try
{
type = static_cast<PartitionType>(json->getValue<Int32>("type"));
expr = json->getValue<String>("expr");
enable = json->getValue<bool>("enable");
auto defs_json = json->getArray("definitions");
definitions.clear();
std::unordered_set<TableID> part_id_set;
for (size_t i = 0; i < defs_json->size(); i++)
{
PartitionDefinition definition(defs_json->getObject(i));
definitions.emplace_back(definition);
part_id_set.emplace(definition.id);
}
/// Treat `adding_definitions` and `dropping_definitions` as the normal `definitions`
/// in TiFlash. Because TiFlash need to create the physical IStorage instance
/// to handle the data on those partitions during DDL.
auto add_defs_json = json->getArray("adding_definitions");
if (!add_defs_json.isNull())
{
for (size_t i = 0; i < add_defs_json->size(); i++)
{
PartitionDefinition definition(add_defs_json->getObject(i));
if (part_id_set.count(definition.id) == 0)
{
definitions.emplace_back(definition);
part_id_set.emplace(definition.id);
}
}
}
auto drop_defs_json = json->getArray("dropping_definitions");
if (!drop_defs_json.isNull())
{
for (size_t i = 0; i < drop_defs_json->size(); i++)
{
PartitionDefinition definition(drop_defs_json->getObject(i));
if (part_id_set.count(definition.id) == 0)
{
definitions.emplace_back(definition);
part_id_set.emplace(definition.id);
}
}
}
num = json->getValue<UInt64>("num");
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (PartitionInfo): " + e.displayText(),
DB::Exception(e));
}
////////////////////////////////
////// TiFlashReplicaInfo //////
////////////////////////////////
Poco::JSON::Object::Ptr TiFlashReplicaInfo::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("Count", count);
if (available)
{
json->set("Available", *available);
}
#ifndef NDEBUG
// Check stringify in Debug mode
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__)
+ ": Serialize TiDB schema JSON failed (TiFlashReplicaInfo): " + e.displayText(),
DB::Exception(e));
}
void TiFlashReplicaInfo::deserialize(Poco::JSON::Object::Ptr & json)
try
{
count = json->getValue<UInt64>("Count");
if (json->has("Available"))
{
available = json->getValue<bool>("Available");
}
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
String(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (TiFlashReplicaInfo): " + e.displayText(),
DB::Exception(e));
}
////////////////////
////// DBInfo //////
////////////////////
String DBInfo::serialize() const
try
{
std::stringstream buf;
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("id", id);
json->set("keyspace_id", keyspace_id);
Poco::JSON::Object::Ptr name_json = new Poco::JSON::Object();
name_json->set("O", name);
name_json->set("L", name);
json->set("db_name", name_json);
json->set("charset", charset);
json->set("collate", collate);
json->set("state", static_cast<Int32>(state));
json->stringify(buf);
return buf.str();
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (DBInfo): " + e.displayText(),
DB::Exception(e));
}
void DBInfo::deserialize(const String & json_str)
try
{
Poco::JSON::Parser parser;
Poco::Dynamic::Var result = parser.parse(json_str);
auto obj = result.extract<Poco::JSON::Object::Ptr>();
id = obj->getValue<DatabaseID>("id");
if (obj->has("keyspace_id"))
{
keyspace_id = obj->getValue<KeyspaceID>("keyspace_id");
}
name = obj->get("db_name").extract<Poco::JSON::Object::Ptr>()->get("L").convert<String>();
charset = obj->get("charset").convert<String>();
collate = obj->get("collate").convert<String>();
state = static_cast<SchemaState>(obj->getValue<Int32>("state"));
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (DBInfo): " + e.displayText()
+ ", json: " + json_str,
DB::Exception(e));
}
///////////////////////
/// IndexColumnInfo ///
///////////////////////
IndexColumnInfo::IndexColumnInfo(Poco::JSON::Object::Ptr json)
: length(0)
, offset(0)
{
deserialize(json);
}
Poco::JSON::Object::Ptr IndexColumnInfo::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
Poco::JSON::Object::Ptr name_json = new Poco::JSON::Object();
name_json->set("O", name);
name_json->set("L", name);
json->set("name", name_json);
json->set("offset", offset);
json->set("length", length);
#ifndef NDEBUG
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (IndexColumnInfo): " + e.displayText(),
DB::Exception(e));
}
void IndexColumnInfo::deserialize(Poco::JSON::Object::Ptr json)
try
{
name = json->getObject("name")->getValue<String>("L");
offset = json->getValue<Int32>("offset");
length = json->getValue<Int32>("length");
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Parse TiDB schema JSON failed (IndexColumnInfo): " + e.displayText(),
DB::Exception(e));
}
///////////////////////
////// IndexInfo //////
///////////////////////
IndexInfo::IndexInfo(Poco::JSON::Object::Ptr json)
{
deserialize(json);
}
Poco::JSON::Object::Ptr IndexInfo::getJSONObject() const
try
{
Poco::JSON::Object::Ptr json = new Poco::JSON::Object();
json->set("id", id);
Poco::JSON::Object::Ptr idx_name_json = new Poco::JSON::Object();
idx_name_json->set("O", idx_name);
idx_name_json->set("L", idx_name);
json->set("idx_name", idx_name_json);
Poco::JSON::Array::Ptr cols_array = new Poco::JSON::Array();
for (const auto & col : idx_cols)
{
auto col_obj = col.getJSONObject();
cols_array->add(col_obj);
}
json->set("idx_cols", cols_array);
json->set("state", static_cast<Int32>(state));
json->set("index_type", index_type);
json->set("is_unique", is_unique);
json->set("is_primary", is_primary);
json->set("is_invisible", is_invisible);
json->set("is_global", is_global);
if (vector_index)
{
json->set("vector_index", vectorIndexToJSON(vector_index));
}
else if (inverted_index)
{
json->set("inverted_index", invertedIndexToJSON(inverted_index));
}
#if ENABLE_CLARA
else if (full_text_index)
{
json->set("full_text_index", fullTextIndexToJSON(full_text_index));
}
#endif
#ifndef NDEBUG
std::stringstream str;
json->stringify(str);
#endif
return json;
}
catch (const Poco::Exception & e)
{
throw DB::Exception(
std::string(__PRETTY_FUNCTION__) + ": Serialize TiDB schema JSON failed (IndexInfo): " + e.displayText(),
DB::Exception(e));
}
void IndexInfo::deserialize(Poco::JSON::Object::Ptr json)
try
{
id = json->getValue<Int64>("id");
idx_name = json->getObject("idx_name")->getValue<String>("L");
auto cols_array = json->getArray("idx_cols");
idx_cols.clear();
if (!cols_array.isNull())
{
for (size_t i = 0; i < cols_array->size(); i++)
{
auto col_json = cols_array->getObject(i);
IndexColumnInfo column_info(col_json);
idx_cols.emplace_back(column_info);
}
}
state = static_cast<SchemaState>(json->getValue<Int32>("state"));
index_type = json->getValue<Int32>("index_type");
is_unique = json->getValue<bool>("is_unique");
is_primary = json->getValue<bool>("is_primary");
if (json->has("is_invisible"))
is_invisible = json->getValue<bool>("is_invisible");
if (json->has("is_global"))
is_global = json->getValue<bool>("is_global");
if (auto vector_index_json = json->getObject("vector_index"); vector_index_json)
{
RUNTIME_CHECK(static_cast<IndexType>(index_type) == IndexType::VECTOR);
vector_index = parseVectorIndexFromJSON(vector_index_json);