-
Notifications
You must be signed in to change notification settings - Fork 411
/
SchemaBuilder.cpp
1787 lines (1633 loc) · 67.6 KB
/
SchemaBuilder.cpp
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/Exception.h>
#include <Common/FailPoint.h>
#include <Common/FmtUtils.h>
#include <Common/TiFlashException.h>
#include <Common/TiFlashMetrics.h>
#include <Common/setThreadName.h>
#include <Core/NamesAndTypes.h>
#include <DataTypes/DataTypeString.h>
#include <Databases/DatabaseTiFlash.h>
#include <Debug/MockSchemaGetter.h>
#include <Debug/MockSchemaNameMapper.h>
#include <IO/FileProvider/FileProvider.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Context.h>
#include <Interpreters/InterpreterCreateQuery.h>
#include <Interpreters/InterpreterRenameQuery.h>
#include <Parsers/ASTCreateQuery.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTRenameQuery.h>
#include <Parsers/ParserCreateQuery.h>
#include <Parsers/parseQuery.h>
#include <Storages/AlterCommands.h>
#include <Storages/IManageableStorage.h>
#include <Storages/KVStore/TMTContext.h>
#include <Storages/MutableSupport.h>
#include <TiDB/Decode/TypeMapping.h>
#include <TiDB/Schema/SchemaBuilder.h>
#include <TiDB/Schema/SchemaNameMapper.h>
#include <TiDB/Schema/TiDB.h>
#include <common/defines.h>
#include <common/logger_useful.h>
#include <fmt/format.h>
#include <boost/algorithm/string/join.hpp>
#include <magic_enum.hpp>
#include <mutex>
#include <string_view>
#include <tuple>
#include <unordered_set>
namespace DB
{
using namespace TiDB;
namespace ErrorCodes
{
extern const int DDL_ERROR;
extern const int SYNTAX_ERROR;
} // namespace ErrorCodes
namespace FailPoints
{
extern const char random_ddl_fail_when_rename_partitions[];
} // namespace FailPoints
bool isReservedDatabase(Context & context, const String & database_name)
{
return context.getTMTContext().getIgnoreDatabases().count(database_name) > 0;
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyCreateTable(
DatabaseID database_id,
TableID table_id,
std::string_view action)
{
TableInfoPtr table_info;
bool get_by_mvcc = false;
std::tie(table_info, get_by_mvcc) = getter.getTableInfoAndCheckMvcc(database_id, table_id);
if (table_info == nullptr)
{
LOG_INFO(
log,
"table is not exist in TiKV, may have been dropped, applyCreateTable is ignored, database_id={} "
"table_id={} action={}",
database_id,
table_id,
action);
return;
}
table_id_map.emplaceTableID(table_id, database_id);
LOG_DEBUG(
log,
"register table to table_id_map, database_id={} table_id={} action={}",
database_id,
table_id,
action);
// non partition table, done
if (!table_info->isLogicalPartitionTable())
{
return;
}
// If table is partition table, we will create the Storage instance for the logical table
// here (and store the table info to local).
// Because `applyPartitionDiffOnLogicalTable` need the logical table for comparing
// the latest partitioning and the local partitioning in table info to apply the changes.
applyCreateStorageInstance(database_id, table_info, get_by_mvcc, action);
// Register the partition_id -> logical_table_id mapping
for (const auto & part_def : table_info->partition.definitions)
{
LOG_DEBUG(
log,
"register table to table_id_map for partition table, database_id={} logical_table_id={} "
"physical_table_id={} action={}",
database_id,
table_id,
part_def.id,
action);
table_id_map.emplacePartitionTableID(part_def.id, table_id);
}
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyExchangeTablePartition(const SchemaDiff & diff)
{
if (diff.old_table_id == diff.table_id && diff.old_schema_id == diff.schema_id)
{
// Only internal changes in non-partitioned table, not affecting TiFlash
LOG_DEBUG(
log,
"Table is going to be exchanged, skipping for now. database_id={} table_id={}",
diff.schema_id,
diff.table_id);
return;
}
if (diff.affected_opts.empty())
{
throw TiFlashException(
Errors::DDL::Internal,
"Invalid exchange partition schema diff without affected_opts, affected_opts_size={}",
diff.affected_opts.size());
}
/// `ALTER TABLE partition_table EXCHANGE PARTITION partition_name WITH TABLE non_partition_table`
/// Table_id in diff is the partition id of which will be exchanged
/// Schema_id in diff is the non-partition table's schema id
/// Old_table_id in diff is the non-partition table's table id
/// Table_id in diff.affected_opts[0] is the table id of the partition table
/// Schema_id in diff.affected_opts[0] is the schema id of the partition table
const auto non_partition_database_id = diff.old_schema_id;
const auto non_partition_table_id = diff.old_table_id;
const auto partition_database_id = diff.affected_opts[0].schema_id;
const auto partition_logical_table_id = diff.affected_opts[0].table_id;
const auto partition_physical_table_id = diff.table_id;
LOG_INFO(
log,
"Execute exchange partition begin. database_id={} table_id={} part_database_id={} part_logical_table_id={}"
" physical_table_id={}",
non_partition_database_id,
non_partition_table_id,
partition_database_id,
partition_logical_table_id,
partition_physical_table_id);
GET_METRIC(tiflash_schema_internal_ddl_count, type_exchange_partition).Increment();
table_id_map.exchangeTablePartition(
non_partition_database_id,
non_partition_table_id,
partition_database_id,
partition_logical_table_id,
partition_physical_table_id);
if (non_partition_database_id != partition_database_id)
{
// Rename old non-partition table belonging new database. Now it should be belong to
// the database of partition table.
auto & tmt_context = context.getTMTContext();
do
{
// skip if the instance is not created
auto storage = tmt_context.getStorages().get(keyspace_id, non_partition_table_id);
if (storage == nullptr)
{
LOG_INFO(
log,
"ExchangeTablePartition: non_partition_table instance is not created in TiFlash"
", rename is ignored, table_id={}",
non_partition_table_id);
break;
}
auto new_table_info = getter.getTableInfo(partition_database_id, partition_logical_table_id);
if (unlikely(new_table_info == nullptr))
{
LOG_INFO(
log,
"ExchangeTablePartition: part_logical_table table is not exist in TiKV, rename is ignored,"
" table_id={}",
partition_logical_table_id);
break;
}
String new_db_display_name = tryGetDatabaseDisplayNameFromLocal(partition_database_id);
auto part_table_info = new_table_info->producePartitionTableInfo(non_partition_table_id, name_mapper);
applyRenamePhysicalTable(partition_database_id, new_db_display_name, *part_table_info, storage);
} while (false);
// Rename the exchanged partition table belonging new database. Now it should belong to
// the database of non-partition table
do
{
// skip if the instance is not created
auto storage = tmt_context.getStorages().get(keyspace_id, partition_physical_table_id);
if (storage == nullptr)
{
LOG_INFO(
log,
"ExchangeTablePartition: partition_physical_table instance is not created in TiFlash"
", rename is ignored, table_id={}",
partition_physical_table_id);
break;
}
auto new_table_info = getter.getTableInfo(non_partition_database_id, partition_physical_table_id);
if (unlikely(new_table_info == nullptr))
{
LOG_INFO(
log,
"ExchangeTablePartition: partition_physical_table is not exist in TiKV, rename is ignored,"
" table_id={}",
partition_physical_table_id);
break;
}
String new_db_display_name = tryGetDatabaseDisplayNameFromLocal(non_partition_database_id);
applyRenamePhysicalTable(non_partition_database_id, new_db_display_name, *new_table_info, storage);
} while (false);
}
LOG_INFO(
log,
"Execute exchange partition end. database_id={} table_id={} part_database_id={} part_logical_table_id={}"
" physical_table_id={}",
non_partition_database_id,
non_partition_table_id,
partition_database_id,
partition_logical_table_id,
partition_physical_table_id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyDiff(const SchemaDiff & diff)
{
LOG_TRACE(log, "applyDiff accept type={}", magic_enum::enum_name(diff.type));
switch (diff.type)
{
case SchemaActionType::CreateSchema:
{
applyCreateDatabase(diff.schema_id);
break;
}
case SchemaActionType::DropSchema:
{
applyDropDatabase(diff.schema_id);
break;
}
case SchemaActionType::ActionRecoverSchema:
{
applyRecoverDatabase(diff.schema_id);
break;
}
case SchemaActionType::CreateTables:
{
/// Because we can't ensure set tiflash replica always be finished earlier than insert actions,
/// so we have to update table_id_map when create table.
/// and the table will not be created physically here.
for (auto && opt : diff.affected_opts)
applyCreateTable(opt.schema_id, opt.table_id, magic_enum::enum_name(diff.type));
break;
}
case SchemaActionType::RenameTables:
{
for (auto && opt : diff.affected_opts)
applyRenameTable(opt.schema_id, opt.table_id);
break;
}
case SchemaActionType::CreateTable:
{
/// Because we can't ensure set tiflash replica is earlier than insert,
/// so we have to update table_id_map when create table.
/// the table will not be created physically here.
applyCreateTable(diff.schema_id, diff.table_id, magic_enum::enum_name(diff.type));
break;
}
case SchemaActionType::RecoverTable:
{
applyRecoverTable(diff.schema_id, diff.table_id);
break;
}
case SchemaActionType::DropTable:
case SchemaActionType::DropView:
{
applyDropTable(diff.schema_id, diff.table_id, magic_enum::enum_name(diff.type));
break;
}
case SchemaActionType::TruncateTable:
{
applyCreateTable(diff.schema_id, diff.table_id, magic_enum::enum_name(diff.type));
applyDropTable(diff.schema_id, diff.old_table_id, magic_enum::enum_name(diff.type));
break;
}
case SchemaActionType::RenameTable:
{
applyRenameTable(diff.schema_id, diff.table_id);
break;
}
case SchemaActionType::AddTablePartition:
case SchemaActionType::DropTablePartition:
case SchemaActionType::TruncateTablePartition:
case SchemaActionType::ActionReorganizePartition:
{
applyPartitionDiff(diff.schema_id, diff.table_id);
break;
}
case SchemaActionType::ActionAlterTablePartitioning:
case SchemaActionType::ActionRemovePartitioning:
{
if (diff.table_id == diff.old_table_id)
{
/// Only internal additions of new partitions
applyPartitionDiff(diff.schema_id, diff.table_id);
}
else
{
// Create the new table.
// If the new table is a partition table, this will also overwrite
// the partition id mapping to the new logical table
applyCreateTable(diff.schema_id, diff.table_id, magic_enum::enum_name(diff.type));
// Drop the old table. if the previous partitions of the old table are
// not mapping to the old logical table now, they will not be removed.
applyDropTable(diff.schema_id, diff.old_table_id, magic_enum::enum_name(diff.type));
}
break;
}
case SchemaActionType::ExchangeTablePartition:
{
applyExchangeTablePartition(diff);
break;
}
case SchemaActionType::SetTiFlashReplica:
case SchemaActionType::UpdateTiFlashReplicaStatus:
{
applySetTiFlashReplica(diff.schema_id, diff.table_id);
break;
}
default:
{
if (diff.type < SchemaActionType::MaxRecognizedType)
{
LOG_INFO(log, "Ignore change type: {}, diff_version={}", magic_enum::enum_name(diff.type), diff.version);
}
else
{
// >= SchemaActionType::MaxRecognizedType
// log down the Int8 value directly
LOG_ERROR(log, "Unsupported change type: {}, diff_version={}", fmt::underlying(diff.type), diff.version);
}
break;
}
}
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applySetTiFlashReplica(DatabaseID database_id, TableID table_id)
{
auto table_info = getter.getTableInfo(database_id, table_id);
if (unlikely(table_info == nullptr))
{
LOG_WARNING(log, "table is not exist in TiKV, applySetTiFlashReplica is ignored, table_id={}", table_id);
return;
}
auto & tmt_context = context.getTMTContext();
if (table_info->replica_info.count == 0)
{
// Replicat number is to 0, mark the table as tombstone in TiFlash
auto storage = tmt_context.getStorages().get(keyspace_id, table_info->id);
if (unlikely(storage == nullptr))
{
LOG_ERROR(
log,
"Storage instance is not exist in TiFlash, applySetTiFlashReplica is ignored, table_id={}",
table_id);
return;
}
applyDropTable(database_id, table_id, "SetTiFlashReplica-0");
return;
}
assert(table_info->replica_info.count != 0);
// Replica number is set to non-zero, create the storage if not exists.
auto action = fmt::format("SetTiFlashReplica-{}", table_info->replica_info.count);
auto storage = tmt_context.getStorages().get(keyspace_id, table_info->id);
if (storage == nullptr)
{
if (!table_id_map.tableIDInDatabaseIdMap(table_id))
{
applyCreateTable(database_id, table_id, action);
}
return;
}
// Recover the table if tombstone
if (storage->isTombstone())
{
applyRecoverLogicalTable(database_id, table_info, action);
return;
}
updateTiFlashReplicaNumOnStorage(database_id, table_id, storage, table_info);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::updateTiFlashReplicaNumOnStorage(
DatabaseID database_id,
TableID table_id,
const ManageableStoragePtr & storage,
const TiDB::TableInfoPtr & table_info)
{
auto local_logical_storage_table_info = storage->getTableInfo(); // copy
// Check whether replica_count and available changed
if (const auto & local_logical_storage_replica_info = local_logical_storage_table_info.replica_info;
local_logical_storage_replica_info.count == table_info->replica_info.count
&& local_logical_storage_replica_info.available == table_info->replica_info.available)
{
return; // nothing changed
}
size_t old_replica_count = 0;
size_t new_replica_count = 0;
if (table_info->isLogicalPartitionTable())
{
auto & tmt_context = context.getTMTContext();
for (const auto & part_def : table_info->partition.definitions)
{
auto new_part_table_info = table_info->producePartitionTableInfo(part_def.id, name_mapper);
auto part_storage = tmt_context.getStorages().get(keyspace_id, new_part_table_info->id);
if (part_storage == nullptr)
{
table_id_map.emplacePartitionTableID(part_def.id, table_id);
continue;
}
{
auto alter_lock = part_storage->lockForAlter(getThreadNameAndID());
auto local_table_info = part_storage->getTableInfo(); // copy
old_replica_count = local_table_info.replica_info.count;
new_replica_count = new_part_table_info->replica_info.count;
// Only update the replica info, do not change other fields. Or it may
// lead to other DDL is unexpectedly ignored.
local_table_info.replica_info = new_part_table_info->replica_info;
part_storage->alterSchemaChange(
alter_lock,
local_table_info,
name_mapper.mapDatabaseName(database_id, keyspace_id),
name_mapper.mapTableName(local_table_info),
context);
}
LOG_INFO(
log,
"Updating replica info, replica count old={} new={} available={}"
" physical_table_id={} logical_table_id={}",
old_replica_count,
new_replica_count,
table_info->replica_info.available,
part_def.id,
table_id);
}
}
{
auto alter_lock = storage->lockForAlter(getThreadNameAndID());
old_replica_count = local_logical_storage_table_info.replica_info.count;
new_replica_count = table_info->replica_info.count;
// Only update the replica info, do not change other fields. Or it may
// lead to other DDL is unexpectedly ignored.
local_logical_storage_table_info.replica_info = table_info->replica_info;
storage->alterSchemaChange(
alter_lock,
local_logical_storage_table_info,
name_mapper.mapDatabaseName(database_id, keyspace_id),
name_mapper.mapTableName(local_logical_storage_table_info),
context);
}
LOG_INFO(
log,
"Updating replica info, replica count old={} new={} available={}"
" physical_table_id={} logical_table_id={}",
old_replica_count,
new_replica_count,
table_info->replica_info.available,
table_id,
table_id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyPartitionDiff(DatabaseID database_id, TableID table_id)
{
auto table_info = getter.getTableInfo(database_id, table_id);
if (unlikely(table_info == nullptr))
{
LOG_ERROR(log, "table is not exist in TiKV, applyPartitionDiff is ignored, table_id={}", table_id);
return;
}
if (!table_info->isLogicalPartitionTable())
{
LOG_ERROR(
log,
"new table in TiKV is not a partition table {}, database_id={} table_id={}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id);
return;
}
auto & tmt_context = context.getTMTContext();
auto storage = tmt_context.getStorages().get(keyspace_id, table_info->id);
if (storage == nullptr)
{
LOG_ERROR(
log,
"logical_table storage instance is not exist in TiFlash, applyPartitionDiff is ignored, table_id={}",
table_id);
return;
}
applyPartitionDiffOnLogicalTable(database_id, table_info, storage);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyPartitionDiffOnLogicalTable(
const DatabaseID database_id,
const TableInfoPtr & table_info,
const ManageableStoragePtr & storage)
{
const auto & local_table_info = storage->getTableInfo();
// ALTER TABLE t PARTITION BY ... may turn a non-partition table into partition table
// with some partition ids in `partition.adding_definitions`/`partition.definitions`
// and `partition.dropping_definitions`. We need to create those partitions.
if (!local_table_info.isLogicalPartitionTable())
{
LOG_INFO(
log,
"Altering non-partition table to be a partition table {} with database_id={}, table_id={}",
name_mapper.debugCanonicalName(local_table_info, database_id, keyspace_id),
database_id,
local_table_info.id);
}
const auto & local_defs = local_table_info.partition.definitions;
const auto & new_defs = table_info->partition.definitions;
std::unordered_set<TableID> local_part_id_set, new_part_id_set;
std::for_each(local_defs.begin(), local_defs.end(), [&local_part_id_set](const auto & def) {
local_part_id_set.emplace(def.id);
});
std::for_each(new_defs.begin(), new_defs.end(), [&new_part_id_set](const auto & def) {
new_part_id_set.emplace(def.id);
});
LOG_INFO(
log,
"Applying partition changes {} with database_id={}, table_id={}, old: {}, new: {}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id,
local_part_id_set,
new_part_id_set);
if (local_part_id_set == new_part_id_set)
{
LOG_INFO(
log,
"No partition changes, partitions_size={} {} with database_id={}, table_id={}",
new_part_id_set.size(),
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id);
return;
}
// Copy the local table info and update fields on the copy
auto updated_table_info = local_table_info;
updated_table_info.is_partition_table = true;
updated_table_info.belonging_table_id = table_info->belonging_table_id;
updated_table_info.partition = table_info->partition;
/// Apply changes to physical tables.
auto reason = fmt::format("ApplyPartitionDiff-logical_table_id={}", local_table_info.id);
for (const auto & local_def : local_defs)
{
if (!new_part_id_set.contains(local_def.id))
{
applyDropPhysicalTable(name_mapper.mapDatabaseName(database_id, keyspace_id), local_def.id, reason);
}
}
for (const auto & new_def : new_defs)
{
if (!local_part_id_set.contains(new_def.id))
{
table_id_map.emplacePartitionTableID(new_def.id, updated_table_info.id);
}
}
auto alter_lock = storage->lockForAlter(getThreadNameAndID());
storage->alterSchemaChange(
alter_lock,
updated_table_info,
name_mapper.mapDatabaseName(database_id, keyspace_id),
name_mapper.mapTableName(updated_table_info),
context);
GET_METRIC(tiflash_schema_internal_ddl_count, type_apply_partition).Increment();
LOG_INFO(
log,
"Applied partition changes {} with database_id={}, table_id={}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRenameTable(DatabaseID database_id, TableID table_id)
{
// update the table_id_map no matter storage instance is created or not
table_id_map.emplaceTableID(table_id, database_id);
auto & tmt_context = context.getTMTContext();
auto storage = tmt_context.getStorages().get(keyspace_id, table_id);
if (storage == nullptr)
{
LOG_WARNING(
log,
"Storage instance is not exist in TiFlash, applyRenameTable is ignored, table_id={}",
table_id);
return;
}
auto new_table_info = getter.getTableInfo(database_id, table_id);
if (unlikely(new_table_info == nullptr))
{
LOG_ERROR(log, "table is not exist in TiKV, applyRenameTable is ignored, table_id={}", table_id);
return;
}
String new_db_display_name = tryGetDatabaseDisplayNameFromLocal(database_id);
applyRenameLogicalTable(database_id, new_db_display_name, new_table_info, storage);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRenameLogicalTable(
const DatabaseID new_database_id,
const String & new_database_display_name,
const TableInfoPtr & new_table_info,
const ManageableStoragePtr & storage)
{
applyRenamePhysicalTable(new_database_id, new_database_display_name, *new_table_info, storage);
if (!new_table_info->isLogicalPartitionTable())
return;
// For partitioned table, try to execute rename on each partition (physical table)
auto & tmt_context = context.getTMTContext();
for (const auto & part_def : new_table_info->partition.definitions)
{
auto part_storage = tmt_context.getStorages().get(keyspace_id, part_def.id);
if (part_storage == nullptr)
{
LOG_WARNING(
log,
"Storage instance is not exist in TiFlash, the partition is not created yet in this TiFlash instance, "
"applyRenamePhysicalTable is ignored, physical_table_id={} logical_table_id={}",
part_def.id,
new_table_info->id);
continue; // continue for next partition
}
FAIL_POINT_TRIGGER_EXCEPTION(FailPoints::random_ddl_fail_when_rename_partitions);
auto part_table_info = new_table_info->producePartitionTableInfo(part_def.id, name_mapper);
applyRenamePhysicalTable(new_database_id, new_database_display_name, *part_table_info, part_storage);
}
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRenamePhysicalTable(
const DatabaseID new_database_id,
const String & new_database_display_name,
const TableInfo & new_table_info,
const ManageableStoragePtr & storage)
{
const auto old_mapped_db_name = storage->getDatabaseName();
const auto new_mapped_db_name = name_mapper.mapDatabaseName(new_database_id, keyspace_id);
const auto old_display_table_name = name_mapper.displayTableName(storage->getTableInfo());
const auto new_display_table_name = name_mapper.displayTableName(new_table_info);
if (old_mapped_db_name == new_mapped_db_name && old_display_table_name == new_display_table_name)
{
LOG_DEBUG(
log,
"Table {} name identical, not renaming. database_id={} table_id={}",
name_mapper.debugCanonicalName(new_table_info, new_database_id, keyspace_id),
new_database_id,
new_table_info.id);
return;
}
// There could be a chance that the target database has been dropped in TiKV before
// TiFlash accepts the "create database" schema diff. We need to ensure the local
// database exist before executing renaming.
const auto action = fmt::format("applyRenamePhysicalTable-table_id={}", new_table_info.id);
ensureLocalDatabaseExist(new_database_id, new_mapped_db_name, action);
const auto old_mapped_tbl_name = storage->getTableName();
GET_METRIC(tiflash_schema_internal_ddl_count, type_rename_table).Increment();
LOG_INFO(
log,
"Rename table {}.{} (display name: {}) to {} begin, database_id={} table_id={}",
old_mapped_db_name,
old_mapped_tbl_name,
old_display_table_name,
name_mapper.debugCanonicalName(new_table_info, new_database_id, keyspace_id),
new_database_id,
new_table_info.id);
// Note that rename will update table info in table create statement by modifying original table info
// with "tidb_display.table" instead of using new_table_info directly, so that other changes
// (ALTER commands) won't be saved. Besides, no need to update schema_version as table name is not structural.
auto rename = std::make_shared<ASTRenameQuery>();
ASTRenameQuery::Element elem{
.from = ASTRenameQuery::Table{old_mapped_db_name, old_mapped_tbl_name},
.to = ASTRenameQuery::Table{new_mapped_db_name, name_mapper.mapTableName(new_table_info)},
.tidb_display = ASTRenameQuery::Table{new_database_display_name, new_display_table_name},
};
rename->elements.emplace_back(std::move(elem));
InterpreterRenameQuery(rename, context, getThreadNameAndID()).execute();
LOG_INFO(
log,
"Rename table {}.{} (display name: {}) to {} end, database_id={} table_id={}",
old_mapped_db_name,
old_mapped_tbl_name,
old_display_table_name,
name_mapper.debugCanonicalName(new_table_info, new_database_id, keyspace_id),
new_database_id,
new_table_info.id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRecoverTable(DatabaseID database_id, TiDB::TableID table_id)
{
auto table_info = getter.getTableInfo(database_id, table_id);
if (unlikely(table_info == nullptr))
{
// this table is dropped.
LOG_INFO(
log,
"table is not exist in TiKV, may have been dropped, recover table is ignored, table_id={}",
table_id);
return;
}
applyRecoverLogicalTable(database_id, table_info, "RecoverTable");
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRecoverLogicalTable(
const DatabaseID database_id,
const TiDB::TableInfoPtr & table_info,
std::string_view action)
{
assert(table_info != nullptr);
if (table_info->isLogicalPartitionTable())
{
for (const auto & part_def : table_info->partition.definitions)
{
auto part_table_info = table_info->producePartitionTableInfo(part_def.id, name_mapper);
tryRecoverPhysicalTable(database_id, part_table_info, action);
}
}
tryRecoverPhysicalTable(database_id, table_info, action);
}
// Return true - the Storage instance exists and is recovered (or not tombstone)
// false - the Storage instance does not exist
template <typename Getter, typename NameMapper>
bool SchemaBuilder<Getter, NameMapper>::tryRecoverPhysicalTable(
const DatabaseID database_id,
const TiDB::TableInfoPtr & table_info,
std::string_view action)
{
assert(table_info != nullptr);
auto & tmt_context = context.getTMTContext();
auto storage = tmt_context.getStorages().get(keyspace_id, table_info->id);
if (storage == nullptr)
{
LOG_INFO(
log,
"Storage instance does not exist, tryRecoverPhysicalTable is ignored, table_id={} action={}",
table_info->id,
action);
return false;
}
if (!storage->isTombstone())
{
LOG_INFO(
log,
"Trying to recover table {} but it is not marked as tombstone, skip, database_id={} table_id={} action={}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id,
action);
return true;
}
LOG_INFO(
log,
"Create table {} by recover begin, database_id={} table_id={} action={}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id,
action);
AlterCommands commands;
{
AlterCommand command;
command.type = AlterCommand::RECOVER;
commands.emplace_back(std::move(command));
}
auto alter_lock = storage->lockForAlter(getThreadNameAndID());
storage->updateTombstone(
alter_lock,
commands,
name_mapper.mapDatabaseName(database_id, keyspace_id),
*table_info,
name_mapper,
context);
LOG_INFO(
log,
"Create table {} by recover end, database_id={} table_id={} action={}",
name_mapper.debugCanonicalName(*table_info, database_id, keyspace_id),
database_id,
table_info->id,
action);
return true;
}
static ASTPtr parseCreateStatement(const String & statement)
{
ParserCreateQuery parser;
const char * pos = statement.data();
std::string error_msg;
auto ast = tryParseQuery(
parser,
pos,
pos + statement.size(),
error_msg,
/*hilite=*/false,
String("in ") + __PRETTY_FUNCTION__,
/*allow_multi_statements=*/false,
0);
if (!ast)
throw Exception(error_msg, ErrorCodes::SYNTAX_ERROR);
return ast;
}
String createDatabaseStmt(Context & context, const DBInfo & db_info, const SchemaNameMapper & name_mapper)
{
auto mapped_db_name = name_mapper.mapDatabaseName(db_info);
if (isReservedDatabase(context, mapped_db_name))
throw TiFlashException(
fmt::format("Database {} is reserved, database_id={}", name_mapper.debugDatabaseName(db_info), db_info.id),
Errors::DDL::Internal);
// R"raw(
// CREATE DATABASE IF NOT EXISTS `db_xx`
// ENGINE = TiFlash('<json-db-info>', <format-version>)
// )raw";
String stmt;
WriteBufferFromString stmt_buf(stmt);
writeString("CREATE DATABASE IF NOT EXISTS ", stmt_buf);
writeBackQuotedString(mapped_db_name, stmt_buf);
writeString(" ENGINE = TiFlash('", stmt_buf);
writeEscapedString(db_info.serialize(), stmt_buf); // must escaped for json-encoded text
writeString("', ", stmt_buf);
writeIntText(DatabaseTiFlash::CURRENT_VERSION, stmt_buf);
writeString(")", stmt_buf);
return stmt;
}
template <typename Getter, typename NameMapper>
bool SchemaBuilder<Getter, NameMapper>::applyCreateDatabase(DatabaseID database_id)
{
auto db_info = getter.getDatabase(database_id);
if (unlikely(db_info == nullptr))
{
LOG_INFO(
log,
"Create database is ignored because database is not exist in TiKV,"
" database_id={}",
database_id);
return false;
}
applyCreateDatabaseByInfo(db_info);
return true;
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyCreateDatabaseByInfo(const TiDB::DBInfoPtr & db_info)
{
GET_METRIC(tiflash_schema_internal_ddl_count, type_create_db).Increment();
LOG_INFO(log, "Create database {} begin, database_id={}", name_mapper.debugDatabaseName(*db_info), db_info->id);
auto statement = createDatabaseStmt(context, *db_info, name_mapper);
ASTPtr ast = parseCreateStatement(statement);
InterpreterCreateQuery interpreter(ast, context);
interpreter.setInternal(true);
interpreter.setForceRestoreData(false);
interpreter.execute();
databases.addDatabaseInfo(db_info);
LOG_INFO(log, "Create database {} end, database_id={}", name_mapper.debugDatabaseName(*db_info), db_info->id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyRecoverDatabase(DatabaseID database_id)
{
auto db_info = getter.getDatabase(database_id);
if (unlikely(db_info == nullptr))
{
LOG_INFO(
log,
"Recover database is ignored because database is not exist in TiKV,"
" database_id={}",
database_id);
return;
}
LOG_INFO(log, "Recover database begin, database_id={}", database_id);
auto db_name = name_mapper.mapDatabaseName(database_id, keyspace_id);
auto db = context.tryGetDatabase(db_name);
if (unlikely(!db))
{
LOG_ERROR(
log,
"Recover database is ignored because instance is not exists, may have been physically dropped, "
"database_id={}",
db_name,
database_id);
return;
}
{
//TODO: it seems may need a lot time, maybe we can do it in a background thread
auto action = fmt::format("RecoverSchema-database_id={}", database_id);
auto table_ids = table_id_map.findTablesByDatabaseID(database_id);
for (auto table_id : table_ids)
{
auto table_info = getter.getTableInfo(database_id, table_id);
applyRecoverLogicalTable(database_id, table_info, action);
}
}
// Usually `FLASHBACK DATABASE ... TO ...` will rename the database
db->alterTombstone(context, 0, db_info);
databases.addDatabaseInfo(db_info); // add back database info cache
LOG_INFO(log, "Recover database end, database_id={}", database_id);
}
template <typename Getter, typename NameMapper>
void SchemaBuilder<Getter, NameMapper>::applyDropDatabase(DatabaseID database_id)
{
// The DDL in TiFlash comes after user executed `DROP DATABASE ...`. So the meta key could
// have already been deleted. In order to handle this situation, we should not fetch the
// `DatabaseInfo` from TiKV.
{
//TODO: it seems may need a lot time, maybe we can do it in a background thread
auto reason = fmt::format("DropDatabase-database_id={}", database_id);
auto table_ids = table_id_map.findTablesByDatabaseID(database_id);
for (auto table_id : table_ids)