-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
partition.go
1918 lines (1783 loc) · 61.6 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 tables
import (
"bytes"
"context"
stderr "errors"
"fmt"
"hash/crc32"
"sort"
"strconv"
"strings"
"sync"
"github.com/google/btree"
"github.com/pingcap/errors"
"github.com/pingcap/tidb/pkg/errctx"
"github.com/pingcap/tidb/pkg/expression"
"github.com/pingcap/tidb/pkg/expression/contextstatic"
"github.com/pingcap/tidb/pkg/kv"
"github.com/pingcap/tidb/pkg/parser"
"github.com/pingcap/tidb/pkg/parser/ast"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/sessionctx/variable"
"github.com/pingcap/tidb/pkg/table"
"github.com/pingcap/tidb/pkg/tablecodec"
"github.com/pingcap/tidb/pkg/types"
"github.com/pingcap/tidb/pkg/util"
"github.com/pingcap/tidb/pkg/util/chunk"
"github.com/pingcap/tidb/pkg/util/codec"
"github.com/pingcap/tidb/pkg/util/dbterror"
"github.com/pingcap/tidb/pkg/util/hack"
"github.com/pingcap/tidb/pkg/util/logutil"
"github.com/pingcap/tidb/pkg/util/ranger"
"github.com/pingcap/tidb/pkg/util/stringutil"
"go.uber.org/zap"
)
const (
btreeDegree = 32
)
// Both partition and partitionedTable implement the table.Table interface.
var _ table.PhysicalTable = &partition{}
var _ table.Table = &partitionedTable{}
// partitionedTable implements the table.PartitionedTable interface.
var _ table.PartitionedTable = &partitionedTable{}
// partition is a feature from MySQL:
// See https://dev.mysql.com/doc/refman/8.0/en/partitioning.html
// A partition table may contain many partitions, each partition has a unique partition
// id. The underlying representation of a partition and a normal table (a table with no
// partitions) is basically the same.
// partition also implements the table.Table interface.
type partition struct {
TableCommon
table *partitionedTable
}
// GetPhysicalID implements table.Table GetPhysicalID interface.
func (p *partition) GetPhysicalID() int64 {
return p.physicalTableID
}
// GetPartitionedTable implements table.Table GetPartitionedTable interface.
func (p *partition) GetPartitionedTable() table.PartitionedTable {
return p.table
}
// GetPartitionedTable implements table.Table GetPartitionedTable interface.
func (t *partitionedTable) GetPartitionedTable() table.PartitionedTable {
return t
}
// partitionedTable implements the table.PartitionedTable interface.
// partitionedTable is a table, it contains many Partitions.
type partitionedTable struct {
TableCommon
partitionExpr *PartitionExpr
partitions map[int64]*partition
evalBufferTypes []*types.FieldType
evalBufferPool sync.Pool
// Only used during Reorganize partition
// reorganizePartitions is the currently used partitions that are reorganized
reorganizePartitions map[int64]any
// doubleWritePartitions are the partitions not visible, but we should double write to
doubleWritePartitions map[int64]any
reorgPartitionExpr *PartitionExpr
}
// TODO: Check which data structures that can be shared between all partitions and which
// needs to be copies
func newPartitionedTable(tbl *TableCommon, tblInfo *model.TableInfo) (table.PartitionedTable, error) {
pi := tblInfo.GetPartitionInfo()
if pi == nil || len(pi.Definitions) == 0 {
return nil, table.ErrUnknownPartition
}
ret := &partitionedTable{TableCommon: tbl.Copy()}
partitionExpr, err := newPartitionExpr(tblInfo, pi.Type, pi.Expr, pi.Columns, pi.Definitions)
if err != nil {
return nil, errors.Trace(err)
}
ret.partitionExpr = partitionExpr
initEvalBufferType(ret)
ret.evalBufferPool = sync.Pool{
New: func() any {
return initEvalBuffer(ret)
},
}
if err := initTableIndices(&ret.TableCommon); err != nil {
return nil, errors.Trace(err)
}
partitions := make(map[int64]*partition, len(pi.Definitions))
for _, p := range pi.Definitions {
var t partition
err := initTableCommonWithIndices(&t.TableCommon, tblInfo, p.ID, tbl.Columns, tbl.allocs, tbl.Constraints)
if err != nil {
return nil, errors.Trace(err)
}
t.table = ret
partitions[p.ID] = &t
}
ret.partitions = partitions
// In StateWriteReorganization we are using the 'old' partition definitions
// and if any new change happens in DroppingDefinitions, it needs to be done
// also in AddingDefinitions (with new evaluation of the new expression)
// In StateDeleteReorganization we are using the 'new' partition definitions
// and if any new change happens in AddingDefinitions, it needs to be done
// also in DroppingDefinitions (since session running on schema version -1)
// should also see the changes
if pi.DDLState == model.StateDeleteReorganization {
origIdx := setIndexesState(ret, pi.DDLState)
defer unsetIndexesState(ret, origIdx)
// TODO: Explicitly explain the different DDL/New fields!
if pi.NewTableID != 0 {
ret.reorgPartitionExpr, err = newPartitionExpr(tblInfo, pi.DDLType, pi.DDLExpr, pi.DDLColumns, pi.DroppingDefinitions)
} else {
ret.reorgPartitionExpr, err = newPartitionExpr(tblInfo, pi.Type, pi.Expr, pi.Columns, pi.DroppingDefinitions)
}
if err != nil {
return nil, errors.Trace(err)
}
ret.reorganizePartitions = make(map[int64]any, len(pi.AddingDefinitions))
for _, def := range pi.AddingDefinitions {
ret.reorganizePartitions[def.ID] = nil
}
ret.doubleWritePartitions = make(map[int64]any, len(pi.DroppingDefinitions))
for _, def := range pi.DroppingDefinitions {
p, err := initPartition(ret, def)
if err != nil {
return nil, err
}
partitions[def.ID] = p
ret.doubleWritePartitions[def.ID] = nil
}
} else {
if len(pi.AddingDefinitions) > 0 {
origIdx := setIndexesState(ret, pi.DDLState)
defer unsetIndexesState(ret, origIdx)
if pi.NewTableID != 0 {
// REMOVE PARTITIONING or PARTITION BY
ret.reorgPartitionExpr, err = newPartitionExpr(tblInfo, pi.DDLType, pi.DDLExpr, pi.DDLColumns, pi.AddingDefinitions)
} else {
// REORGANIZE PARTITION
ret.reorgPartitionExpr, err = newPartitionExpr(tblInfo, pi.Type, pi.Expr, pi.Columns, pi.AddingDefinitions)
}
if err != nil {
return nil, errors.Trace(err)
}
ret.doubleWritePartitions = make(map[int64]any, len(pi.AddingDefinitions))
for _, def := range pi.AddingDefinitions {
ret.doubleWritePartitions[def.ID] = nil
p, err := initPartition(ret, def)
if err != nil {
return nil, err
}
partitions[def.ID] = p
}
}
if len(pi.DroppingDefinitions) > 0 {
ret.reorganizePartitions = make(map[int64]any, len(pi.DroppingDefinitions))
for _, def := range pi.DroppingDefinitions {
ret.reorganizePartitions[def.ID] = nil
}
}
}
return ret, nil
}
func setIndexesState(t *partitionedTable, state model.SchemaState) []*model.IndexInfo {
orig := t.meta.Indices
t.meta.Indices = make([]*model.IndexInfo, 0, len(orig))
for i := range orig {
t.meta.Indices = append(t.meta.Indices, orig[i].Clone())
if t.meta.Indices[i].State == model.StatePublic {
switch state {
case model.StateDeleteOnly, model.StateNone:
t.meta.Indices[i].State = model.StateDeleteOnly
case model.StatePublic:
// Keep as is
default:
// use the 'StateWriteReorganization' here, since StateDeleteReorganization
// would skip index writes.
t.meta.Indices[i].State = model.StateWriteReorganization
}
}
}
return orig
}
func unsetIndexesState(t *partitionedTable, orig []*model.IndexInfo) {
t.meta.Indices = orig
}
func initPartition(t *partitionedTable, def model.PartitionDefinition) (*partition, error) {
var newPart partition
err := initTableCommonWithIndices(&newPart.TableCommon, t.meta, def.ID, t.Columns, t.allocs, t.Constraints)
if err != nil {
return nil, err
}
newPart.table = t
return &newPart, nil
}
// NewPartitionExprBuildCtx returns a context to build partition expression.
func NewPartitionExprBuildCtx() expression.BuildContext {
return contextstatic.NewStaticExprContext(
contextstatic.WithEvalCtx(contextstatic.NewStaticEvalContext(
// Set a non-strict SQL mode and allow all date values if possible to make sure constant fold can work to
// estimate some undetermined result when locating a row to a partition.
// See issue: https://github.com/pingcap/tidb/issues/54271 for details.
contextstatic.WithSQLMode(mysql.ModeAllowInvalidDates),
contextstatic.WithTypeFlags(types.StrictFlags.
WithIgnoreTruncateErr(true).
WithIgnoreZeroDateErr(true).
WithIgnoreZeroInDate(true).
WithIgnoreInvalidDateErr(true),
),
contextstatic.WithErrLevelMap(errctx.LevelMap{
errctx.ErrGroupTruncate: errctx.LevelIgnore,
}),
)),
)
}
func newPartitionExpr(tblInfo *model.TableInfo, tp model.PartitionType, expr string, partCols []model.CIStr, defs []model.PartitionDefinition) (*PartitionExpr, error) {
ctx := NewPartitionExprBuildCtx()
dbName := model.NewCIStr(ctx.GetEvalCtx().CurrentDB())
columns, names, err := expression.ColumnInfos2ColumnsAndNames(ctx, dbName, tblInfo.Name, tblInfo.Cols(), tblInfo)
if err != nil {
return nil, err
}
switch tp {
case model.PartitionTypeNone:
// Nothing to do
return nil, nil
case model.PartitionTypeRange:
return generateRangePartitionExpr(ctx, expr, partCols, defs, columns, names)
case model.PartitionTypeHash:
return generateHashPartitionExpr(ctx, expr, columns, names)
case model.PartitionTypeKey:
return generateKeyPartitionExpr(ctx, expr, partCols, columns, names)
case model.PartitionTypeList:
return generateListPartitionExpr(ctx, tblInfo, expr, partCols, defs, columns, names)
}
panic("cannot reach here")
}
// PartitionExpr is the partition definition expressions.
type PartitionExpr struct {
// UpperBounds: (x < y1); (x < y2); (x < y3), used by locatePartition.
UpperBounds []expression.Expression
// OrigExpr is the partition expression ast used in point get.
OrigExpr ast.ExprNode
// Expr is the hash partition expression.
Expr expression.Expression
// Used in the key partition
*ForKeyPruning
// Used in the range pruning process.
*ForRangePruning
// Used in the range column pruning process.
*ForRangeColumnsPruning
// ColOffset is the offsets of partition columns.
ColumnOffset []int
*ForListPruning
}
// GetPartColumnsForKeyPartition is used to get partition columns for key partition table
func (pe *PartitionExpr) GetPartColumnsForKeyPartition(columns []*expression.Column) ([]*expression.Column, []int) {
schema := expression.NewSchema(columns...)
partCols := make([]*expression.Column, len(pe.ColumnOffset))
colLen := make([]int, 0, len(pe.ColumnOffset))
for i, offset := range pe.ColumnOffset {
partCols[i] = schema.Columns[offset]
partCols[i].Index = i
colLen = append(colLen, partCols[i].RetType.GetFlen())
}
return partCols, colLen
}
// LocateKeyPartition is the common interface used to locate the destination partition
func (kp *ForKeyPruning) LocateKeyPartition(numParts uint64, r []types.Datum) (int, error) {
h := crc32.NewIEEE()
for _, col := range kp.KeyPartCols {
val := r[col.Index]
if val.Kind() == types.KindNull {
h.Write([]byte{0})
} else {
data, err := val.ToHashKey()
if err != nil {
return 0, err
}
h.Write(data)
}
}
return int(h.Sum32() % uint32(numParts)), nil
}
func initEvalBufferType(t *partitionedTable) {
hasExtraHandle := false
numCols := len(t.Cols())
if !t.Meta().PKIsHandle {
hasExtraHandle = true
numCols++
}
t.evalBufferTypes = make([]*types.FieldType, numCols)
for i, col := range t.Cols() {
t.evalBufferTypes[i] = &col.FieldType
}
if hasExtraHandle {
t.evalBufferTypes[len(t.evalBufferTypes)-1] = types.NewFieldType(mysql.TypeLonglong)
}
}
func initEvalBuffer(t *partitionedTable) *chunk.MutRow {
evalBuffer := chunk.MutRowFromTypes(t.evalBufferTypes)
return &evalBuffer
}
// ForRangeColumnsPruning is used for range partition pruning.
type ForRangeColumnsPruning struct {
// LessThan contains expressions for [Partition][column].
// If Maxvalue, then nil
LessThan [][]*expression.Expression
}
func dataForRangeColumnsPruning(ctx expression.BuildContext, defs []model.PartitionDefinition, schema *expression.Schema, names []*types.FieldName, p *parser.Parser, colOffsets []int) (*ForRangeColumnsPruning, error) {
var res ForRangeColumnsPruning
res.LessThan = make([][]*expression.Expression, 0, len(defs))
for i := 0; i < len(defs); i++ {
lessThanCols := make([]*expression.Expression, 0, len(defs[i].LessThan))
for j := range defs[i].LessThan {
if strings.EqualFold(defs[i].LessThan[j], "MAXVALUE") {
// Use a nil pointer instead of math.MaxInt64 to avoid the corner cases.
lessThanCols = append(lessThanCols, nil)
// No column after MAXVALUE matters
break
}
tmp, err := parseSimpleExprWithNames(p, ctx, defs[i].LessThan[j], schema, names)
if err != nil {
return nil, err
}
_, ok := tmp.(*expression.Constant)
if !ok {
return nil, dbterror.ErrPartitionConstDomain
}
// TODO: Enable this for all types!
// Currently it will trigger changes for collation differences
switch schema.Columns[colOffsets[j]].RetType.GetType() {
case mysql.TypeDatetime, mysql.TypeDate:
// Will also fold constant
tmp = expression.BuildCastFunction(ctx, tmp, schema.Columns[colOffsets[j]].RetType)
}
lessThanCols = append(lessThanCols, &tmp)
}
res.LessThan = append(res.LessThan, lessThanCols)
}
return &res, nil
}
// parseSimpleExprWithNames parses simple expression string to Expression.
// The expression string must only reference the column in the given NameSlice.
func parseSimpleExprWithNames(p *parser.Parser, ctx expression.BuildContext, exprStr string, schema *expression.Schema, names types.NameSlice) (expression.Expression, error) {
exprNode, err := parseExpr(p, exprStr)
if err != nil {
return nil, errors.Trace(err)
}
return expression.BuildSimpleExpr(ctx, exprNode, expression.WithInputSchemaAndNames(schema, names, nil))
}
// ForKeyPruning is used for key partition pruning.
type ForKeyPruning struct {
KeyPartCols []*expression.Column
}
// ForListPruning is used for list partition pruning.
type ForListPruning struct {
// LocateExpr uses to locate list partition by row.
LocateExpr expression.Expression
// PruneExpr uses to prune list partition in partition pruner.
PruneExpr expression.Expression
// PruneExprCols is the columns of PruneExpr, it has removed the duplicate columns.
PruneExprCols []*expression.Column
// valueMap is column value -> partition idx, uses to locate list partition.
valueMap map[int64]int
// nullPartitionIdx is the partition idx for null value.
nullPartitionIdx int
// defaultPartitionIdx is the partition idx for default value/fallback.
defaultPartitionIdx int
// For list columns partition pruning
ColPrunes []*ForListColumnPruning
}
// btreeListColumnItem is BTree's Item that uses string to compare.
type btreeListColumnItem struct {
key string
location ListPartitionLocation
}
func newBtreeListColumnItem(key string, location ListPartitionLocation) *btreeListColumnItem {
return &btreeListColumnItem{
key: key,
location: location,
}
}
func newBtreeListColumnSearchItem(key string) *btreeListColumnItem {
return &btreeListColumnItem{
key: key,
}
}
func (item *btreeListColumnItem) Less(other btree.Item) bool {
return item.key < other.(*btreeListColumnItem).key
}
func lessBtreeListColumnItem(a, b *btreeListColumnItem) bool {
return a.key < b.key
}
// ForListColumnPruning is used for list columns partition pruning.
type ForListColumnPruning struct {
ExprCol *expression.Column
valueTp *types.FieldType
valueMap map[string]ListPartitionLocation
sorted *btree.BTreeG[*btreeListColumnItem]
// To deal with the location partition failure caused by inconsistent NewCollationEnabled values(see issue #32416).
// The following fields are used to delay building valueMap.
ctx expression.BuildContext
tblInfo *model.TableInfo
schema *expression.Schema
names types.NameSlice
colIdx int
// catch-all partition / DEFAULT
defaultPartID int64
}
// ListPartitionGroup indicate the group index of the column value in a partition.
type ListPartitionGroup struct {
// Such as: list columns (a,b) (partition p0 values in ((1,5),(1,6)));
// For the column a which value is 1, the ListPartitionGroup is:
// ListPartitionGroup {
// PartIdx: 0, // 0 is the partition p0 index in all partitions.
// GroupIdxs: []int{0,1}, // p0 has 2 value group: (1,5) and (1,6), and they both contain the column a where value is 1;
// } // the value of GroupIdxs `0,1` is the index of the value group that contain the column a which value is 1.
PartIdx int
GroupIdxs []int
}
// ListPartitionLocation indicate the partition location for the column value in list columns partition.
// Here is an example:
// Suppose the list columns partition is: list columns (a,b) (partition p0 values in ((1,5),(1,6)), partition p1 values in ((1,7),(9,9)));
// How to express the location of the column a which value is 1?
// For the column a which value is 1, both partition p0 and p1 contain the column a which value is 1.
// In partition p0, both value group0 (1,5) and group1 (1,6) are contain the column a which value is 1.
// In partition p1, value group0 (1,7) contains the column a which value is 1.
// So, the ListPartitionLocation of column a which value is 1 is:
//
// []ListPartitionGroup{
// {
// PartIdx: 0, // `0` is the partition p0 index in all partitions.
// GroupIdxs: []int{0, 1} // `0,1` is the index of the value group0, group1.
// },
// {
// PartIdx: 1, // `1` is the partition p1 index in all partitions.
// GroupIdxs: []int{0} // `0` is the index of the value group0.
// },
// }
type ListPartitionLocation []ListPartitionGroup
// IsEmpty returns true if the ListPartitionLocation is empty.
func (ps ListPartitionLocation) IsEmpty() bool {
for _, pg := range ps {
if len(pg.GroupIdxs) > 0 {
return false
}
}
return true
}
func (ps ListPartitionLocation) findByPartitionIdx(partIdx int) int {
for i, p := range ps {
if p.PartIdx == partIdx {
return i
}
}
return -1
}
type listPartitionLocationHelper struct {
initialized bool
location ListPartitionLocation
}
// NewListPartitionLocationHelper returns a new listPartitionLocationHelper.
func NewListPartitionLocationHelper() *listPartitionLocationHelper {
return &listPartitionLocationHelper{}
}
// GetLocation gets the list partition location.
func (p *listPartitionLocationHelper) GetLocation() ListPartitionLocation {
return p.location
}
// UnionPartitionGroup unions with the list-partition-value-group.
func (p *listPartitionLocationHelper) UnionPartitionGroup(pg ListPartitionGroup) {
idx := p.location.findByPartitionIdx(pg.PartIdx)
if idx < 0 {
// copy the group idx.
groupIdxs := make([]int, len(pg.GroupIdxs))
copy(groupIdxs, pg.GroupIdxs)
p.location = append(p.location, ListPartitionGroup{
PartIdx: pg.PartIdx,
GroupIdxs: groupIdxs,
})
return
}
p.location[idx].union(pg)
}
// Union unions with the other location.
func (p *listPartitionLocationHelper) Union(location ListPartitionLocation) {
for _, pg := range location {
p.UnionPartitionGroup(pg)
}
}
// Intersect intersect with other location.
func (p *listPartitionLocationHelper) Intersect(location ListPartitionLocation) bool {
if !p.initialized {
p.initialized = true
p.location = make([]ListPartitionGroup, 0, len(location))
p.location = append(p.location, location...)
return true
}
currPgs := p.location
remainPgs := make([]ListPartitionGroup, 0, len(location))
for _, pg := range location {
idx := currPgs.findByPartitionIdx(pg.PartIdx)
if idx < 0 {
continue
}
if !currPgs[idx].intersect(pg) {
continue
}
remainPgs = append(remainPgs, currPgs[idx])
}
p.location = remainPgs
return len(remainPgs) > 0
}
func (pg *ListPartitionGroup) intersect(otherPg ListPartitionGroup) bool {
if pg.PartIdx != otherPg.PartIdx {
return false
}
var groupIdxs []int
for _, gidx := range otherPg.GroupIdxs {
if pg.findGroupIdx(gidx) {
groupIdxs = append(groupIdxs, gidx)
}
}
pg.GroupIdxs = groupIdxs
return len(groupIdxs) > 0
}
func (pg *ListPartitionGroup) union(otherPg ListPartitionGroup) {
if pg.PartIdx != otherPg.PartIdx {
return
}
pg.GroupIdxs = append(pg.GroupIdxs, otherPg.GroupIdxs...)
}
func (pg *ListPartitionGroup) findGroupIdx(groupIdx int) bool {
for _, gidx := range pg.GroupIdxs {
if gidx == groupIdx {
return true
}
}
return false
}
// ForRangePruning is used for range partition pruning.
type ForRangePruning struct {
LessThan []int64
MaxValue bool
Unsigned bool
}
// dataForRangePruning extracts the less than parts from 'partition p0 less than xx ... partition p1 less than ...'
func dataForRangePruning(sctx expression.BuildContext, defs []model.PartitionDefinition) (*ForRangePruning, error) {
var maxValue bool
var unsigned bool
lessThan := make([]int64, len(defs))
for i := 0; i < len(defs); i++ {
if strings.EqualFold(defs[i].LessThan[0], "MAXVALUE") {
// Use a bool flag instead of math.MaxInt64 to avoid the corner cases.
maxValue = true
} else {
var err error
lessThan[i], err = strconv.ParseInt(defs[i].LessThan[0], 10, 64)
var numErr *strconv.NumError
if stderr.As(err, &numErr) && numErr.Err == strconv.ErrRange {
var tmp uint64
tmp, err = strconv.ParseUint(defs[i].LessThan[0], 10, 64)
lessThan[i] = int64(tmp)
unsigned = true
}
if err != nil {
val, ok := fixOldVersionPartitionInfo(sctx, defs[i].LessThan[0])
if !ok {
logutil.BgLogger().Error("wrong partition definition", zap.String("less than", defs[i].LessThan[0]))
return nil, errors.WithStack(err)
}
lessThan[i] = val
}
}
}
return &ForRangePruning{
LessThan: lessThan,
MaxValue: maxValue,
Unsigned: unsigned,
}, nil
}
func fixOldVersionPartitionInfo(sctx expression.BuildContext, str string) (int64, bool) {
// less than value should be calculate to integer before persistent.
// Old version TiDB may not do it and store the raw expression.
tmp, err := parseSimpleExprWithNames(parser.New(), sctx, str, nil, nil)
if err != nil {
return 0, false
}
ret, isNull, err := tmp.EvalInt(sctx.GetEvalCtx(), chunk.Row{})
if err != nil || isNull {
return 0, false
}
return ret, true
}
func rangePartitionExprStrings(cols []model.CIStr, expr string) []string {
var s []string
if len(cols) > 0 {
s = make([]string, 0, len(cols))
for _, col := range cols {
s = append(s, stringutil.Escape(col.O, mysql.ModeNone))
}
} else {
s = []string{expr}
}
return s
}
func generateKeyPartitionExpr(ctx expression.BuildContext, expr string, partCols []model.CIStr,
columns []*expression.Column, names types.NameSlice) (*PartitionExpr, error) {
ret := &PartitionExpr{
ForKeyPruning: &ForKeyPruning{},
}
_, partColumns, offset, err := extractPartitionExprColumns(ctx, expr, partCols, columns, names)
if err != nil {
return nil, errors.Trace(err)
}
ret.ColumnOffset = offset
ret.KeyPartCols = partColumns
return ret, nil
}
func generateRangePartitionExpr(ctx expression.BuildContext, expr string, partCols []model.CIStr,
defs []model.PartitionDefinition, columns []*expression.Column, names types.NameSlice) (*PartitionExpr, error) {
// The caller should assure partition info is not nil.
p := parser.New()
schema := expression.NewSchema(columns...)
partStrs := rangePartitionExprStrings(partCols, expr)
locateExprs, err := getRangeLocateExprs(ctx, p, defs, partStrs, schema, names)
if err != nil {
return nil, errors.Trace(err)
}
ret := &PartitionExpr{
UpperBounds: locateExprs,
}
partExpr, _, offset, err := extractPartitionExprColumns(ctx, expr, partCols, columns, names)
if err != nil {
return nil, errors.Trace(err)
}
ret.ColumnOffset = offset
if len(partCols) < 1 {
tmp, err := dataForRangePruning(ctx, defs)
if err != nil {
return nil, errors.Trace(err)
}
ret.Expr = partExpr
ret.ForRangePruning = tmp
} else {
tmp, err := dataForRangeColumnsPruning(ctx, defs, schema, names, p, offset)
if err != nil {
return nil, errors.Trace(err)
}
ret.ForRangeColumnsPruning = tmp
}
return ret, nil
}
func getRangeLocateExprs(ctx expression.BuildContext, p *parser.Parser, defs []model.PartitionDefinition, partStrs []string, schema *expression.Schema, names types.NameSlice) ([]expression.Expression, error) {
var buf bytes.Buffer
locateExprs := make([]expression.Expression, 0, len(defs))
for i := 0; i < len(defs); i++ {
if strings.EqualFold(defs[i].LessThan[0], "MAXVALUE") {
// Expr less than maxvalue is always true.
fmt.Fprintf(&buf, "true")
} else {
maxValueFound := false
for j := range partStrs[1:] {
if strings.EqualFold(defs[i].LessThan[j+1], "MAXVALUE") {
// if any column will be less than MAXVALUE, so change < to <= of the previous prefix of columns
fmt.Fprintf(&buf, "((%s) <= (%s))", strings.Join(partStrs[:j+1], ","), strings.Join(defs[i].LessThan[:j+1], ","))
maxValueFound = true
break
}
}
if !maxValueFound {
fmt.Fprintf(&buf, "((%s) < (%s))", strings.Join(partStrs, ","), strings.Join(defs[i].LessThan, ","))
}
}
expr, err := parseSimpleExprWithNames(p, ctx, buf.String(), schema, names)
if err != nil {
// If it got an error here, ddl may hang forever, so this error log is important.
logutil.BgLogger().Error("wrong table partition expression", zap.String("expression", buf.String()), zap.Error(err))
return nil, errors.Trace(err)
}
locateExprs = append(locateExprs, expr)
buf.Reset()
}
return locateExprs, nil
}
func getColumnsOffset(cols, columns []*expression.Column) []int {
colsOffset := make([]int, len(cols))
for i, col := range columns {
if idx := findIdxByColUniqueID(cols, col); idx >= 0 {
colsOffset[idx] = i
}
}
return colsOffset
}
func findIdxByColUniqueID(cols []*expression.Column, col *expression.Column) int {
for idx, c := range cols {
if c.UniqueID == col.UniqueID {
return idx
}
}
return -1
}
func extractPartitionExprColumns(ctx expression.BuildContext, expr string, partCols []model.CIStr, columns []*expression.Column, names types.NameSlice) (expression.Expression, []*expression.Column, []int, error) {
var cols []*expression.Column
var partExpr expression.Expression
if len(partCols) == 0 {
schema := expression.NewSchema(columns...)
expr, err := expression.ParseSimpleExpr(ctx, expr, expression.WithInputSchemaAndNames(schema, names, nil))
if err != nil {
return nil, nil, nil, err
}
cols = expression.ExtractColumns(expr)
partExpr = expr
} else {
for _, col := range partCols {
idx := expression.FindFieldNameIdxByColName(names, col.L)
if idx < 0 {
panic("should never happen")
}
cols = append(cols, columns[idx])
}
}
offset := getColumnsOffset(cols, columns)
deDupCols := make([]*expression.Column, 0, len(cols))
for _, col := range cols {
if findIdxByColUniqueID(deDupCols, col) < 0 {
c := col.Clone().(*expression.Column)
deDupCols = append(deDupCols, c)
}
}
return partExpr, deDupCols, offset, nil
}
func generateListPartitionExpr(ctx expression.BuildContext, tblInfo *model.TableInfo, expr string, partCols []model.CIStr,
defs []model.PartitionDefinition, columns []*expression.Column, names types.NameSlice) (*PartitionExpr, error) {
// The caller should assure partition info is not nil.
partExpr, exprCols, offset, err := extractPartitionExprColumns(ctx, expr, partCols, columns, names)
if err != nil {
return nil, err
}
listPrune := &ForListPruning{}
if len(partCols) == 0 {
err = listPrune.buildListPruner(ctx, expr, defs, exprCols, columns, names)
} else {
err = listPrune.buildListColumnsPruner(ctx, tblInfo, partCols, defs, columns, names)
}
if err != nil {
return nil, err
}
ret := &PartitionExpr{
ForListPruning: listPrune,
ColumnOffset: offset,
Expr: partExpr,
}
return ret, nil
}
// Clone a copy of ForListPruning
func (lp *ForListPruning) Clone() *ForListPruning {
ret := *lp
if ret.LocateExpr != nil {
ret.LocateExpr = lp.LocateExpr.Clone()
}
if ret.PruneExpr != nil {
ret.PruneExpr = lp.PruneExpr.Clone()
}
ret.PruneExprCols = make([]*expression.Column, 0, len(lp.PruneExprCols))
for i := range lp.PruneExprCols {
c := lp.PruneExprCols[i].Clone().(*expression.Column)
ret.PruneExprCols = append(ret.PruneExprCols, c)
}
ret.ColPrunes = make([]*ForListColumnPruning, 0, len(lp.ColPrunes))
for i := range lp.ColPrunes {
l := *lp.ColPrunes[i]
l.ExprCol = l.ExprCol.Clone().(*expression.Column)
ret.ColPrunes = append(ret.ColPrunes, &l)
}
return &ret
}
func (lp *ForListPruning) buildListPruner(ctx expression.BuildContext, exprStr string, defs []model.PartitionDefinition, exprCols []*expression.Column,
columns []*expression.Column, names types.NameSlice) error {
schema := expression.NewSchema(columns...)
p := parser.New()
expr, err := parseSimpleExprWithNames(p, ctx, exprStr, schema, names)
if err != nil {
// If it got an error here, ddl may hang forever, so this error log is important.
logutil.BgLogger().Error("wrong table partition expression", zap.String("expression", exprStr), zap.Error(err))
return errors.Trace(err)
}
// Since need to change the column index of the expression, clone the expression first.
lp.LocateExpr = expr.Clone()
lp.PruneExprCols = exprCols
lp.PruneExpr = expr.Clone()
cols := expression.ExtractColumns(lp.PruneExpr)
for _, c := range cols {
idx := findIdxByColUniqueID(exprCols, c)
if idx < 0 {
return table.ErrUnknownColumn.GenWithStackByArgs(c.OrigName)
}
c.Index = idx
}
err = lp.buildListPartitionValueMap(ctx, defs, schema, names, p)
if err != nil {
return err
}
return nil
}
func (lp *ForListPruning) buildListColumnsPruner(ctx expression.BuildContext,
tblInfo *model.TableInfo, partCols []model.CIStr, defs []model.PartitionDefinition,
columns []*expression.Column, names types.NameSlice) error {
schema := expression.NewSchema(columns...)
p := parser.New()
colPrunes := make([]*ForListColumnPruning, 0, len(partCols))
lp.defaultPartitionIdx = -1
for colIdx := range partCols {
colInfo := model.FindColumnInfo(tblInfo.Columns, partCols[colIdx].L)
if colInfo == nil {
return table.ErrUnknownColumn.GenWithStackByArgs(partCols[colIdx].L)
}
idx := expression.FindFieldNameIdxByColName(names, partCols[colIdx].L)
if idx < 0 {
return table.ErrUnknownColumn.GenWithStackByArgs(partCols[colIdx].L)
}
colPrune := &ForListColumnPruning{
ctx: ctx,
tblInfo: tblInfo,
schema: schema,
names: names,
colIdx: colIdx,
ExprCol: columns[idx],
valueTp: &colInfo.FieldType,
valueMap: make(map[string]ListPartitionLocation),
sorted: btree.NewG[*btreeListColumnItem](btreeDegree, lessBtreeListColumnItem),
}
err := colPrune.buildPartitionValueMapAndSorted(p, defs)
if err != nil {
return err
}
if colPrune.defaultPartID > 0 {
for i := range defs {
if defs[i].ID == colPrune.defaultPartID {
if lp.defaultPartitionIdx >= 0 && i != lp.defaultPartitionIdx {
// Should be same for all columns, i.e. should never happen!
return table.ErrUnknownPartition
}
lp.defaultPartitionIdx = i
}
}
}
colPrunes = append(colPrunes, colPrune)
}
lp.ColPrunes = colPrunes
return nil
}
// buildListPartitionValueMap builds list partition value map.
// The map is column value -> partition index.
// colIdx is the column index in the list columns.
func (lp *ForListPruning) buildListPartitionValueMap(ctx expression.BuildContext, defs []model.PartitionDefinition,
schema *expression.Schema, names types.NameSlice, p *parser.Parser) error {
lp.valueMap = map[int64]int{}
lp.nullPartitionIdx = -1
lp.defaultPartitionIdx = -1
for partitionIdx, def := range defs {
for _, vs := range def.InValues {
if strings.EqualFold(vs[0], "DEFAULT") {
lp.defaultPartitionIdx = partitionIdx
continue
}
expr, err := parseSimpleExprWithNames(p, ctx, vs[0], schema, names)
if err != nil {
return errors.Trace(err)
}
v, isNull, err := expr.EvalInt(ctx.GetEvalCtx(), chunk.Row{})
if err != nil {
return errors.Trace(err)
}
if isNull {
lp.nullPartitionIdx = partitionIdx
continue
}
lp.valueMap[v] = partitionIdx
}
}
return nil
}
// LocatePartition locates partition by the column value
func (lp *ForListPruning) LocatePartition(value int64, isNull bool) int {
if isNull {
if lp.nullPartitionIdx >= 0 {
return lp.nullPartitionIdx
}
return lp.defaultPartitionIdx
}
partitionIdx, ok := lp.valueMap[value]
if !ok {
return lp.defaultPartitionIdx
}
return partitionIdx
}
func (lp *ForListPruning) locateListPartitionByRow(ctx expression.EvalContext, r []types.Datum) (int, error) {
value, isNull, err := lp.LocateExpr.EvalInt(ctx, chunk.MutRowFromDatums(r).ToRow())