-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Expand file tree
/
Copy pathcreate_table.go
More file actions
1782 lines (1649 loc) · 60 KB
/
Copy pathcreate_table.go
File metadata and controls
1782 lines (1649 loc) · 60 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 2024 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.
package ddl
import (
"context"
"fmt"
"math"
"strings"
"sync/atomic"
"unicode/utf8"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/pkg/config"
"github.com/pingcap/tidb/pkg/ddl/logutil"
"github.com/pingcap/tidb/pkg/ddl/notifier"
"github.com/pingcap/tidb/pkg/ddl/placement"
"github.com/pingcap/tidb/pkg/domain/infosync"
"github.com/pingcap/tidb/pkg/errctx"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/infoschema"
infoschemactx "github.com/pingcap/tidb/pkg/infoschema/context"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/meta"
"github.com/pingcap/tidb/pkg/meta/autoid"
"github.com/pingcap/tidb/pkg/meta/metabuild"
"github.com/pingcap/tidb/pkg/meta/model"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/format"
"github.com/pingcap/tidb/pkg/parser/mysql"
field_types "github.com/pingcap/tidb/pkg/parser/types"
"github.com/pingcap/tidb/pkg/sessionctx/vardef"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/table/tables"
"github.com/pingcap/tidb/pkg/types"
driver "github.com/pingcap/tidb/pkg/types/parser_driver"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/set"
"github.com/pingcap/tidb/pkg/util/tracing"
"go.uber.org/zap"
)
// DANGER: it is an internal function used by onCreateTable and onCreateTables, for reusing code. Be careful.
// 1. it expects the argument of job has been deserialized.
// 2. it won't call updateSchemaVersion, FinishTableJob and asyncNotifyEvent.
func createTable(jobCtx *jobContext, job *model.Job, r autoid.Requirement, args *model.CreateTableArgs) (*model.TableInfo, error) {
schemaID := job.SchemaID
tbInfo, fkCheck := args.TableInfo, args.FKCheck
tbInfo.State = model.StateNone
err := checkTableNotExists(jobCtx.infoCache, schemaID, tbInfo.Name.L)
if err != nil {
if infoschema.ErrDatabaseNotExists.Equal(err) || infoschema.ErrTableExists.Equal(err) {
job.State = model.JobStateCancelled
}
return tbInfo, errors.Trace(err)
}
metaMut := jobCtx.metaMut
err = checkConstraintNamesNotExists(metaMut, schemaID, tbInfo.Constraints)
if err != nil {
if infoschema.ErrCheckConstraintDupName.Equal(err) {
job.State = model.JobStateCancelled
}
return tbInfo, errors.Trace(err)
}
retryable, err := checkTableForeignKeyValidInOwner(jobCtx, job, tbInfo, fkCheck)
if err != nil {
if !retryable {
job.State = model.JobStateCancelled
}
return tbInfo, errors.Trace(err)
}
// Allocate foreign key ID.
for _, fkInfo := range tbInfo.ForeignKeys {
fkInfo.ID = allocateFKIndexID(tbInfo)
fkInfo.State = model.StatePublic
}
switch tbInfo.State {
case model.StateNone:
// none -> public
tbInfo.State = model.StatePublic
tbInfo.UpdateTS = metaMut.StartTS
err = createTableOrViewWithCheck(metaMut, job, schemaID, tbInfo)
if err != nil {
return tbInfo, errors.Trace(err)
}
failpoint.Inject("checkOwnerCheckAllVersionsWaitTime", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(tbInfo, errors.New("mock create table error"))
}
})
// build table & partition bundles if any.
if err = checkAllTablePlacementPoliciesExistAndCancelNonExistJob(jobCtx.metaMut, job, tbInfo); err != nil {
return tbInfo, errors.Trace(err)
}
if tbInfo.TiFlashReplica != nil {
replicaInfo := tbInfo.TiFlashReplica
if pi := tbInfo.GetPartitionInfo(); pi != nil {
logutil.DDLLogger().Info("Set TiFlash replica pd rule for partitioned table when creating", zap.Int64("tableID", tbInfo.ID))
if e := infosync.ConfigureTiFlashPDForPartitions(false, &pi.Definitions, replicaInfo.Count, &replicaInfo.LocationLabels, tbInfo.ID); e != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Trace(e)
}
// Partitions that in adding mid-state. They have high priorities, so we should set accordingly pd rules.
if e := infosync.ConfigureTiFlashPDForPartitions(true, &pi.AddingDefinitions, replicaInfo.Count, &replicaInfo.LocationLabels, tbInfo.ID); e != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Trace(e)
}
} else {
logutil.DDLLogger().Info("Set TiFlash replica pd rule when creating", zap.Int64("tableID", tbInfo.ID))
if e := infosync.ConfigureTiFlashPDForTable(tbInfo.ID, replicaInfo.Count, &replicaInfo.LocationLabels); e != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Trace(e)
}
}
}
bundles, err := placement.NewFullTableBundles(metaMut, tbInfo)
if err != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Trace(err)
}
// Send the placement bundle to PD.
err = infosync.PutRuleBundlesWithDefaultRetry(context.TODO(), bundles)
if err != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Wrapf(err, "failed to notify PD the placement rules")
}
if tbInfo.Affinity != nil {
if err = createTableAffinityGroupsInPD(jobCtx, tbInfo); err != nil {
job.State = model.JobStateCancelled
return tbInfo, errors.Wrapf(err, "failed to create table affinity groups in PD")
}
}
// Updating auto id meta kv is done in a separate txn.
// It's ok as these data are bind with table ID, and we won't use these
// table IDs until info schema version is updated.
if err := handleAutoIncID(r, job, tbInfo); err != nil {
return tbInfo, errors.Trace(err)
}
return tbInfo, nil
default:
return tbInfo, dbterror.ErrInvalidDDLState.GenWithStackByArgs("table", tbInfo.State)
}
}
type autoIDType struct {
End int64
Tp autoid.AllocatorType
}
// handleAutoIncID handles auto_increment option in DDL. It creates a ID counter for the table and initiates the counter to a proper value.
// For example if the option sets auto_increment to 10. The counter will be set to 9. So the next allocated ID will be 10.
func handleAutoIncID(r autoid.Requirement, job *model.Job, tbInfo *model.TableInfo) error {
allocs := autoid.NewAllocatorsFromTblInfo(r, job.SchemaID, tbInfo)
hs := make([]autoIDType, 0, 3)
if tbInfo.AutoIncID > 1 {
// Default tableAutoIncID base is 0.
// If the first ID is expected to greater than 1, we need to do rebase.
if tbInfo.SepAutoInc() {
hs = append(hs, autoIDType{tbInfo.AutoIncID - 1, autoid.AutoIncrementType})
} else {
hs = append(hs, autoIDType{tbInfo.AutoIncID - 1, autoid.RowIDAllocType})
}
}
if tbInfo.AutoIncIDExtra != 0 {
hs = append(hs, autoIDType{tbInfo.AutoIncIDExtra - 1, autoid.RowIDAllocType})
}
if tbInfo.AutoRandID > 1 {
// Default tableAutoRandID base is 0.
// If the first ID is expected to greater than 1, we need to do rebase.
hs = append(hs, autoIDType{tbInfo.AutoRandID - 1, autoid.AutoRandomType})
}
for _, h := range hs {
if alloc := allocs.Get(h.Tp); alloc != nil {
if err := alloc.Rebase(context.Background(), h.End, false); err != nil {
return errors.Trace(err)
}
}
}
failpoint.InjectCall("handleAutoIncID")
return nil
}
func (w *worker) onCreateTable(jobCtx *jobContext, job *model.Job) (ver int64, _ error) {
failpoint.Inject("mockExceedErrorLimit", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(ver, errors.New("mock do job error"))
}
})
r := tracing.StartRegion(jobCtx.ctx, "ddlWorker.onCreateTable")
defer r.End()
args, err := model.GetCreateTableArgs(job)
if err != nil {
// Invalid arguments, cancel this job.
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
jobCtx.jobArgs = args
tbInfo := args.TableInfo
if len(tbInfo.ForeignKeys) > 0 {
return w.createTableWithForeignKeys(jobCtx, job, args)
}
tbInfo, err = createTable(jobCtx, job, &asAutoIDRequirement{
store: w.store,
autoidCli: w.autoidCli,
}, args)
if err != nil {
return ver, errors.Trace(err)
}
ver, err = updateSchemaVersion(jobCtx, job)
if err != nil {
return ver, errors.Trace(err)
}
createTableEvent := notifier.NewCreateTableEvent(tbInfo)
err = asyncNotifyEvent(jobCtx, createTableEvent, job, noSubJob, w.sess)
if err != nil {
return ver, errors.Trace(err)
}
w.tryRegisterTTLTableToExternalWorkload(jobCtx.ctx, tbInfo)
// Finish this job.
job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tbInfo)
return ver, errors.Trace(err)
}
func (w *worker) createTableWithForeignKeys(jobCtx *jobContext, job *model.Job, args *model.CreateTableArgs) (ver int64, err error) {
tbInfo := args.TableInfo
switch tbInfo.State {
case model.StateNone, model.StatePublic:
// create table in non-public or public state. The function `createTable` will always reset
// the `tbInfo.State` with `model.StateNone`, so it's fine to just call the `createTable` with
// public state.
// when `br` restores table, the state of `tbInfo` will be public.
tbInfo, err = createTable(jobCtx, job, &asAutoIDRequirement{
store: w.store,
autoidCli: w.autoidCli,
}, args)
if err != nil {
return ver, errors.Trace(err)
}
tbInfo.State = model.StateDeleteOnly
ver, err = updateVersionAndTableInfo(jobCtx, job, tbInfo, true)
if err != nil {
return ver, errors.Trace(err)
}
job.SchemaState = model.StateDeleteOnly
// The `tblInfo.State` should be transformed from `None/Public` to `DeleteOnly`. In the `DeleteOnly` state, the table cannot be used explicitly
// in any SQL statement, but if this table has a `ON DELETE CASCADE` or `ON UPDATE CASCADE`, it'll still be deleted/updated automatically to keep
// consistency.
//
// This branch handles both `StateDeleteOnly` and `StateWriteOnly` to avoid compatibility issues. If the TiDB is upgraded from an old version,
// there may be a DDL job in the `StateWriteOnly` state. Now, we handle it in the same way as the `StateDeleteOnly` state. When we believe it's
// impossible to upgrade from a too old version to the current version, we can remove the `StateWriteOnly` branch.
case model.StateDeleteOnly, model.StateWriteOnly:
tbInfo.State = model.StatePublic
ver, err = updateVersionAndTableInfo(jobCtx, job, tbInfo, true)
if err != nil {
return ver, errors.Trace(err)
}
createTableEvent := notifier.NewCreateTableEvent(tbInfo)
err = asyncNotifyEvent(jobCtx, createTableEvent, job, noSubJob, w.sess)
if err != nil {
return ver, errors.Trace(err)
}
w.tryRegisterTTLTableToExternalWorkload(jobCtx.ctx, tbInfo)
job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tbInfo)
return ver, nil
default:
return ver, errors.Trace(dbterror.ErrInvalidDDLJob.GenWithStackByArgs("table", tbInfo.State))
}
return ver, errors.Trace(err)
}
func (w *worker) onCreateTables(jobCtx *jobContext, job *model.Job) (int64, error) {
var ver int64
args, err := model.GetBatchCreateTableArgs(job)
if err != nil {
// Invalid arguments, cancel this job.
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
tableInfos := make([]*model.TableInfo, 0, len(args.Tables))
// We don't construct jobs for every table, but only tableInfo
// The following loop creates a stub job for every table
//
// it clones a stub job from the ActionCreateTables job
stubJob := job.Clone()
for i := range args.Tables {
tblArgs := args.Tables[i]
tableInfo := tblArgs.TableInfo
stubJob.TableID = tableInfo.ID
if tableInfo.Sequence != nil {
err := createSequenceWithCheck(jobCtx.metaMut, stubJob, tableInfo)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
tableInfos = append(tableInfos, tableInfo)
} else {
tbInfo, err := createTable(jobCtx, stubJob, &asAutoIDRequirement{
store: w.store,
autoidCli: w.autoidCli,
}, tblArgs)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
tableInfos = append(tableInfos, tbInfo)
}
}
ver, err = updateSchemaVersion(jobCtx, job)
if err != nil {
return ver, errors.Trace(err)
}
for i := range tableInfos {
createTableEvent := notifier.NewCreateTableEvent(tableInfos[i])
err = asyncNotifyEvent(jobCtx, createTableEvent, job, int64(i), w.sess)
if err != nil {
return ver, errors.Trace(err)
}
}
job.State = model.JobStateDone
job.SchemaState = model.StatePublic
job.BinlogInfo.SetTableInfos(ver, tableInfos)
return ver, errors.Trace(err)
}
func createTableOrViewWithCheck(t *meta.Mutator, job *model.Job, schemaID int64, tbInfo *model.TableInfo) error {
err := checkTableInfoValid(tbInfo)
if err != nil {
job.State = model.JobStateCancelled
return errors.Trace(err)
}
return t.CreateTableOrView(schemaID, tbInfo)
}
func onCreateView(jobCtx *jobContext, job *model.Job) (ver int64, _ error) {
schemaID := job.SchemaID
args, err := model.GetCreateTableArgs(job)
if err != nil {
// Invalid arguments, cancel this job.
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
tbInfo, orReplace := args.TableInfo, args.OnExistReplace
tbInfo.State = model.StateNone
metaMut := jobCtx.metaMut
oldTableID, err := findTableIDByName(jobCtx.infoCache, metaMut, schemaID, tbInfo.Name.L)
if err == nil && oldTableID > 0 {
err = infoschema.ErrTableExists
}
if infoschema.ErrTableNotExists.Equal(err) {
err = nil
}
failpoint.InjectCall("onDDLCreateView", job)
if err != nil {
if infoschema.ErrDatabaseNotExists.Equal(err) {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
} else if !infoschema.ErrTableExists.Equal(err) {
return ver, errors.Trace(err)
}
if !orReplace {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
}
ver, err = updateSchemaVersion(jobCtx, job)
if err != nil {
return ver, errors.Trace(err)
}
switch tbInfo.State {
case model.StateNone:
// none -> public
tbInfo.State = model.StatePublic
tbInfo.UpdateTS = metaMut.StartTS
if oldTableID > 0 && orReplace {
err = metaMut.DropTableOrView(schemaID, oldTableID)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
err = metaMut.GetAutoIDAccessors(schemaID, oldTableID).Del()
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
}
err = createTableOrViewWithCheck(metaMut, job, schemaID, tbInfo)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
// Finish this job.
job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tbInfo)
return ver, nil
default:
return ver, dbterror.ErrInvalidDDLState.GenWithStackByArgs("table", tbInfo.State)
}
}
func findTableIDByName(infoCache *infoschema.InfoCache, t *meta.Mutator, schemaID int64, tableName string) (int64, error) {
// Try to use memory schema info to check first.
currVer, err := t.GetSchemaVersion()
if err != nil {
return 0, err
}
is := infoCache.GetLatest()
if is != nil && is.SchemaMetaVersion() == currVer {
return findTableIDFromInfoSchema(is, schemaID, tableName)
}
return findTableIDFromStore(t, schemaID, tableName)
}
func findTableIDFromInfoSchema(is infoschema.InfoSchema, schemaID int64, tableName string) (int64, error) {
schema, ok := is.SchemaByID(schemaID)
if !ok {
return 0, infoschema.ErrDatabaseNotExists.GenWithStackByArgs("")
}
tbl, err := is.TableByName(context.Background(), schema.Name, ast.NewCIStr(tableName))
if err != nil {
return 0, err
}
return tbl.Meta().ID, nil
}
func findTableIDFromStore(t *meta.Mutator, schemaID int64, tableName string) (int64, error) {
tbls, err := t.ListSimpleTables(schemaID)
if err != nil {
if meta.ErrDBNotExists.Equal(err) {
return 0, infoschema.ErrDatabaseNotExists.GenWithStackByArgs("")
}
return 0, errors.Trace(err)
}
for _, tbl := range tbls {
if tbl.Name.L == tableName {
return tbl.ID, nil
}
}
return 0, infoschema.ErrTableNotExists.FastGenByArgs(tableName)
}
// BuildTableInfoFromAST builds model.TableInfo from a SQL statement.
// Note: TableID and PartitionID are left as uninitialized value.
func BuildTableInfoFromAST(ctx *metabuild.Context, s *ast.CreateTableStmt) (*model.TableInfo, error) {
// TODO: Support the vector index for this function.
return buildTableInfoWithCheck(ctx, nil, s, mysql.DefaultCharset, "", nil)
}
// buildTableInfoWithCheck builds model.TableInfo from a SQL statement.
// Note: TableID and PartitionIDs are left as uninitialized value.
func buildTableInfoWithCheck(ctx *metabuild.Context, store kv.Storage, s *ast.CreateTableStmt, dbCharset, dbCollate string, placementPolicyRef *model.PolicyRefInfo) (*model.TableInfo, error) {
tbInfo, err := BuildTableInfoWithStmt(ctx, s, dbCharset, dbCollate, placementPolicyRef)
if err != nil {
return nil, err
}
// Fix issue 17952 which will cause partition range expr can't be parsed as Int.
// checkTableInfoValidWithStmt will do the constant fold the partition expression first,
// then checkTableInfoValidExtra will pass the tableInfo check successfully.
if err = checkTableInfoValidWithStmt(ctx, tbInfo, s); err != nil {
return nil, err
}
if err = checkTableInfoValidExtra(ctx.GetExprCtx().GetEvalCtx().ErrCtx(), store, s.Table.Schema, tbInfo); err != nil {
return nil, err
}
return tbInfo, nil
}
// CheckTableInfoValidWithStmt exposes checkTableInfoValidWithStmt to SchemaTracker. Maybe one day we can delete it.
func CheckTableInfoValidWithStmt(ctx *metabuild.Context, tbInfo *model.TableInfo, s *ast.CreateTableStmt) (err error) {
return checkTableInfoValidWithStmt(ctx, tbInfo, s)
}
func checkTableInfoValidWithStmt(ctx *metabuild.Context, tbInfo *model.TableInfo, s *ast.CreateTableStmt) (err error) {
// All of these rely on the AST structure of expressions, which were
// lost in the model (got serialized into strings).
if err := checkGeneratedColumn(ctx, s.Table.Schema, tbInfo.Name, s.Cols); err != nil {
return errors.Trace(err)
}
// Check if table has a primary key if required.
if ctx.PrimaryKeyRequired() && len(tbInfo.GetPkName().String()) == 0 {
return infoschema.ErrTableWithoutPrimaryKey
}
if tbInfo.Partition != nil {
if err := checkPartitionDefinitionConstraints(ctx.GetExprCtx(), tbInfo); err != nil {
return errors.Trace(err)
}
if err := rebuildStorageClassForPartitions(tbInfo, tbInfo.Partition.Definitions); err != nil {
return errors.Trace(err)
}
if s.Partition != nil {
if err := checkPartitionFuncType(ctx.GetExprCtx(), s.Partition.Expr, s.Table.Schema.O, tbInfo); err != nil {
return errors.Trace(err)
}
if err := checkPartitioningKeysConstraints(ctx, s, tbInfo); err != nil {
return errors.Trace(err)
}
}
}
if tbInfo.TTLInfo != nil {
var foreignKeyCheckIs infoschemactx.MetaOnlyInfoSchema
if is, ok := ctx.GetInfoSchema(); ok {
foreignKeyCheckIs = is
}
if err = checkTTLInfoValid(s.Table.Schema, tbInfo, foreignKeyCheckIs); err != nil {
return err
}
}
return nil
}
func checkGeneratedColumn(ctx *metabuild.Context, schemaName ast.CIStr, tableName ast.CIStr, colDefs []*ast.ColumnDef) error {
var colName2Generation = make(map[string]columnGenerationInDDL, len(colDefs))
var exists bool
var autoIncrementColumn string
for i, colDef := range colDefs {
for _, option := range colDef.Options {
if option.Tp == ast.ColumnOptionGenerated {
if err := checkIllegalFn4Generated(colDef.Name.Name.L, typeColumn, option.Expr); err != nil {
return errors.Trace(err)
}
}
}
if containsColumnOption(colDef, ast.ColumnOptionAutoIncrement) {
exists, autoIncrementColumn = true, colDef.Name.Name.L
}
generated, depCols, err := findDependedColumnNames(schemaName, tableName, colDef)
if err != nil {
return errors.Trace(err)
}
if !generated {
colName2Generation[colDef.Name.Name.L] = columnGenerationInDDL{
position: i,
generated: false,
}
} else {
colName2Generation[colDef.Name.Name.L] = columnGenerationInDDL{
position: i,
generated: true,
dependences: depCols,
}
}
}
// Check whether the generated column refers to any auto-increment columns
if exists {
if !ctx.EnableAutoIncrementInGenerated() {
for colName, generated := range colName2Generation {
if _, found := generated.dependences[autoIncrementColumn]; found {
return dbterror.ErrGeneratedColumnRefAutoInc.GenWithStackByArgs(colName)
}
}
}
}
for _, colDef := range colDefs {
colName := colDef.Name.Name.L
if err := verifyColumnGeneration(colName2Generation, colName); err != nil {
return errors.Trace(err)
}
}
return nil
}
func checkColumnarIndexIfNeedTiFlashReplica(store kv.Storage, dbName ast.CIStr, tblInfo *model.TableInfo) error {
var hasColumnarIndex bool
for _, idx := range tblInfo.Indices {
if idx.IsColumnarIndex() {
hasColumnarIndex = true
break
}
}
if !hasColumnarIndex {
return nil
}
if store == nil {
return errors.New("the store is nil")
}
if err := isTableTiFlashSupported(dbName, tblInfo); err != nil {
return errors.Trace(err)
}
if tblInfo.TiFlashReplica == nil || tblInfo.TiFlashReplica.Count == 0 {
if config.GetGlobalConfig().CSE.IsTiFlashEnabled() {
replicas, err := infoschema.GetTiFlashStoreCount(store)
if err != nil {
return errors.Trace(err)
}
if replicas == 0 {
return errors.Trace(dbterror.ErrUnsupportedAddColumnarIndex.FastGenByArgs("unsupported TiFlash store count is 0"))
}
}
// Always try to set to 1 as the default replica count.
defaultReplicas := uint64(1)
tblInfo.TiFlashReplica = &model.TiFlashReplicaInfo{
Count: defaultReplicas,
LocationLabels: make([]string, 0),
}
}
return errors.Trace(checkTableTypeForColumnarIndex(tblInfo))
}
// checkTableInfoValidExtra is like checkTableInfoValid, but also assumes the
// table info comes from untrusted source and performs further checks such as
// name length and column count.
// (checkTableInfoValid is also used in repairing objects which don't perform
// these checks. Perhaps the two functions should be merged together regardless?)
func checkTableInfoValidExtra(ec errctx.Context, store kv.Storage, dbName ast.CIStr, tbInfo *model.TableInfo) error {
if err := checkTooLongTable(tbInfo.Name); err != nil {
return err
}
if err := checkDuplicateColumn(tbInfo.Columns); err != nil {
return err
}
if err := checkTooLongColumns(tbInfo.Columns); err != nil {
return err
}
if err := checkTooManyColumns(tbInfo.Columns); err != nil {
return errors.Trace(err)
}
if err := checkTooManyIndexes(tbInfo.Indices); err != nil {
return errors.Trace(err)
}
if err := checkColumnsAttributes(tbInfo.Columns); err != nil {
return errors.Trace(err)
}
if err := checkGlobalIndexes(ec, tbInfo); err != nil {
return errors.Trace(err)
}
if err := checkColumnarIndexIfNeedTiFlashReplica(store, dbName, tbInfo); err != nil {
return errors.Trace(err)
}
// FIXME: perform checkConstraintNames
if err := checkCharsetAndCollation(tbInfo.Charset, tbInfo.Collate); err != nil {
return errors.Trace(err)
}
oldState := tbInfo.State
tbInfo.State = model.StatePublic
err := checkTableInfoValid(tbInfo)
tbInfo.State = oldState
return err
}
// checkTableInfoValid uses to check table info valid. This is used to validate table info.
func checkTableInfoValid(tblInfo *model.TableInfo) error {
_, err := tables.TableFromMeta(autoid.NewAllocators(false), tblInfo)
if err != nil {
return err
}
return checkInvisibleIndexOnPK(tblInfo)
}
func checkDuplicateColumn(cols []*model.ColumnInfo) error {
colNames := set.StringSet{}
for _, col := range cols {
colName := col.Name
if colNames.Exist(colName.L) {
return infoschema.ErrColumnExists.GenWithStackByArgs(colName.O)
}
colNames.Insert(colName.L)
}
return nil
}
func checkTooLongColumns(cols []*model.ColumnInfo) error {
for _, col := range cols {
if err := checkTooLongColumn(col.Name); err != nil {
return err
}
}
return nil
}
func checkTooManyColumns(colDefs []*model.ColumnInfo) error {
if uint32(len(colDefs)) > atomic.LoadUint32(&config.GetGlobalConfig().TableColumnCountLimit) {
return dbterror.ErrTooManyFields
}
return nil
}
func checkTooManyIndexes(idxDefs []*model.IndexInfo) error {
if len(idxDefs) > config.GetGlobalConfig().IndexLimit {
return dbterror.ErrTooManyKeys.GenWithStackByArgs(config.GetGlobalConfig().IndexLimit)
}
return nil
}
// checkColumnsAttributes checks attributes for multiple columns.
func checkColumnsAttributes(colDefs []*model.ColumnInfo) error {
for _, colDef := range colDefs {
if err := checkColumnAttributes(colDef.Name.O, &colDef.FieldType); err != nil {
return errors.Trace(err)
}
}
return nil
}
// checkColumnAttributes check attributes for single column.
func checkColumnAttributes(colName string, tp *types.FieldType) error {
switch tp.GetType() {
case mysql.TypeNewDecimal, mysql.TypeDouble, mysql.TypeFloat:
if tp.GetFlen() < tp.GetDecimal() {
return types.ErrMBiggerThanD.GenWithStackByArgs(colName)
}
case mysql.TypeDatetime, mysql.TypeDuration, mysql.TypeTimestamp:
if tp.GetDecimal() != types.UnspecifiedFsp && (tp.GetDecimal() < types.MinFsp || tp.GetDecimal() > types.MaxFsp) {
return types.ErrTooBigPrecision.GenWithStackByArgs(tp.GetDecimal(), colName, types.MaxFsp)
}
}
return nil
}
// BuildSessionTemporaryTableInfo builds model.TableInfo from a SQL statement.
func BuildSessionTemporaryTableInfo(ctx *metabuild.Context, store kv.Storage, is infoschema.InfoSchema, s *ast.CreateTableStmt,
dbCharset, dbCollate string, placementPolicyRef *model.PolicyRefInfo) (*model.TableInfo, error) {
ident := ast.Ident{Schema: s.Table.Schema, Name: s.Table.Name}
//build tableInfo
var tbInfo *model.TableInfo
var referTbl table.Table
var err error
if s.ReferTable != nil {
referIdent := ast.Ident{Schema: s.ReferTable.Schema, Name: s.ReferTable.Name}
_, ok := is.SchemaByName(referIdent.Schema)
if !ok {
return nil, infoschema.ErrTableNotExists.GenWithStackByArgs(referIdent.Schema, referIdent.Name)
}
referTbl, err = is.TableByName(context.Background(), referIdent.Schema, referIdent.Name)
if err != nil {
return nil, infoschema.ErrTableNotExists.GenWithStackByArgs(referIdent.Schema, referIdent.Name)
}
tbInfo, err = BuildTableInfoWithLike(ident, referTbl.Meta(), s)
} else {
tbInfo, err = BuildTableInfoWithStmt(ctx, s, dbCharset, dbCollate, placementPolicyRef)
}
if err != nil {
return nil, err
}
if err = checkTableInfoValidWithStmt(ctx, tbInfo, s); err != nil {
return nil, err
}
if err = checkTableInfoValidExtra(ctx.GetExprCtx().GetEvalCtx().ErrCtx(), store, s.Table.Schema, tbInfo); err != nil {
return nil, err
}
return tbInfo, nil
}
// BuildTableInfoWithStmt builds model.TableInfo from a SQL statement without validity check
func BuildTableInfoWithStmt(ctx *metabuild.Context, s *ast.CreateTableStmt, dbCharset, dbCollate string, placementPolicyRef *model.PolicyRefInfo) (*model.TableInfo, error) {
colDefs := s.Cols
tableCharset, tableCollate, err := GetCharsetAndCollateInTableOption(0, s.Options, ctx.GetDefaultCollationForUTF8MB4())
if err != nil {
return nil, errors.Trace(err)
}
tableCharset, tableCollate, err = ResolveCharsetCollation([]ast.CharsetOpt{
{Chs: tableCharset, Col: tableCollate},
{Chs: dbCharset, Col: dbCollate},
}, ctx.GetDefaultCollationForUTF8MB4())
if err != nil {
return nil, errors.Trace(err)
}
// The column charset haven't been resolved here.
cols, newConstraints, err := buildColumnsAndConstraints(ctx, colDefs, s.Constraints, tableCharset, tableCollate)
if err != nil {
return nil, errors.Trace(err)
}
err = checkConstraintNames(s.Table.Name, newConstraints)
if err != nil {
return nil, errors.Trace(err)
}
var tbInfo *model.TableInfo
tbInfo, err = BuildTableInfo(ctx, s.Table.Name, cols, newConstraints, tableCharset, tableCollate)
if err != nil {
return nil, errors.Trace(err)
}
if err = setTemporaryType(tbInfo, s); err != nil {
return nil, errors.Trace(err)
}
if err = setTableAutoRandomBits(ctx, tbInfo, colDefs); err != nil {
return nil, errors.Trace(err)
}
// set default shard row id bits and pre-split regions for table.
if !tbInfo.HasClusteredIndex() && tbInfo.TempTableType == model.TempTableNone {
tbInfo.ShardRowIDBits = ctx.GetShardRowIDBits()
tbInfo.MaxShardRowIDBits = tbInfo.ShardRowIDBits
tbInfo.PreSplitRegions = ctx.GetPreSplitRegions()
}
if err = handleTableOptions(s.Options, tbInfo); err != nil {
return nil, errors.Trace(err)
}
if _, err = validateCommentLength(ctx.GetExprCtx().GetEvalCtx().ErrCtx(), ctx.GetSQLMode(), tbInfo.Name.L, &tbInfo.Comment, dbterror.ErrTooLongTableComment); err != nil {
return nil, errors.Trace(err)
}
if tbInfo.TempTableType == model.TempTableNone && tbInfo.PlacementPolicyRef == nil && placementPolicyRef != nil {
// Set the defaults from Schema. Note: they are mutual exclusive!
tbInfo.PlacementPolicyRef = placementPolicyRef
}
// After handleTableOptions, so the partitions can get defaults from Table level
err = buildTablePartitionInfo(ctx, s.Partition, tbInfo)
if err != nil {
return nil, errors.Trace(err)
}
// validateTableAffinity settings, this should be after buildTablePartitionInfo for some partition checks
if err = validateTableAffinity(tbInfo, tbInfo.Affinity); err != nil {
return nil, errors.Trace(err)
}
return tbInfo, nil
}
func setTableAutoRandomBits(ctx *metabuild.Context, tbInfo *model.TableInfo, colDefs []*ast.ColumnDef) error {
for _, col := range colDefs {
if containsColumnOption(col, ast.ColumnOptionAutoRandom) {
if col.Tp.GetType() != mysql.TypeLonglong {
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(
fmt.Sprintf(autoid.AutoRandomOnNonBigIntColumn, types.TypeStr(col.Tp.GetType())))
}
switch {
case tbInfo.PKIsHandle:
if tbInfo.GetPkName().L != col.Name.Name.L {
errMsg := fmt.Sprintf(autoid.AutoRandomMustFirstColumnInPK, col.Name.Name.O)
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(errMsg)
}
case tbInfo.IsCommonHandle:
pk := tables.FindPrimaryIndex(tbInfo)
if pk == nil {
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(autoid.AutoRandomNoClusteredPKErrMsg)
}
if col.Name.Name.L != pk.Columns[0].Name.L {
errMsg := fmt.Sprintf(autoid.AutoRandomMustFirstColumnInPK, col.Name.Name.O)
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(errMsg)
}
default:
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(autoid.AutoRandomNoClusteredPKErrMsg)
}
if containsColumnOption(col, ast.ColumnOptionAutoIncrement) {
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(autoid.AutoRandomIncompatibleWithAutoIncErrMsg)
}
if containsColumnOption(col, ast.ColumnOptionDefaultValue) {
return dbterror.ErrInvalidAutoRandom.GenWithStackByArgs(autoid.AutoRandomIncompatibleWithDefaultValueErrMsg)
}
shardBits, rangeBits, err := extractAutoRandomBitsFromColDef(col)
if err != nil {
return errors.Trace(err)
}
tbInfo.AutoRandomBits = shardBits
tbInfo.AutoRandomRangeBits = rangeBits
shardFmt := autoid.NewShardIDFormat(col.Tp, shardBits, rangeBits)
if shardFmt.IncrementalBits < autoid.AutoRandomIncBitsMin {
return dbterror.ErrInvalidAutoRandom.FastGenByArgs(autoid.AutoRandomIncrementalBitsTooSmall)
}
msg := fmt.Sprintf(autoid.AutoRandomAvailableAllocTimesNote, shardFmt.IncrementalBitsCapacity())
ctx.AppendNote(errors.NewNoStackError(msg))
}
}
return nil
}
func containsColumnOption(colDef *ast.ColumnDef, opTp ast.ColumnOptionType) bool {
for _, option := range colDef.Options {
if option.Tp == opTp {
return true
}
}
return false
}
func extractAutoRandomBitsFromColDef(colDef *ast.ColumnDef) (shardBits, rangeBits uint64, err error) {
for _, op := range colDef.Options {
if op.Tp == ast.ColumnOptionAutoRandom {
shardBits, err = autoid.AutoRandomShardBitsNormalize(op.AutoRandOpt.ShardBits, colDef.Name.Name.O)
if err != nil {
return 0, 0, err
}
rangeBits, err = autoid.AutoRandomRangeBitsNormalize(op.AutoRandOpt.RangeBits)
if err != nil {
return 0, 0, err
}
return shardBits, rangeBits, nil
}
}
return 0, 0, nil
}
// handleTableOptions updates tableInfo according to table options.
func handleTableOptions(options []*ast.TableOption, tbInfo *model.TableInfo) error {
var ttlOptionsHandled bool
engineAttribute, hasEngineAttribute, engineAttributeErr := GetEngineAttributeFromStorageClassTableOptions(options)
if engineAttributeErr != nil {
return engineAttributeErr
}
for _, op := range options {
switch op.Tp {
case ast.TableOptionAutoIncrement:
tbInfo.AutoIncID = int64(op.UintValue)
case ast.TableOptionAutoIdCache:
if op.UintValue > uint64(math.MaxInt64) {
// TODO: Refine this error.
return errors.New("table option auto_id_cache overflows int64")
}
tbInfo.AutoIDCache = int64(op.UintValue)
case ast.TableOptionAutoRandomBase:
tbInfo.AutoRandID = int64(op.UintValue)
case ast.TableOptionComment:
tbInfo.Comment = op.StrValue
case ast.TableOptionCompression:
tbInfo.Compression = op.StrValue
case ast.TableOptionShardRowID:
if op.UintValue > 0 && tbInfo.HasClusteredIndex() {
return dbterror.ErrUnsupportedShardRowIDBits
}
tbInfo.ShardRowIDBits = min(op.UintValue, vardef.MaxShardRowIDBits)
tbInfo.MaxShardRowIDBits = tbInfo.ShardRowIDBits
case ast.TableOptionPreSplitRegion:
if tbInfo.TempTableType != model.TempTableNone {
return errors.Trace(dbterror.ErrOptOnTemporaryTable.GenWithStackByArgs("pre split regions"))
}
tbInfo.PreSplitRegions = op.UintValue
case ast.TableOptionCharset, ast.TableOptionCollate:
// We don't handle charset and collate here since they're handled in `GetCharsetAndCollateInTableOption`.
case ast.TableOptionPlacementPolicy:
tbInfo.PlacementPolicyRef = &model.PolicyRefInfo{
Name: ast.NewCIStr(op.StrValue),
}
case ast.TableOptionTTL, ast.TableOptionTTLEnable, ast.TableOptionTTLJobInterval:
if ttlOptionsHandled {
continue
}
ttlInfo, ttlEnable, ttlJobInterval, err := getTTLInfoInOptions(options)
if err != nil {
return err
}
// It's impossible that `ttlInfo` and `ttlEnable` are all nil, because we have met this option.
// After exclude the situation `ttlInfo == nil && ttlEnable != nil`, we could say `ttlInfo != nil`
if ttlInfo == nil {
if ttlEnable != nil {
return errors.Trace(dbterror.ErrSetTTLOptionForNonTTLTable.FastGenByArgs("TTL_ENABLE"))
}