forked from pingcap/tidb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
196 lines (176 loc) · 5.81 KB
/
index.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
package dbutil
import (
"context"
"database/sql"
"fmt"
"sort"
"strconv"
"github.com/pingcap/errors"
"github.com/pingcap/parser/model"
)
// IndexInfo contains information of table index.
type IndexInfo struct {
Table string
NoneUnique bool
KeyName string
SeqInIndex int
ColumnName string
Cardinality int
}
// ShowIndex returns result of executing `show index`
func ShowIndex(ctx context.Context, db *sql.DB, schemaName string, table string) ([]*IndexInfo, error) {
/*
show index example result:
mysql> show index from test;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| test | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | |
| test | 0 | aid | 1 | aid | A | 0 | NULL | NULL | YES | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
*/
indices := make([]*IndexInfo, 0, 3)
query := fmt.Sprintf("SHOW INDEX FROM `%s`.`%s`", schemaName, table)
rows, err := db.QueryContext(ctx, query)
if err != nil {
return nil, errors.Trace(err)
}
defer rows.Close()
for rows.Next() {
fields, err1 := ScanRow(rows)
if err1 != nil {
return nil, errors.Trace(err1)
}
seqInIndex, err1 := strconv.Atoi(string(fields["Seq_in_index"].Data))
if err != nil {
return nil, errors.Trace(err1)
}
cardinality, err1 := strconv.Atoi(string(fields["Cardinality"].Data))
if err != nil {
return nil, errors.Trace(err1)
}
index := &IndexInfo{
Table: string(fields["Table"].Data),
NoneUnique: string(fields["Non_unique"].Data) == "1",
KeyName: string(fields["Key_name"].Data),
ColumnName: string(fields["Column_name"].Data),
SeqInIndex: seqInIndex,
Cardinality: cardinality,
}
indices = append(indices, index)
}
return indices, nil
}
// FindSuitableColumnWithIndex returns first column of a suitable index.
// The priority is
// * primary key
// * unique key
// * normal index which has max cardinality
func FindSuitableColumnWithIndex(ctx context.Context, db *sql.DB, schemaName string, tableInfo *model.TableInfo) (*model.ColumnInfo, error) {
// find primary key
for _, index := range tableInfo.Indices {
if index.Primary {
return FindColumnByName(tableInfo.Columns, index.Columns[0].Name.O), nil
}
}
// no primary key found, seek unique index
for _, index := range tableInfo.Indices {
if index.Unique {
return FindColumnByName(tableInfo.Columns, index.Columns[0].Name.O), nil
}
}
// no unique index found, seek index with max cardinality
indices, err := ShowIndex(ctx, db, schemaName, tableInfo.Name.O)
if err != nil {
return nil, errors.Trace(err)
}
var c *model.ColumnInfo
var maxCardinality int
for _, indexInfo := range indices {
// just use the first column in the index, otherwise can't hit the index when select
if indexInfo.SeqInIndex != 1 {
continue
}
if indexInfo.Cardinality > maxCardinality {
column := FindColumnByName(tableInfo.Columns, indexInfo.ColumnName)
if column == nil {
return nil, errors.NotFoundf("column %s in %s.%s", indexInfo.ColumnName, schemaName, tableInfo.Name.O)
}
maxCardinality = indexInfo.Cardinality
c = column
}
}
return c, nil
}
// FindAllIndex returns all index, order is pk, uk, and normal index.
func FindAllIndex(tableInfo *model.TableInfo) []*model.IndexInfo {
indices := make([]*model.IndexInfo, len(tableInfo.Indices))
copy(indices, tableInfo.Indices)
sort.SliceStable(indices, func(i, j int) bool {
a := indices[i]
b := indices[j]
switch {
case b.Primary:
return false
case a.Primary:
return true
case b.Unique:
return false
case a.Unique:
return true
default:
return false
}
})
return indices
}
// FindAllColumnWithIndex returns columns with index, order is pk, uk and normal index.
func FindAllColumnWithIndex(tableInfo *model.TableInfo) []*model.ColumnInfo {
colsMap := make(map[string]interface{})
cols := make([]*model.ColumnInfo, 0, 2)
for _, index := range FindAllIndex(tableInfo) {
// index will be guaranteed to be visited in order PK -> UK -> IK
for _, indexCol := range index.Columns {
col := FindColumnByName(tableInfo.Columns, indexCol.Name.O)
if _, ok := colsMap[col.Name.O]; ok {
continue
}
colsMap[col.Name.O] = struct{}{}
cols = append(cols, col)
}
}
return cols
}
// SelectUniqueOrderKey returns some columns for order by condition.
func SelectUniqueOrderKey(tbInfo *model.TableInfo) ([]string, []*model.ColumnInfo) {
keys := make([]string, 0, 2)
keyCols := make([]*model.ColumnInfo, 0, 2)
for _, index := range tbInfo.Indices {
if index.Primary {
keys = keys[:0]
keyCols = keyCols[:0]
for _, indexCol := range index.Columns {
keys = append(keys, indexCol.Name.O)
keyCols = append(keyCols, tbInfo.Columns[indexCol.Offset])
}
break
}
if index.Unique {
keys = keys[:0]
keyCols = keyCols[:0]
for _, indexCol := range index.Columns {
keys = append(keys, indexCol.Name.O)
keyCols = append(keyCols, tbInfo.Columns[indexCol.Offset])
}
}
}
if len(keys) != 0 {
return keys, keyCols
}
// no primary key or unique found, use all fields as order by key
for _, col := range tbInfo.Columns {
keys = append(keys, col.Name.O)
keyCols = append(keyCols, col)
}
return keys, keyCols
}