forked from go-mysql-org/go-mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
470 lines (402 loc) · 11.4 KB
/
schema.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
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package schema
import (
"database/sql"
"fmt"
"strconv"
"strings"
"github.com/pingcap/errors"
"github.com/atoonk/go-mysql/mysql"
)
var ErrTableNotExist = errors.New("table is not exist")
var ErrMissingTableMeta = errors.New("missing table meta")
var HAHealthCheckSchema = "mysql.ha_health_check"
// Different column type
const (
TYPE_NUMBER = iota + 1 // tinyint, smallint, int, bigint, year
TYPE_FLOAT // float, double
TYPE_ENUM // enum
TYPE_SET // set
TYPE_STRING // char, varchar, etc.
TYPE_DATETIME // datetime
TYPE_TIMESTAMP // timestamp
TYPE_DATE // date
TYPE_TIME // time
TYPE_BIT // bit
TYPE_JSON // json
TYPE_DECIMAL // decimal
TYPE_MEDIUM_INT
TYPE_BINARY // binary, varbinary
TYPE_POINT // coordinates
)
type TableColumn struct {
Name string
Type int
Collation string
RawType string
IsAuto bool
IsUnsigned bool
IsVirtual bool
IsStored bool
EnumValues []string
SetValues []string
FixedSize uint
MaxSize uint
}
type Index struct {
Name string
Columns []string
Cardinality []uint64
NoneUnique uint64
}
type Table struct {
Schema string
Name string
Columns []TableColumn
Indexes []*Index
PKColumns []int
UnsignedColumns []int
}
func (ta *Table) String() string {
return fmt.Sprintf("%s.%s", ta.Schema, ta.Name)
}
func (ta *Table) AddColumn(name string, columnType string, collation string, extra string) {
index := len(ta.Columns)
ta.Columns = append(ta.Columns, TableColumn{Name: name, Collation: collation})
ta.Columns[index].RawType = columnType
if strings.HasPrefix(columnType, "float") ||
strings.HasPrefix(columnType, "double") {
ta.Columns[index].Type = TYPE_FLOAT
} else if strings.HasPrefix(columnType, "decimal") {
ta.Columns[index].Type = TYPE_DECIMAL
} else if strings.HasPrefix(columnType, "enum") {
ta.Columns[index].Type = TYPE_ENUM
ta.Columns[index].EnumValues = strings.Split(strings.Replace(
strings.TrimSuffix(
strings.TrimPrefix(
columnType, "enum("),
")"),
"'", "", -1),
",")
} else if strings.HasPrefix(columnType, "set") {
ta.Columns[index].Type = TYPE_SET
ta.Columns[index].SetValues = strings.Split(strings.Replace(
strings.TrimSuffix(
strings.TrimPrefix(
columnType, "set("),
")"),
"'", "", -1),
",")
} else if strings.HasPrefix(columnType, "binary") {
ta.Columns[index].Type = TYPE_BINARY
size := getSizeFromColumnType(columnType)
ta.Columns[index].MaxSize = size
ta.Columns[index].FixedSize = size
} else if strings.HasPrefix(columnType, "varbinary") {
ta.Columns[index].Type = TYPE_BINARY
ta.Columns[index].MaxSize = getSizeFromColumnType(columnType)
} else if strings.HasPrefix(columnType, "datetime") {
ta.Columns[index].Type = TYPE_DATETIME
} else if strings.HasPrefix(columnType, "timestamp") {
ta.Columns[index].Type = TYPE_TIMESTAMP
} else if strings.HasPrefix(columnType, "time") {
ta.Columns[index].Type = TYPE_TIME
} else if "date" == columnType {
ta.Columns[index].Type = TYPE_DATE
} else if strings.HasPrefix(columnType, "bit") {
ta.Columns[index].Type = TYPE_BIT
} else if strings.HasPrefix(columnType, "json") {
ta.Columns[index].Type = TYPE_JSON
} else if strings.Contains(columnType, "point") {
ta.Columns[index].Type = TYPE_POINT
} else if strings.Contains(columnType, "mediumint") {
ta.Columns[index].Type = TYPE_MEDIUM_INT
} else if strings.Contains(columnType, "int") || strings.HasPrefix(columnType, "year") {
ta.Columns[index].Type = TYPE_NUMBER
} else if strings.HasPrefix(columnType, "char") {
ta.Columns[index].Type = TYPE_STRING
size := getSizeFromColumnType(columnType)
ta.Columns[index].FixedSize = size
ta.Columns[index].MaxSize = size
} else {
ta.Columns[index].Type = TYPE_STRING
ta.Columns[index].MaxSize = getSizeFromColumnType(columnType)
}
if strings.Contains(columnType, "unsigned") || strings.Contains(columnType, "zerofill") {
ta.Columns[index].IsUnsigned = true
ta.UnsignedColumns = append(ta.UnsignedColumns, index)
}
if extra == "auto_increment" {
ta.Columns[index].IsAuto = true
} else if extra == "VIRTUAL GENERATED" {
ta.Columns[index].IsVirtual = true
} else if extra == "STORED GENERATED" {
ta.Columns[index].IsStored = true
}
}
func getSizeFromColumnType(columnType string) uint {
startIndex := strings.Index(columnType, "(")
if startIndex < 0 {
return 0
}
// we are searching for the first () and there may not be any closing
// brackets before the opening, so no need search at the offset from the
// opening ones
endIndex := strings.Index(columnType, ")")
if startIndex < 0 || endIndex < 0 || startIndex > endIndex {
return 0
}
i, err := strconv.Atoi(columnType[startIndex+1 : endIndex])
if err != nil || i < 0 {
return 0
}
return uint(i)
}
func (ta *Table) FindColumn(name string) int {
for i, col := range ta.Columns {
if col.Name == name {
return i
}
}
return -1
}
// Get TableColumn by column index of primary key.
func (ta *Table) GetPKColumn(index int) *TableColumn {
if index >= len(ta.PKColumns) {
return nil
}
return &ta.Columns[ta.PKColumns[index]]
}
func (ta *Table) IsPrimaryKey(colIndex int) bool {
for _, i := range ta.PKColumns {
if i == colIndex {
return true
}
}
return false
}
func (ta *Table) AddIndex(name string) (index *Index) {
index = NewIndex(name)
ta.Indexes = append(ta.Indexes, index)
return index
}
func NewIndex(name string) *Index {
return &Index{name, make([]string, 0, 8), make([]uint64, 0, 8), 0}
}
func (idx *Index) AddColumn(name string, cardinality uint64) {
idx.Columns = append(idx.Columns, name)
if cardinality == 0 {
cardinality = uint64(len(idx.Cardinality) + 1)
}
idx.Cardinality = append(idx.Cardinality, cardinality)
}
func (idx *Index) FindColumn(name string) int {
for i, colName := range idx.Columns {
if name == colName {
return i
}
}
return -1
}
func IsTableExist(conn mysql.Executer, schema string, name string) (bool, error) {
query := fmt.Sprintf("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s' and TABLE_NAME = '%s' LIMIT 1", schema, name)
r, err := conn.Execute(query)
if err != nil {
return false, errors.Trace(err)
}
return r.RowNumber() == 1, nil
}
func NewTableFromSqlDB(conn *sql.DB, schema string, name string) (*Table, error) {
ta := &Table{
Schema: schema,
Name: name,
Columns: make([]TableColumn, 0, 16),
Indexes: make([]*Index, 0, 8),
}
if err := ta.fetchColumnsViaSqlDB(conn); err != nil {
return nil, errors.Trace(err)
}
if err := ta.fetchIndexesViaSqlDB(conn); err != nil {
return nil, errors.Trace(err)
}
return ta, nil
}
func NewTable(conn mysql.Executer, schema string, name string) (*Table, error) {
ta := &Table{
Schema: schema,
Name: name,
Columns: make([]TableColumn, 0, 16),
Indexes: make([]*Index, 0, 8),
}
if err := ta.fetchColumns(conn); err != nil {
return nil, errors.Trace(err)
}
if err := ta.fetchIndexes(conn); err != nil {
return nil, errors.Trace(err)
}
return ta, nil
}
func (ta *Table) fetchColumns(conn mysql.Executer) error {
r, err := conn.Execute(fmt.Sprintf("show full columns from `%s`.`%s`", ta.Schema, ta.Name))
if err != nil {
return errors.Trace(err)
}
for i := 0; i < r.RowNumber(); i++ {
name, _ := r.GetString(i, 0)
colType, _ := r.GetString(i, 1)
collation, _ := r.GetString(i, 2)
extra, _ := r.GetString(i, 6)
ta.AddColumn(name, colType, collation, extra)
}
return nil
}
func (ta *Table) fetchColumnsViaSqlDB(conn *sql.DB) error {
r, err := conn.Query(fmt.Sprintf("show full columns from `%s`.`%s`", ta.Schema, ta.Name))
if err != nil {
return errors.Trace(err)
}
defer r.Close()
var unusedVal interface{}
unused := &unusedVal
for r.Next() {
var name, colType, extra string
var collation sql.NullString
err := r.Scan(&name, &colType, &collation, &unused, &unused, &unused, &extra, &unused, &unused)
if err != nil {
return errors.Trace(err)
}
ta.AddColumn(name, colType, collation.String, extra)
}
return r.Err()
}
func (ta *Table) fetchIndexes(conn mysql.Executer) error {
r, err := conn.Execute(fmt.Sprintf("show index from `%s`.`%s`", ta.Schema, ta.Name))
if err != nil {
return errors.Trace(err)
}
var currentIndex *Index
currentName := ""
for i := 0; i < r.RowNumber(); i++ {
indexName, _ := r.GetString(i, 2)
if currentName != indexName {
currentIndex = ta.AddIndex(indexName)
currentName = indexName
}
cardinality, _ := r.GetUint(i, 6)
colName, _ := r.GetString(i, 4)
currentIndex.AddColumn(colName, cardinality)
currentIndex.NoneUnique, _ = r.GetUint(i, 1)
}
return ta.fetchPrimaryKeyColumns()
}
func (ta *Table) fetchIndexesViaSqlDB(conn *sql.DB) error {
r, err := conn.Query(fmt.Sprintf("show index from `%s`.`%s`", ta.Schema, ta.Name))
if err != nil {
return errors.Trace(err)
}
defer r.Close()
var currentIndex *Index
currentName := ""
var unusedVal interface{}
for r.Next() {
var indexName, colName string
var noneUnique uint64
var cardinality interface{}
cols, err := r.Columns()
if err != nil {
return errors.Trace(err)
}
values := make([]interface{}, len(cols))
for i := 0; i < len(cols); i++ {
switch i {
case 1:
values[i] = &noneUnique
case 2:
values[i] = &indexName
case 4:
values[i] = &colName
case 6:
values[i] = &cardinality
default:
values[i] = &unusedVal
}
}
err = r.Scan(values...)
if err != nil {
return errors.Trace(err)
}
if currentName != indexName {
currentIndex = ta.AddIndex(indexName)
currentName = indexName
}
c := toUint64(cardinality)
currentIndex.AddColumn(colName, c)
currentIndex.NoneUnique = noneUnique
}
return ta.fetchPrimaryKeyColumns()
}
func toUint64(i interface{}) uint64 {
switch i := i.(type) {
case int:
return uint64(i)
case int8:
return uint64(i)
case int16:
return uint64(i)
case int32:
return uint64(i)
case int64:
return uint64(i)
case uint:
return uint64(i)
case uint8:
return uint64(i)
case uint16:
return uint64(i)
case uint32:
return uint64(i)
case uint64:
return i
}
return 0
}
func (ta *Table) fetchPrimaryKeyColumns() error {
if len(ta.Indexes) == 0 {
return nil
}
// Primary key must be the first index?
pkIndex := ta.Indexes[0]
if pkIndex.Name != "PRIMARY" {
return nil
}
ta.PKColumns = make([]int, len(pkIndex.Columns))
for i, pkCol := range pkIndex.Columns {
ta.PKColumns[i] = ta.FindColumn(pkCol)
}
return nil
}
// GetPKValues gets primary keys in one row for a table, a table may use multi fields as the PK
func (ta *Table) GetPKValues(row []interface{}) ([]interface{}, error) {
indexes := ta.PKColumns
if len(indexes) == 0 {
return nil, errors.Errorf("table %s has no PK", ta)
} else if len(ta.Columns) != len(row) {
return nil, errors.Errorf("table %s has %d columns, but row data %v len is %d", ta,
len(ta.Columns), row, len(row))
}
values := make([]interface{}, 0, len(indexes))
for _, index := range indexes {
values = append(values, row[index])
}
return values, nil
}
// GetColumnValue gets term column's value
func (ta *Table) GetColumnValue(column string, row []interface{}) (interface{}, error) {
index := ta.FindColumn(column)
if index == -1 {
return nil, errors.Errorf("table %s has no column name %s", ta, column)
}
return row[index], nil
}