-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathpartition.go
4253 lines (3908 loc) · 148 KB
/
partition.go
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 2018 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 (
"bytes"
"context"
"encoding/hex"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/tidb/config"
sess "github.com/pingcap/tidb/ddl/internal/session"
"github.com/pingcap/tidb/ddl/label"
"github.com/pingcap/tidb/ddl/placement"
"github.com/pingcap/tidb/ddl/util"
"github.com/pingcap/tidb/domain/infosync"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/infoschema"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/parser"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/format"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/opcode"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/table"
"github.com/pingcap/tidb/table/tables"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/types"
driver "github.com/pingcap/tidb/types/parser_driver"
tidbutil "github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/collate"
"github.com/pingcap/tidb/util/dbterror"
"github.com/pingcap/tidb/util/hack"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/mathutil"
"github.com/pingcap/tidb/util/mock"
decoder "github.com/pingcap/tidb/util/rowDecoder"
"github.com/pingcap/tidb/util/slice"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/stringutil"
"github.com/tikv/client-go/v2/tikv"
kvutil "github.com/tikv/client-go/v2/util"
"go.uber.org/zap"
)
const (
partitionMaxValue = "MAXVALUE"
)
func checkAddPartition(t *meta.Meta, job *model.Job) (*model.TableInfo, *model.PartitionInfo, []model.PartitionDefinition, error) {
schemaID := job.SchemaID
tblInfo, err := GetTableInfoAndCancelFaultJob(t, job, schemaID)
if err != nil {
return nil, nil, nil, errors.Trace(err)
}
partInfo := &model.PartitionInfo{}
err = job.DecodeArgs(&partInfo)
if err != nil {
job.State = model.JobStateCancelled
return nil, nil, nil, errors.Trace(err)
}
if len(tblInfo.Partition.AddingDefinitions) > 0 {
return tblInfo, partInfo, tblInfo.Partition.AddingDefinitions, nil
}
return tblInfo, partInfo, []model.PartitionDefinition{}, nil
}
// TODO: Move this into reorganize partition!
func (w *worker) onAddTablePartition(d *ddlCtx, t *meta.Meta, job *model.Job) (ver int64, _ error) {
// Handle the rolling back job
if job.IsRollingback() {
ver, err := w.onDropTablePartition(d, t, job)
if err != nil {
return ver, errors.Trace(err)
}
return ver, nil
}
// notice: addingDefinitions is empty when job is in state model.StateNone
tblInfo, partInfo, addingDefinitions, err := checkAddPartition(t, job)
if err != nil {
return ver, err
}
// In order to skip maintaining the state check in partitionDefinition, TiDB use addingDefinition instead of state field.
// So here using `job.SchemaState` to judge what the stage of this job is.
switch job.SchemaState {
case model.StateNone:
// job.SchemaState == model.StateNone means the job is in the initial state of add partition.
// Here should use partInfo from job directly and do some check action.
err = checkAddPartitionTooManyPartitions(uint64(len(tblInfo.Partition.Definitions) + len(partInfo.Definitions)))
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
err = checkAddPartitionValue(tblInfo, partInfo)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
err = checkAddPartitionNameUnique(tblInfo, partInfo)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
// move the adding definition into tableInfo.
updateAddingPartitionInfo(partInfo, tblInfo)
ver, err = updateVersionAndTableInfoWithCheck(d, t, job, tblInfo, true)
if err != nil {
return ver, errors.Trace(err)
}
// modify placement settings
for _, def := range tblInfo.Partition.AddingDefinitions {
if _, err = checkPlacementPolicyRefValidAndCanNonValidJob(t, job, def.PlacementPolicyRef); err != nil {
return ver, errors.Trace(err)
}
}
if tblInfo.TiFlashReplica != nil {
// Must set placement rule, and make sure it succeeds.
if err := infosync.ConfigureTiFlashPDForPartitions(true, &tblInfo.Partition.AddingDefinitions, tblInfo.TiFlashReplica.Count, &tblInfo.TiFlashReplica.LocationLabels, tblInfo.ID); err != nil {
logutil.BgLogger().Error("ConfigureTiFlashPDForPartitions fails", zap.Error(err))
return ver, errors.Trace(err)
}
}
bundles, err := alterTablePartitionBundles(t, tblInfo, tblInfo.Partition.AddingDefinitions)
if err != nil {
job.State = model.JobStateCancelled
return ver, errors.Trace(err)
}
if err = infosync.PutRuleBundlesWithDefaultRetry(context.TODO(), bundles); err != nil {
job.State = model.JobStateCancelled
return ver, errors.Wrapf(err, "failed to notify PD the placement rules")
}
ids := getIDs([]*model.TableInfo{tblInfo})
for _, p := range tblInfo.Partition.AddingDefinitions {
ids = append(ids, p.ID)
}
if _, err := alterTableLabelRule(job.SchemaName, tblInfo, ids); err != nil {
job.State = model.JobStateCancelled
return ver, err
}
// none -> replica only
job.SchemaState = model.StateReplicaOnly
case model.StateReplicaOnly:
// replica only -> public
failpoint.Inject("sleepBeforeReplicaOnly", func(val failpoint.Value) {
sleepSecond := val.(int)
time.Sleep(time.Duration(sleepSecond) * time.Second)
})
// Here need do some tiflash replica complement check.
// TODO: If a table is with no TiFlashReplica or it is not available, the replica-only state can be eliminated.
if tblInfo.TiFlashReplica != nil && tblInfo.TiFlashReplica.Available {
// For available state, the new added partition should wait it's replica to
// be finished. Otherwise the query to this partition will be blocked.
needRetry, err := checkPartitionReplica(tblInfo.TiFlashReplica.Count, addingDefinitions, d)
if err != nil {
return convertAddTablePartitionJob2RollbackJob(d, t, job, err, tblInfo)
}
if needRetry {
// The new added partition hasn't been replicated.
// Do nothing to the job this time, wait next worker round.
time.Sleep(tiflashCheckTiDBHTTPAPIHalfInterval)
// Set the error here which will lead this job exit when it's retry times beyond the limitation.
return ver, errors.Errorf("[ddl] add partition wait for tiflash replica to complete")
}
}
// When TiFlash Replica is ready, we must move them into `AvailablePartitionIDs`.
if tblInfo.TiFlashReplica != nil && tblInfo.TiFlashReplica.Available {
for _, d := range partInfo.Definitions {
tblInfo.TiFlashReplica.AvailablePartitionIDs = append(tblInfo.TiFlashReplica.AvailablePartitionIDs, d.ID)
err = infosync.UpdateTiFlashProgressCache(d.ID, 1)
if err != nil {
// just print log, progress will be updated in `refreshTiFlashTicker`
logutil.BgLogger().Error("update tiflash sync progress cache failed",
zap.Error(err),
zap.Int64("tableID", tblInfo.ID),
zap.Int64("partitionID", d.ID),
)
}
}
}
// For normal and replica finished table, move the `addingDefinitions` into `Definitions`.
updatePartitionInfo(tblInfo)
preSplitAndScatter(w.sess.Context, d.store, tblInfo, addingDefinitions)
ver, err = updateVersionAndTableInfo(d, t, job, tblInfo, true)
if err != nil {
return ver, errors.Trace(err)
}
// Finish this job.
job.FinishTableJob(model.JobStateDone, model.StatePublic, ver, tblInfo)
asyncNotifyEvent(d, &util.Event{Tp: model.ActionAddTablePartition, TableInfo: tblInfo, PartInfo: partInfo})
default:
err = dbterror.ErrInvalidDDLState.GenWithStackByArgs("partition", job.SchemaState)
}
return ver, errors.Trace(err)
}
// alterTableLabelRule updates Label Rules if they exists
// returns true if changed.
func alterTableLabelRule(schemaName string, meta *model.TableInfo, ids []int64) (bool, error) {
tableRuleID := fmt.Sprintf(label.TableIDFormat, label.IDPrefix, schemaName, meta.Name.L)
oldRule, err := infosync.GetLabelRules(context.TODO(), []string{tableRuleID})
if err != nil {
return false, errors.Trace(err)
}
if len(oldRule) == 0 {
return false, nil
}
r, ok := oldRule[tableRuleID]
if ok {
rule := r.Reset(schemaName, meta.Name.L, "", ids...)
err = infosync.PutLabelRule(context.TODO(), rule)
if err != nil {
return false, errors.Wrapf(err, "failed to notify PD label rule")
}
return true, nil
}
return false, nil
}
func alterTablePartitionBundles(t *meta.Meta, tblInfo *model.TableInfo, addingDefinitions []model.PartitionDefinition) ([]*placement.Bundle, error) {
var bundles []*placement.Bundle
// tblInfo do not include added partitions, so we should add them first
tblInfo = tblInfo.Clone()
p := *tblInfo.Partition
p.Definitions = append([]model.PartitionDefinition{}, p.Definitions...)
p.Definitions = append(tblInfo.Partition.Definitions, addingDefinitions...)
tblInfo.Partition = &p
// bundle for table should be recomputed because it includes some default configs for partitions
tblBundle, err := placement.NewTableBundle(t, tblInfo)
if err != nil {
return nil, errors.Trace(err)
}
if tblBundle != nil {
bundles = append(bundles, tblBundle)
}
partitionBundles, err := placement.NewPartitionListBundles(t, addingDefinitions)
if err != nil {
return nil, errors.Trace(err)
}
bundles = append(bundles, partitionBundles...)
return bundles, nil
}
// When drop/truncate a partition, we should still keep the dropped partition's placement settings to avoid unnecessary region schedules.
// When a partition is not configured with a placement policy directly, its rule is in the table's placement group which will be deleted after
// partition truncated/dropped. So it is necessary to create a standalone placement group with partition id after it.
func droppedPartitionBundles(t *meta.Meta, tblInfo *model.TableInfo, dropPartitions []model.PartitionDefinition) ([]*placement.Bundle, error) {
partitions := make([]model.PartitionDefinition, 0, len(dropPartitions))
for _, def := range dropPartitions {
def = def.Clone()
if def.PlacementPolicyRef == nil {
def.PlacementPolicyRef = tblInfo.PlacementPolicyRef
}
if def.PlacementPolicyRef != nil {
partitions = append(partitions, def)
}
}
return placement.NewPartitionListBundles(t, partitions)
}
// updatePartitionInfo merge `addingDefinitions` into `Definitions` in the tableInfo.
func updatePartitionInfo(tblInfo *model.TableInfo) {
parInfo := &model.PartitionInfo{}
oldDefs, newDefs := tblInfo.Partition.Definitions, tblInfo.Partition.AddingDefinitions
parInfo.Definitions = make([]model.PartitionDefinition, 0, len(newDefs)+len(oldDefs))
parInfo.Definitions = append(parInfo.Definitions, oldDefs...)
parInfo.Definitions = append(parInfo.Definitions, newDefs...)
tblInfo.Partition.Definitions = parInfo.Definitions
tblInfo.Partition.AddingDefinitions = nil
}
// updateAddingPartitionInfo write adding partitions into `addingDefinitions` field in the tableInfo.
func updateAddingPartitionInfo(partitionInfo *model.PartitionInfo, tblInfo *model.TableInfo) {
newDefs := partitionInfo.Definitions
tblInfo.Partition.AddingDefinitions = make([]model.PartitionDefinition, 0, len(newDefs))
tblInfo.Partition.AddingDefinitions = append(tblInfo.Partition.AddingDefinitions, newDefs...)
}
// rollbackAddingPartitionInfo remove the `addingDefinitions` in the tableInfo.
func rollbackAddingPartitionInfo(tblInfo *model.TableInfo) ([]int64, []string, []*placement.Bundle) {
physicalTableIDs := make([]int64, 0, len(tblInfo.Partition.AddingDefinitions))
partNames := make([]string, 0, len(tblInfo.Partition.AddingDefinitions))
rollbackBundles := make([]*placement.Bundle, 0, len(tblInfo.Partition.AddingDefinitions))
for _, one := range tblInfo.Partition.AddingDefinitions {
physicalTableIDs = append(physicalTableIDs, one.ID)
partNames = append(partNames, one.Name.L)
if one.PlacementPolicyRef != nil {
rollbackBundles = append(rollbackBundles, placement.NewBundle(one.ID))
}
}
tblInfo.Partition.AddingDefinitions = nil
return physicalTableIDs, partNames, rollbackBundles
}
// Check if current table already contains DEFAULT list partition
func checkAddListPartitions(tblInfo *model.TableInfo) error {
for i := range tblInfo.Partition.Definitions {
for j := range tblInfo.Partition.Definitions[i].InValues {
for _, val := range tblInfo.Partition.Definitions[i].InValues[j] {
if val == "DEFAULT" { // should already be normalized
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("ADD List partition, already contains DEFAULT partition. Please use REORGANIZE PARTITION instead")
}
}
}
}
return nil
}
// checkAddPartitionValue check add Partition Values,
// For Range: values less than value must be strictly increasing for each partition.
// For List: if a Default partition exists,
//
// no ADD partition can be allowed
// (needs reorganize partition instead).
func checkAddPartitionValue(meta *model.TableInfo, part *model.PartitionInfo) error {
switch meta.Partition.Type {
case model.PartitionTypeRange:
if len(meta.Partition.Columns) == 0 {
newDefs, oldDefs := part.Definitions, meta.Partition.Definitions
rangeValue := oldDefs[len(oldDefs)-1].LessThan[0]
if strings.EqualFold(rangeValue, "MAXVALUE") {
return errors.Trace(dbterror.ErrPartitionMaxvalue)
}
currentRangeValue, err := strconv.Atoi(rangeValue)
if err != nil {
return errors.Trace(err)
}
for i := 0; i < len(newDefs); i++ {
ifMaxvalue := strings.EqualFold(newDefs[i].LessThan[0], "MAXVALUE")
if ifMaxvalue && i == len(newDefs)-1 {
return nil
} else if ifMaxvalue && i != len(newDefs)-1 {
return errors.Trace(dbterror.ErrPartitionMaxvalue)
}
nextRangeValue, err := strconv.Atoi(newDefs[i].LessThan[0])
if err != nil {
return errors.Trace(err)
}
if nextRangeValue <= currentRangeValue {
return errors.Trace(dbterror.ErrRangeNotIncreasing)
}
currentRangeValue = nextRangeValue
}
}
case model.PartitionTypeList:
err := checkAddListPartitions(meta)
if err != nil {
return err
}
}
return nil
}
func checkPartitionReplica(replicaCount uint64, addingDefinitions []model.PartitionDefinition, d *ddlCtx) (needWait bool, err error) {
failpoint.Inject("mockWaitTiFlashReplica", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(true, nil)
}
})
failpoint.Inject("mockWaitTiFlashReplicaOK", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(false, nil)
}
})
ctx := context.Background()
pdCli := d.store.(tikv.Storage).GetRegionCache().PDClient()
stores, err := pdCli.GetAllStores(ctx)
if err != nil {
return needWait, errors.Trace(err)
}
// Check whether stores have `count` tiflash engines.
tiFlashStoreCount := uint64(0)
for _, store := range stores {
if storeHasEngineTiFlashLabel(store) {
tiFlashStoreCount++
}
}
if replicaCount > tiFlashStoreCount {
return false, errors.Errorf("[ddl] the tiflash replica count: %d should be less than the total tiflash server count: %d", replicaCount, tiFlashStoreCount)
}
for _, pd := range addingDefinitions {
startKey, endKey := tablecodec.GetTableHandleKeyRange(pd.ID)
regions, err := pdCli.ScanRegions(ctx, startKey, endKey, -1)
if err != nil {
return needWait, errors.Trace(err)
}
// For every region in the partition, if it has some corresponding peers and
// no pending peers, that means the replication has completed.
for _, region := range regions {
regionState, err := pdCli.GetRegionByID(ctx, region.Meta.Id)
if err != nil {
return needWait, errors.Trace(err)
}
tiflashPeerAtLeastOne := checkTiFlashPeerStoreAtLeastOne(stores, regionState.Meta.Peers)
failpoint.Inject("ForceTiflashNotAvailable", func(v failpoint.Value) {
tiflashPeerAtLeastOne = v.(bool)
})
// It's unnecessary to wait all tiflash peer to be replicated.
// Here only make sure that tiflash peer count > 0 (at least one).
if tiflashPeerAtLeastOne {
continue
}
needWait = true
logutil.BgLogger().Info("partition replicas check failed in replica-only DDL state", zap.String("category", "ddl"), zap.Int64("pID", pd.ID), zap.Uint64("wait region ID", region.Meta.Id), zap.Bool("tiflash peer at least one", tiflashPeerAtLeastOne), zap.Time("check time", time.Now()))
return needWait, nil
}
}
logutil.BgLogger().Info("partition replicas check ok in replica-only DDL state", zap.String("category", "ddl"))
return needWait, nil
}
func checkTiFlashPeerStoreAtLeastOne(stores []*metapb.Store, peers []*metapb.Peer) bool {
for _, peer := range peers {
for _, store := range stores {
if peer.StoreId == store.Id && storeHasEngineTiFlashLabel(store) {
return true
}
}
}
return false
}
func storeHasEngineTiFlashLabel(store *metapb.Store) bool {
for _, label := range store.Labels {
if label.Key == placement.EngineLabelKey && label.Value == placement.EngineLabelTiFlash {
return true
}
}
return false
}
func checkListPartitions(defs []*ast.PartitionDefinition) error {
for _, def := range defs {
_, ok := def.Clause.(*ast.PartitionDefinitionClauseIn)
if !ok {
switch def.Clause.(type) {
case *ast.PartitionDefinitionClauseLessThan:
return ast.ErrPartitionWrongValues.GenWithStackByArgs("RANGE", "LESS THAN")
case *ast.PartitionDefinitionClauseNone:
return ast.ErrPartitionRequiresValues.GenWithStackByArgs("LIST", "IN")
default:
return dbterror.ErrUnsupportedCreatePartition.GenWithStack("Only VALUES IN () is supported for LIST partitioning")
}
}
}
return nil
}
// buildTablePartitionInfo builds partition info and checks for some errors.
func buildTablePartitionInfo(ctx sessionctx.Context, s *ast.PartitionOptions, tbInfo *model.TableInfo) error {
if s == nil {
return nil
}
if strings.EqualFold(ctx.GetSessionVars().EnableTablePartition, "OFF") {
ctx.GetSessionVars().StmtCtx.AppendWarning(dbterror.ErrTablePartitionDisabled)
return nil
}
var enable bool
switch s.Tp {
case model.PartitionTypeRange:
enable = true
case model.PartitionTypeList:
// Partition by list is enabled only when tidb_enable_list_partition is 'ON'.
enable = ctx.GetSessionVars().EnableListTablePartition
if enable {
err := checkListPartitions(s.Definitions)
if err != nil {
return err
}
}
case model.PartitionTypeHash, model.PartitionTypeKey:
// Partition by hash and key is enabled by default.
if s.Sub != nil {
// Subpartitioning only allowed with Range or List
return ast.ErrSubpartition
}
// Note that linear hash is simply ignored, and creates non-linear hash/key.
if s.Linear {
ctx.GetSessionVars().StmtCtx.AppendWarning(dbterror.ErrUnsupportedCreatePartition.GenWithStack(fmt.Sprintf("LINEAR %s is not supported, using non-linear %s instead", s.Tp.String(), s.Tp.String())))
}
if s.Tp == model.PartitionTypeHash || len(s.ColumnNames) != 0 {
enable = true
}
}
if !enable {
ctx.GetSessionVars().StmtCtx.AppendWarning(dbterror.ErrUnsupportedCreatePartition.GenWithStack(fmt.Sprintf("Unsupported partition type %v, treat as normal table", s.Tp)))
return nil
}
if s.Sub != nil {
ctx.GetSessionVars().StmtCtx.AppendWarning(dbterror.ErrUnsupportedCreatePartition.GenWithStack(fmt.Sprintf("Unsupported subpartitioning, only using %v partitioning", s.Tp)))
}
pi := &model.PartitionInfo{
Type: s.Tp,
Enable: enable,
Num: s.Num,
}
tbInfo.Partition = pi
if s.Expr != nil {
if err := checkPartitionFuncValid(ctx, tbInfo, s.Expr); err != nil {
return errors.Trace(err)
}
buf := new(bytes.Buffer)
restoreCtx := format.NewRestoreCtx(format.DefaultRestoreFlags|format.RestoreBracketAroundBinaryOperation, buf)
if err := s.Expr.Restore(restoreCtx); err != nil {
return err
}
pi.Expr = buf.String()
} else if s.ColumnNames != nil {
pi.Columns = make([]model.CIStr, 0, len(s.ColumnNames))
for _, cn := range s.ColumnNames {
pi.Columns = append(pi.Columns, cn.Name)
}
if err := checkColumnsPartitionType(tbInfo); err != nil {
return err
}
}
err := generatePartitionDefinitionsFromInterval(ctx, s, tbInfo)
if err != nil {
return errors.Trace(err)
}
defs, err := buildPartitionDefinitionsInfo(ctx, s.Definitions, tbInfo, s.Num)
if err != nil {
return errors.Trace(err)
}
tbInfo.Partition.Definitions = defs
if s.Interval != nil {
// Syntactic sugar for INTERVAL partitioning
// Generate the resulting CREATE TABLE as the query string
query, ok := ctx.Value(sessionctx.QueryString).(string)
if ok {
sqlMode := ctx.GetSessionVars().SQLMode
var buf bytes.Buffer
AppendPartitionDefs(tbInfo.Partition, &buf, sqlMode)
syntacticSugar := s.Interval.OriginalText()
syntacticStart := s.Interval.OriginTextPosition()
newQuery := query[:syntacticStart] + "(" + buf.String() + ")" + query[syntacticStart+len(syntacticSugar):]
ctx.SetValue(sessionctx.QueryString, newQuery)
}
}
partCols, err := getPartitionColSlices(ctx, tbInfo, s)
if err != nil {
return errors.Trace(err)
}
for _, index := range tbInfo.Indices {
if index.Unique && !checkUniqueKeyIncludePartKey(partCols, index.Columns) {
index.Global = config.GetGlobalConfig().EnableGlobalIndex
}
}
return nil
}
func getPartitionColSlices(sctx sessionctx.Context, tblInfo *model.TableInfo, s *ast.PartitionOptions) (partCols stringSlice, err error) {
if s.Expr != nil {
extractCols := newPartitionExprChecker(sctx, tblInfo)
s.Expr.Accept(extractCols)
partColumns, err := extractCols.columns, extractCols.err
if err != nil {
return nil, err
}
partCols = columnInfoSlice(partColumns)
} else if len(s.ColumnNames) > 0 {
partCols = columnNameSlice(s.ColumnNames)
} else {
return nil, errors.Errorf("Table partition metadata not correct, neither partition expression or list of partition columns")
}
return partCols, nil
}
// getPartitionIntervalFromTable checks if a partitioned table matches a generated INTERVAL partitioned scheme
// will return nil if error occurs, i.e. not an INTERVAL partitioned table
func getPartitionIntervalFromTable(ctx sessionctx.Context, tbInfo *model.TableInfo) *ast.PartitionInterval {
if tbInfo.Partition == nil ||
tbInfo.Partition.Type != model.PartitionTypeRange {
return nil
}
if len(tbInfo.Partition.Columns) > 1 {
// Multi-column RANGE COLUMNS is not supported with INTERVAL
return nil
}
if len(tbInfo.Partition.Definitions) < 2 {
// Must have at least two partitions to calculate an INTERVAL
return nil
}
var (
interval ast.PartitionInterval
startIdx = 0
endIdx = len(tbInfo.Partition.Definitions) - 1
isIntType = true
minVal = "0"
)
if len(tbInfo.Partition.Columns) > 0 {
partCol := findColumnByName(tbInfo.Partition.Columns[0].L, tbInfo)
if partCol.FieldType.EvalType() == types.ETInt {
min := getLowerBoundInt(partCol)
minVal = strconv.FormatInt(min, 10)
} else if partCol.FieldType.EvalType() == types.ETDatetime {
isIntType = false
minVal = "0000-01-01"
} else {
// Only INT and Datetime columns are supported for INTERVAL partitioning
return nil
}
} else {
if !isPartExprUnsigned(tbInfo) {
minVal = "-9223372036854775808"
}
}
// Check if possible null partition
firstPartLessThan := driver.UnwrapFromSingleQuotes(tbInfo.Partition.Definitions[0].LessThan[0])
if strings.EqualFold(firstPartLessThan, minVal) {
interval.NullPart = true
startIdx++
firstPartLessThan = driver.UnwrapFromSingleQuotes(tbInfo.Partition.Definitions[startIdx].LessThan[0])
}
// flag if MAXVALUE partition
lastPartLessThan := driver.UnwrapFromSingleQuotes(tbInfo.Partition.Definitions[endIdx].LessThan[0])
if strings.EqualFold(lastPartLessThan, partitionMaxValue) {
interval.MaxValPart = true
endIdx--
lastPartLessThan = driver.UnwrapFromSingleQuotes(tbInfo.Partition.Definitions[endIdx].LessThan[0])
}
// Guess the interval
if startIdx >= endIdx {
// Must have at least two partitions to calculate an INTERVAL
return nil
}
var firstExpr, lastExpr ast.ExprNode
if isIntType {
exprStr := fmt.Sprintf("((%s) - (%s)) DIV %d", lastPartLessThan, firstPartLessThan, endIdx-startIdx)
exprs, err := expression.ParseSimpleExprsWithNames(ctx, exprStr, nil, nil)
if err != nil {
return nil
}
val, isNull, err := exprs[0].EvalInt(ctx, chunk.Row{})
if isNull || err != nil || val < 1 {
// If NULL, error or interval < 1 then cannot be an INTERVAL partitioned table
return nil
}
interval.IntervalExpr.Expr = ast.NewValueExpr(val, "", "")
interval.IntervalExpr.TimeUnit = ast.TimeUnitInvalid
firstExpr, err = astIntValueExprFromStr(firstPartLessThan, minVal == "0")
if err != nil {
return nil
}
interval.FirstRangeEnd = &firstExpr
lastExpr, err = astIntValueExprFromStr(lastPartLessThan, minVal == "0")
if err != nil {
return nil
}
interval.LastRangeEnd = &lastExpr
} else { // types.ETDatetime
exprStr := fmt.Sprintf("TIMESTAMPDIFF(SECOND, '%s', '%s')", firstPartLessThan, lastPartLessThan)
exprs, err := expression.ParseSimpleExprsWithNames(ctx, exprStr, nil, nil)
if err != nil {
return nil
}
val, isNull, err := exprs[0].EvalInt(ctx, chunk.Row{})
if isNull || err != nil || val < 1 {
// If NULL, error or interval < 1 then cannot be an INTERVAL partitioned table
return nil
}
// This will not find all matches > 28 days, since INTERVAL 1 MONTH can generate
// 2022-01-31, 2022-02-28, 2022-03-31 etc. so we just assume that if there is a
// diff >= 28 days, we will try with Month and not retry with something else...
i := val / int64(endIdx-startIdx)
if i < (28 * 24 * 60 * 60) {
// Since it is not stored or displayed, non need to try Minute..Week!
interval.IntervalExpr.Expr = ast.NewValueExpr(i, "", "")
interval.IntervalExpr.TimeUnit = ast.TimeUnitSecond
} else {
// Since it is not stored or displayed, non need to try to match Quarter or Year!
if (endIdx - startIdx) <= 3 {
// in case February is in the range
i = i / (28 * 24 * 60 * 60)
} else {
// This should be good for intervals up to 5 years
i = i / (30 * 24 * 60 * 60)
}
interval.IntervalExpr.Expr = ast.NewValueExpr(i, "", "")
interval.IntervalExpr.TimeUnit = ast.TimeUnitMonth
}
firstExpr = ast.NewValueExpr(firstPartLessThan, "", "")
lastExpr = ast.NewValueExpr(lastPartLessThan, "", "")
interval.FirstRangeEnd = &firstExpr
interval.LastRangeEnd = &lastExpr
}
partitionMethod := ast.PartitionMethod{
Tp: model.PartitionTypeRange,
Interval: &interval,
}
partOption := &ast.PartitionOptions{PartitionMethod: partitionMethod}
// Generate the definitions from interval, first and last
err := generatePartitionDefinitionsFromInterval(ctx, partOption, tbInfo)
if err != nil {
return nil
}
return &interval
}
// comparePartitionAstAndModel compares a generated *ast.PartitionOptions and a *model.PartitionInfo
func comparePartitionAstAndModel(ctx sessionctx.Context, pAst *ast.PartitionOptions, pModel *model.PartitionInfo) error {
a := pAst.Definitions
m := pModel.Definitions
if len(pAst.Definitions) != len(pModel.Definitions) {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning: number of partitions generated != partition defined (%d != %d)", len(a), len(m))
}
for i := range pAst.Definitions {
// Allow options to differ! (like Placement Rules)
// Allow names to differ!
// Check MAXVALUE
maxVD := false
if strings.EqualFold(m[i].LessThan[0], partitionMaxValue) {
maxVD = true
}
generatedExpr := a[i].Clause.(*ast.PartitionDefinitionClauseLessThan).Exprs[0]
_, maxVG := generatedExpr.(*ast.MaxValueExpr)
if maxVG || maxVD {
if maxVG && maxVD {
continue
}
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("INTERVAL partitioning: MAXVALUE clause defined for partition %s differs between generated and defined", m[i].Name.O))
}
lessThan := m[i].LessThan[0]
if len(lessThan) > 1 && lessThan[:1] == "'" && lessThan[len(lessThan)-1:] == "'" {
lessThan = driver.UnwrapFromSingleQuotes(lessThan)
}
cmpExpr := &ast.BinaryOperationExpr{
Op: opcode.EQ,
L: ast.NewValueExpr(lessThan, "", ""),
R: generatedExpr,
}
cmp, err := expression.EvalAstExpr(ctx, cmpExpr)
if err != nil {
return err
}
if cmp.GetInt64() != 1 {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("INTERVAL partitioning: LESS THAN for partition %s differs between generated and defined", m[i].Name.O))
}
}
return nil
}
// comparePartitionDefinitions check if generated definitions are the same as the given ones
// Allow names to differ
// returns error in case of error or non-accepted difference
func comparePartitionDefinitions(ctx sessionctx.Context, a, b []*ast.PartitionDefinition) error {
if len(a) != len(b) {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("number of partitions generated != partition defined (%d != %d)", len(a), len(b))
}
for i := range a {
if len(b[i].Sub) > 0 {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("partition %s does have unsupported subpartitions", b[i].Name.O))
}
// TODO: We could extend the syntax to allow for table options too, like:
// CREATE TABLE t ... INTERVAL ... LAST PARTITION LESS THAN ('2015-01-01') PLACEMENT POLICY = 'cheapStorage'
// ALTER TABLE t LAST PARTITION LESS THAN ('2022-01-01') PLACEMENT POLICY 'defaultStorage'
// ALTER TABLE t LAST PARTITION LESS THAN ('2023-01-01') PLACEMENT POLICY 'fastStorage'
if len(b[i].Options) > 0 {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("partition %s does have unsupported options", b[i].Name.O))
}
lessThan, ok := b[i].Clause.(*ast.PartitionDefinitionClauseLessThan)
if !ok {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("partition %s does not have the right type for LESS THAN", b[i].Name.O))
}
definedExpr := lessThan.Exprs[0]
generatedExpr := a[i].Clause.(*ast.PartitionDefinitionClauseLessThan).Exprs[0]
_, maxVD := definedExpr.(*ast.MaxValueExpr)
_, maxVG := generatedExpr.(*ast.MaxValueExpr)
if maxVG || maxVD {
if maxVG && maxVD {
continue
}
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("partition %s differs between generated and defined for MAXVALUE", b[i].Name.O))
}
cmpExpr := &ast.BinaryOperationExpr{
Op: opcode.EQ,
L: definedExpr,
R: generatedExpr,
}
cmp, err := expression.EvalAstExpr(ctx, cmpExpr)
if err != nil {
return err
}
if cmp.GetInt64() != 1 {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs(fmt.Sprintf("partition %s differs between generated and defined for expression", b[i].Name.O))
}
}
return nil
}
func getLowerBoundInt(partCols ...*model.ColumnInfo) int64 {
ret := int64(0)
for _, col := range partCols {
if mysql.HasUnsignedFlag(col.FieldType.GetFlag()) {
return 0
}
ret = mathutil.Min(ret, types.IntergerSignedLowerBound(col.GetType()))
}
return ret
}
// generatePartitionDefinitionsFromInterval generates partition Definitions according to INTERVAL options on partOptions
func generatePartitionDefinitionsFromInterval(ctx sessionctx.Context, partOptions *ast.PartitionOptions, tbInfo *model.TableInfo) error {
if partOptions.Interval == nil {
return nil
}
if tbInfo.Partition.Type != model.PartitionTypeRange {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, only allowed on RANGE partitioning")
}
if len(partOptions.ColumnNames) > 1 || len(tbInfo.Partition.Columns) > 1 {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, does not allow RANGE COLUMNS with more than one column")
}
var partCol *model.ColumnInfo
if len(tbInfo.Partition.Columns) > 0 {
partCol = findColumnByName(tbInfo.Partition.Columns[0].L, tbInfo)
if partCol == nil {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, could not find any RANGE COLUMNS")
}
// Only support Datetime, date and INT column types for RANGE INTERVAL!
switch partCol.FieldType.EvalType() {
case types.ETInt, types.ETDatetime:
default:
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, only supports Date, Datetime and INT types")
}
}
// Allow given partition definitions, but check it later!
definedPartDefs := partOptions.Definitions
partOptions.Definitions = make([]*ast.PartitionDefinition, 0, 1)
if partOptions.Interval.FirstRangeEnd == nil || partOptions.Interval.LastRangeEnd == nil {
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, currently requires FIRST and LAST partitions to be defined")
}
switch partOptions.Interval.IntervalExpr.TimeUnit {
case ast.TimeUnitInvalid, ast.TimeUnitYear, ast.TimeUnitQuarter, ast.TimeUnitMonth, ast.TimeUnitWeek, ast.TimeUnitDay, ast.TimeUnitHour, ast.TimeUnitDayMinute, ast.TimeUnitSecond:
default:
return dbterror.ErrGeneralUnsupportedDDL.GenWithStackByArgs("INTERVAL partitioning, only supports YEAR, QUARTER, MONTH, WEEK, DAY, HOUR, MINUTE and SECOND as time unit")
}
first := ast.PartitionDefinitionClauseLessThan{
Exprs: []ast.ExprNode{*partOptions.Interval.FirstRangeEnd},
}
last := ast.PartitionDefinitionClauseLessThan{
Exprs: []ast.ExprNode{*partOptions.Interval.LastRangeEnd},
}
if len(tbInfo.Partition.Columns) > 0 {
colTypes := collectColumnsType(tbInfo)
if len(colTypes) != len(tbInfo.Partition.Columns) {
return dbterror.ErrWrongPartitionName.GenWithStack("partition column name cannot be found")
}
if _, err := checkAndGetColumnsTypeAndValuesMatch(ctx, colTypes, first.Exprs); err != nil {
return err
}
if _, err := checkAndGetColumnsTypeAndValuesMatch(ctx, colTypes, last.Exprs); err != nil {
return err
}
} else {
if err := checkPartitionValuesIsInt(ctx, "FIRST PARTITION", first.Exprs, tbInfo); err != nil {
return err
}
if err := checkPartitionValuesIsInt(ctx, "LAST PARTITION", last.Exprs, tbInfo); err != nil {
return err
}
}
if partOptions.Interval.NullPart {
var partExpr ast.ExprNode
if len(tbInfo.Partition.Columns) == 1 && partOptions.Interval.IntervalExpr.TimeUnit != ast.TimeUnitInvalid {
// Notice compatibility with MySQL, keyword here is 'supported range' but MySQL seems to work from 0000-01-01 too
// https://dev.mysql.com/doc/refman/8.0/en/datetime.html says range 1000-01-01 - 9999-12-31
// https://docs.pingcap.com/tidb/dev/data-type-date-and-time says The supported range is '0000-01-01' to '9999-12-31'
// set LESS THAN to ZeroTime
partExpr = ast.NewValueExpr("0000-01-01", "", "")
} else {
var min int64
if partCol != nil {
min = getLowerBoundInt(partCol)
} else {
if !isPartExprUnsigned(tbInfo) {
min = math.MinInt64
}
}
partExpr = ast.NewValueExpr(min, "", "")
}
partOptions.Definitions = append(partOptions.Definitions, &ast.PartitionDefinition{
Name: model.NewCIStr("P_NULL"),
Clause: &ast.PartitionDefinitionClauseLessThan{
Exprs: []ast.ExprNode{partExpr},
},
})
}
err := GeneratePartDefsFromInterval(ctx, ast.AlterTablePartition, tbInfo, partOptions)
if err != nil {
return err
}
if partOptions.Interval.MaxValPart {
partOptions.Definitions = append(partOptions.Definitions, &ast.PartitionDefinition{
Name: model.NewCIStr("P_MAXVALUE"),
Clause: &ast.PartitionDefinitionClauseLessThan{
Exprs: []ast.ExprNode{&ast.MaxValueExpr{}},
},
})
}
if len(definedPartDefs) > 0 {
err := comparePartitionDefinitions(ctx, partOptions.Definitions, definedPartDefs)
if err != nil {
return err
}
// Seems valid, so keep the defined so that the user defined names are kept etc.
partOptions.Definitions = definedPartDefs
} else if len(tbInfo.Partition.Definitions) > 0 {
err := comparePartitionAstAndModel(ctx, partOptions, tbInfo.Partition)
if err != nil {
return err
}
}
return nil
}
func astIntValueExprFromStr(s string, unsigned bool) (ast.ExprNode, error) {
if unsigned {
u, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return nil, err
}
return ast.NewValueExpr(u, "", ""), nil
}
i, err := strconv.ParseInt(s, 10, 64)