forked from hidu/mysql-schema-sync
/
index.go
117 lines (101 loc) · 2.67 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
package internal
import (
"encoding/json"
"fmt"
"log"
"regexp"
"strings"
)
// DbIndex db index
type DbIndex struct {
IndexType IndexType
Name string
SQL string
RelationTables []string //相关联的表
}
type IndexType string
const (
IndexTypePrimary IndexType = "PRIMARY"
IndexTypeIndex IndexType = "INDEX"
IndexTypeForeignKey IndexType = "FOREIGN KEY"
)
func (idx *DbIndex) AlterAddSQL(drop bool) string {
alterSQL := []string{}
if drop {
dropSQL := idx.AlterDropSQL()
if dropSQL != "" {
alterSQL = append(alterSQL, dropSQL)
}
}
switch idx.IndexType {
case IndexTypePrimary:
alterSQL = append(alterSQL, "ADD "+idx.SQL)
case IndexTypeIndex, IndexTypeForeignKey:
alterSQL = append(alterSQL, fmt.Sprintf("ADD %s", idx.SQL))
default:
log.Fatalln("unknown indexType", idx.IndexType)
}
return strings.Join(alterSQL, ",\n")
}
func (idx *DbIndex) String() string {
bs, _ := json.MarshalIndent(idx, " ", " ")
return string(bs)
}
func (idx *DbIndex) AlterDropSQL() string {
switch idx.IndexType {
case IndexTypePrimary:
return "DROP PRIMARY KEY"
case IndexTypeIndex:
return fmt.Sprintf("DROP INDEX `%s`", idx.Name)
case IndexTypeForeignKey:
return fmt.Sprintf("DROP FOREIGN KEY `%s`", idx.Name)
default:
log.Fatalln("unknown indexType", idx.IndexType)
}
return ""
}
func (idx *DbIndex) addRelationTable(table string) {
table = strings.TrimSpace(table)
if table != "" {
idx.RelationTables = append(idx.RelationTables, table)
}
}
func (idx *DbIndex) AddRelationTable(table string) {
idx.addRelationTable(table)
}
// 匹配索引字段
var indexReg = regexp.MustCompile(`^([A-Z]+\s)?KEY\s`)
// 匹配外键
var foreignKeyReg = regexp.MustCompile("^CONSTRAINT `(.+)` FOREIGN KEY.+ REFERENCES `(.+)` ")
func parseDbIndexLine(line string) *DbIndex {
line = strings.TrimSpace(line)
idx := &DbIndex{
SQL: line,
RelationTables: []string{},
}
if strings.HasPrefix(line, "PRIMARY") {
idx.IndexType = IndexTypePrimary
idx.Name = "PRIMARY KEY"
return idx
}
// UNIQUE KEY `idx_a` (`a`) USING HASH COMMENT '注释',
// FULLTEXT KEY `c` (`c`)
// PRIMARY KEY (`d`)
// KEY `idx_e` (`e`),
if indexReg.MatchString(line) {
arr := strings.Split(line, "`")
idx.IndexType = IndexTypeIndex
idx.Name = arr[1]
return idx
}
//CONSTRAINT `busi_table_ibfk_1` FOREIGN KEY (`repo_id`) REFERENCES `repo_table` (`repo_id`)
foreignMatches := foreignKeyReg.FindStringSubmatch(line)
if len(foreignMatches) > 0 {
idx.IndexType = IndexTypeForeignKey
idx.Name = foreignMatches[1]
idx.addRelationTable(foreignMatches[2])
return idx
}
log.Fatalln("db_index parse failed, unsupported, line:", line)
return nil
}