-
Notifications
You must be signed in to change notification settings - Fork 269
/
schema_storage.go
513 lines (465 loc) · 15.6 KB
/
schema_storage.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
// Copyright 2020 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package model
import (
"fmt"
"github.com/pingcap/log"
"github.com/pingcap/tidb/pkg/parser/model"
"github.com/pingcap/tidb/pkg/parser/mysql"
"github.com/pingcap/tidb/pkg/parser/types"
"github.com/pingcap/tidb/pkg/table/tables"
datumTypes "github.com/pingcap/tidb/pkg/types"
"github.com/pingcap/tidb/pkg/util/rowcodec"
"go.uber.org/zap"
)
const (
// HandleIndexPKIsHandle represents that the handle index is the pk and the pk is the handle
HandleIndexPKIsHandle = -1
// HandleIndexTableIneligible represents that the table is ineligible
HandleIndexTableIneligible = -2
)
// TableInfo provides meta data describing a DB table.
type TableInfo struct {
*model.TableInfo
SchemaID int64
// NOTICE: We probably store the logical ID inside TableName,
// not the physical ID.
// For normal table, there is only one ID, which is the physical ID.
// AKA TIDB_TABLE_ID.
// For partitioned table, there are two kinds of ID:
// 1. TIDB_PARTITION_ID is the physical ID of the partition.
// 2. TIDB_TABLE_ID is the logical ID of the table.
// In general, we always use the physical ID to represent a table, but we
// record the logical ID from the DDL event(job.BinlogInfo.TableInfo).
// So be careful when using the TableInfo.
TableName TableName
// Version record the tso of create the table info.
Version uint64
// ColumnID -> offset in model.TableInfo.Columns
columnsOffset map[int64]int
// ColumnID -> offset in model.TableInfo.Indices
indicesOffset map[int64]int
// Column name -> ColumnID
nameToColID map[string]int64
hasUniqueColumn bool
// ColumnID -> offset in RowChangedEvents.Columns.
RowColumnsOffset map[int64]int
ColumnsFlag map[int64]*ColumnFlagType
// the mounter will choose this index to output delete events
// special value:
// HandleIndexPKIsHandle(-1) : pk is handle
// HandleIndexTableIneligible(-2) : the table is not eligible
HandleIndexID int64
// IndexColumnsOffset store the offset of the columns in row changed events for
// unique index and primary key
// The reason why we need this is that the Indexes in TableInfo
// will not contain the PK if it is create in statement like:
// create table t (a int primary key, b int unique key);
// Every element in first dimension is a index, and the second dimension is the columns offset
// for example:
// table has 3 columns: a, b, c
// pk: a
// index1: a, b
// index2: a, c
// indexColumnsOffset: [[0], [0, 1], [0, 2]]
IndexColumnsOffset [][]int
// The following 3 fields, should only be used to decode datum from the raw value bytes, do not abuse those field.
// rowColInfos extend the model.ColumnInfo with some extra information
// it's the same length and order with the model.TableInfo.Columns
rowColInfos []rowcodec.ColInfo
rowColFieldTps map[int64]*types.FieldType
// only for new row format decoder
handleColID []int64
// number of virtual columns
virtualColumnCount int
// rowColInfosWithoutVirtualCols is the same as rowColInfos, but without virtual columns
rowColInfosWithoutVirtualCols *[]rowcodec.ColInfo
}
// WrapTableInfo creates a TableInfo from a timodel.TableInfo
func WrapTableInfo(schemaID int64, schemaName string, version uint64, info *model.TableInfo) *TableInfo {
ti := &TableInfo{
TableInfo: info,
SchemaID: schemaID,
TableName: TableName{
Schema: schemaName,
Table: info.Name.O,
TableID: info.ID,
IsPartition: info.GetPartitionInfo() != nil,
},
hasUniqueColumn: false,
Version: version,
columnsOffset: make(map[int64]int, len(info.Columns)),
indicesOffset: make(map[int64]int, len(info.Indices)),
nameToColID: make(map[string]int64, len(info.Columns)),
RowColumnsOffset: make(map[int64]int, len(info.Columns)),
ColumnsFlag: make(map[int64]*ColumnFlagType, len(info.Columns)),
handleColID: []int64{-1},
HandleIndexID: HandleIndexTableIneligible,
rowColInfos: make([]rowcodec.ColInfo, len(info.Columns)),
rowColFieldTps: make(map[int64]*types.FieldType, len(info.Columns)),
}
rowColumnsCurrentOffset := 0
ti.virtualColumnCount = 0
for i, col := range ti.Columns {
ti.columnsOffset[col.ID] = i
pkIsHandle := false
if IsColCDCVisible(col) {
ti.nameToColID[col.Name.O] = col.ID
ti.RowColumnsOffset[col.ID] = rowColumnsCurrentOffset
rowColumnsCurrentOffset++
pkIsHandle = (ti.PKIsHandle && mysql.HasPriKeyFlag(col.GetFlag())) || col.ID == model.ExtraHandleID
if pkIsHandle {
// pk is handle
ti.handleColID = []int64{col.ID}
ti.HandleIndexID = HandleIndexPKIsHandle
ti.hasUniqueColumn = true
ti.IndexColumnsOffset = append(ti.IndexColumnsOffset, []int{ti.RowColumnsOffset[col.ID]})
} else if ti.IsCommonHandle {
ti.HandleIndexID = HandleIndexPKIsHandle
ti.handleColID = ti.handleColID[:0]
pkIdx := tables.FindPrimaryIndex(info)
for _, pkCol := range pkIdx.Columns {
id := info.Columns[pkCol.Offset].ID
ti.handleColID = append(ti.handleColID, id)
}
}
} else {
ti.virtualColumnCount += 1
}
ti.rowColInfos[i] = rowcodec.ColInfo{
ID: col.ID,
IsPKHandle: pkIsHandle,
Ft: col.FieldType.Clone(),
VirtualGenCol: col.IsGenerated(),
}
ti.rowColFieldTps[col.ID] = ti.rowColInfos[i].Ft
}
for i, idx := range ti.Indices {
ti.indicesOffset[idx.ID] = i
if ti.IsIndexUnique(idx) {
ti.hasUniqueColumn = true
}
if idx.Primary || idx.Unique {
indexColOffset := make([]int, 0, len(idx.Columns))
for _, idxCol := range idx.Columns {
colInfo := ti.Columns[idxCol.Offset]
if IsColCDCVisible(colInfo) {
indexColOffset = append(indexColOffset, ti.RowColumnsOffset[colInfo.ID])
}
}
if len(indexColOffset) > 0 {
ti.IndexColumnsOffset = append(ti.IndexColumnsOffset, indexColOffset)
}
}
}
ti.initRowColInfosWithoutVirtualCols()
ti.findHandleIndex()
ti.initColumnsFlag()
return ti
}
func (ti *TableInfo) initRowColInfosWithoutVirtualCols() {
if ti.virtualColumnCount == 0 {
ti.rowColInfosWithoutVirtualCols = &ti.rowColInfos
return
}
colInfos := make([]rowcodec.ColInfo, 0, len(ti.rowColInfos)-ti.virtualColumnCount)
for i, col := range ti.Columns {
if IsColCDCVisible(col) {
colInfos = append(colInfos, ti.rowColInfos[i])
}
}
if len(colInfos) != len(ti.rowColInfos)-ti.virtualColumnCount {
log.Panic("invalid rowColInfosWithoutVirtualCols",
zap.Int("len(colInfos)", len(colInfos)),
zap.Int("len(ti.rowColInfos)", len(ti.rowColInfos)),
zap.Int("ti.virtualColumnCount", ti.virtualColumnCount))
}
ti.rowColInfosWithoutVirtualCols = &colInfos
}
func (ti *TableInfo) findHandleIndex() {
if ti.HandleIndexID == HandleIndexPKIsHandle {
// pk is handle
return
}
handleIndexOffset := -1
for i, idx := range ti.Indices {
if !ti.IsIndexUnique(idx) {
continue
}
if idx.Primary {
handleIndexOffset = i
break
}
if handleIndexOffset < 0 {
handleIndexOffset = i
} else {
if len(ti.Indices[handleIndexOffset].Columns) > len(ti.Indices[i].Columns) ||
(len(ti.Indices[handleIndexOffset].Columns) == len(ti.Indices[i].Columns) &&
ti.Indices[handleIndexOffset].ID > ti.Indices[i].ID) {
handleIndexOffset = i
}
}
}
if handleIndexOffset >= 0 {
ti.HandleIndexID = ti.Indices[handleIndexOffset].ID
}
}
func (ti *TableInfo) initColumnsFlag() {
for _, colInfo := range ti.Columns {
var flag ColumnFlagType
if colInfo.GetCharset() == "binary" {
flag.SetIsBinary()
}
if colInfo.IsGenerated() {
flag.SetIsGeneratedColumn()
}
if mysql.HasPriKeyFlag(colInfo.GetFlag()) {
flag.SetIsPrimaryKey()
if ti.HandleIndexID == HandleIndexPKIsHandle {
flag.SetIsHandleKey()
}
}
if mysql.HasUniKeyFlag(colInfo.GetFlag()) {
flag.SetIsUniqueKey()
}
if !mysql.HasNotNullFlag(colInfo.GetFlag()) {
flag.SetIsNullable()
}
if mysql.HasMultipleKeyFlag(colInfo.GetFlag()) {
flag.SetIsMultipleKey()
}
if mysql.HasUnsignedFlag(colInfo.GetFlag()) {
flag.SetIsUnsigned()
}
ti.ColumnsFlag[colInfo.ID] = &flag
}
// In TiDB, just as in MySQL, only the first column of an index can be marked as "multiple key" or "unique key",
// and only the first column of a unique index may be marked as "unique key".
// See https://dev.mysql.com/doc/refman/5.7/en/show-columns.html.
// Yet if an index has multiple columns, we would like to easily determine that all those columns are indexed,
// which is crucial for the completeness of the information we pass to the downstream.
// Therefore, instead of using the MySQL standard,
// we made our own decision to mark all columns in an index with the appropriate flag(s).
for _, idxInfo := range ti.Indices {
for _, idxCol := range idxInfo.Columns {
colInfo := ti.Columns[idxCol.Offset]
flag := ti.ColumnsFlag[colInfo.ID]
if idxInfo.Primary {
flag.SetIsPrimaryKey()
} else if idxInfo.Unique {
flag.SetIsUniqueKey()
}
if len(idxInfo.Columns) > 1 {
flag.SetIsMultipleKey()
}
if idxInfo.ID == ti.HandleIndexID && ti.HandleIndexID >= 0 {
flag.SetIsHandleKey()
}
ti.ColumnsFlag[colInfo.ID] = flag
}
}
}
// GetColumnInfo returns the column info by ID
func (ti *TableInfo) GetColumnInfo(colID int64) (info *model.ColumnInfo, exist bool) {
colOffset, exist := ti.columnsOffset[colID]
if !exist {
return nil, false
}
return ti.Columns[colOffset], true
}
// ForceGetColumnInfo return the column info by ID
// Caller must ensure `colID` exists
func (ti *TableInfo) ForceGetColumnInfo(colID int64) *model.ColumnInfo {
colInfo, ok := ti.GetColumnInfo(colID)
if !ok {
log.Panic("invalid column id", zap.Int64("columnID", colID))
}
return colInfo
}
// ForceGetColumnFlagType return the column flag type by ID
// Caller must ensure `colID` exists
func (ti *TableInfo) ForceGetColumnFlagType(colID int64) *ColumnFlagType {
flag, ok := ti.ColumnsFlag[colID]
if !ok {
log.Panic("invalid column id", zap.Int64("columnID", colID))
}
return flag
}
// ForceGetColumnName return the column name by ID
// Caller must ensure `colID` exists
func (ti *TableInfo) ForceGetColumnName(colID int64) string {
return ti.ForceGetColumnInfo(colID).Name.O
}
// ForceGetColumnIDByName return column ID by column name
// Caller must ensure `colID` exists
func (ti *TableInfo) ForceGetColumnIDByName(name string) int64 {
colID, ok := ti.nameToColID[name]
if !ok {
log.Panic("invalid column name", zap.String("column", name))
}
return colID
}
// GetSchemaName returns the schema name of the table
func (ti *TableInfo) GetSchemaName() string {
return ti.TableName.Schema
}
// GetTableName returns the table name of the table
func (ti *TableInfo) GetTableName() string {
return ti.TableName.Table
}
// GetSchemaNamePtr returns the pointer to the schema name of the table
func (ti *TableInfo) GetSchemaNamePtr() *string {
return &ti.TableName.Schema
}
// GetTableNamePtr returns the pointer to the table name of the table
func (ti *TableInfo) GetTableNamePtr() *string {
return &ti.TableName.Table
}
// IsPartitionTable returns whether the table is partition table
func (ti *TableInfo) IsPartitionTable() bool {
return ti.TableName.IsPartition
}
func (ti *TableInfo) String() string {
return fmt.Sprintf("TableInfo, ID: %d, Name:%s, ColNum: %d, IdxNum: %d, PKIsHandle: %t", ti.ID, ti.TableName, len(ti.Columns), len(ti.Indices), ti.PKIsHandle)
}
// GetRowColInfos returns all column infos for rowcodec
func (ti *TableInfo) GetRowColInfos() ([]int64, map[int64]*types.FieldType, []rowcodec.ColInfo) {
return ti.handleColID, ti.rowColFieldTps, ti.rowColInfos
}
// GetColInfosForRowChangedEvent return column infos for non-virtual columns
// The column order in the result is the same as the order in its corresponding RowChangedEvent
func (ti *TableInfo) GetColInfosForRowChangedEvent() []rowcodec.ColInfo {
return *ti.rowColInfosWithoutVirtualCols
}
// IsColCDCVisible returns whether the col is visible for CDC
func IsColCDCVisible(col *model.ColumnInfo) bool {
// this column is a virtual generated column
if col.IsGenerated() && !col.GeneratedStored {
return false
}
return true
}
// HasUniqueColumn returns whether the table has a unique column
func (ti *TableInfo) HasUniqueColumn() bool {
return ti.hasUniqueColumn
}
// HasVirtualColumns returns whether the table has virtual columns
func (ti *TableInfo) HasVirtualColumns() bool {
return ti.virtualColumnCount > 0
}
// IsEligible returns whether the table is a eligible table
func (ti *TableInfo) IsEligible(forceReplicate bool) bool {
// Sequence is not supported yet, TiCDC needs to filter all sequence tables.
// See https://github.com/pingcap/tiflow/issues/4559
if ti.IsSequence() {
return false
}
if forceReplicate {
return true
}
if ti.IsView() {
return true
}
return ti.HasUniqueColumn()
}
// IsIndexUnique returns whether the index is unique
func (ti *TableInfo) IsIndexUnique(indexInfo *model.IndexInfo) bool {
if indexInfo.Primary {
return true
}
if indexInfo.Unique {
for _, col := range indexInfo.Columns {
colInfo := ti.Columns[col.Offset]
if !mysql.HasNotNullFlag(colInfo.GetFlag()) {
return false
}
// this column is a virtual generated column
if colInfo.IsGenerated() && !colInfo.GeneratedStored {
return false
}
}
return true
}
return false
}
// Clone clones the TableInfo
func (ti *TableInfo) Clone() *TableInfo {
return WrapTableInfo(ti.SchemaID, ti.TableName.Schema, ti.Version, ti.TableInfo.Clone())
}
// GetIndex return the corresponding index by the given name.
func (ti *TableInfo) GetIndex(name string) *model.IndexInfo {
for _, index := range ti.Indices {
if index != nil && index.Name.O == name {
return index
}
}
return nil
}
// IndexByName returns the index columns and offsets of the corresponding index by name
func (ti *TableInfo) IndexByName(name string) ([]string, []int, bool) {
index := ti.GetIndex(name)
if index == nil {
return nil, nil, false
}
names := make([]string, 0, len(index.Columns))
offset := make([]int, 0, len(index.Columns))
for _, col := range index.Columns {
names = append(names, col.Name.O)
offset = append(offset, col.Offset)
}
return names, offset, true
}
// OffsetsByNames returns the column offsets of the corresponding columns by names
// If any column does not exist, return false
func (ti *TableInfo) OffsetsByNames(names []string) ([]int, bool) {
// todo: optimize it
columnOffsets := make(map[string]int, len(ti.Columns))
for _, col := range ti.Columns {
if col != nil {
columnOffsets[col.Name.O] = col.Offset
}
}
result := make([]int, 0, len(names))
for _, col := range names {
offset, ok := columnOffsets[col]
if !ok {
return nil, false
}
result = append(result, offset)
}
return result, true
}
// GetPrimaryKeyColumnNames returns the primary key column names
func (ti *TableInfo) GetPrimaryKeyColumnNames() []string {
var result []string
if ti.PKIsHandle {
result = append(result, ti.GetPkColInfo().Name.O)
return result
}
indexInfo := ti.GetPrimaryKey()
if indexInfo != nil {
for _, col := range indexInfo.Columns {
result = append(result, col.Name.O)
}
}
return result
}
// GetColumnDefaultValue returns the default definition of a column.
func GetColumnDefaultValue(col *model.ColumnInfo) interface{} {
defaultValue := col.GetDefaultValue()
if defaultValue == nil {
defaultValue = col.GetOriginDefaultValue()
}
defaultDatum := datumTypes.NewDatum(defaultValue)
return defaultDatum.GetValue()
}