forked from yunionio/sqlchemy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.go
More file actions
286 lines (263 loc) · 7.07 KB
/
sync.go
File metadata and controls
286 lines (263 loc) · 7.07 KB
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
package sqlchemy
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"yunion.io/x/log"
"yunion.io/x/pkg/utils"
)
type SSqlColumnInfo struct {
Field string
Type string
Collation string
Null string
Key string
Default string
Extra string
Privileges string
Comment string
}
func decodeSqlTypeString(typeStr string) []string {
typeReg := regexp.MustCompile(`(\w+)\((\d+)(,\s*(\d+))?\)`)
matches := typeReg.FindStringSubmatch(typeStr)
if len(matches) >= 3 {
return matches[1:]
} else {
return []string{typeStr}
}
}
func (info *SSqlColumnInfo) toColumnSpec() IColumnSpec {
tagmap := make(map[string]string)
matches := decodeSqlTypeString(info.Type)
typeStr := strings.ToUpper(matches[0])
width := 0
if len(matches) > 1 {
width, _ = strconv.Atoi(matches[1])
}
if width > 0 {
tagmap[TAG_WIDTH] = fmt.Sprintf("%d", width)
}
if info.Null == "YES" {
tagmap[TAG_NULLABLE] = "true"
} else {
tagmap[TAG_NULLABLE] = "false"
}
if info.Key == "PRI" {
tagmap[TAG_PRIMARY] = "true"
} else {
tagmap[TAG_PRIMARY] = "false"
}
charset := ""
if info.Collation == "ascii_general_ci" {
charset = "ascii"
} else if info.Collation == "utf8_general_ci" {
charset = "utf8"
}
if len(charset) > 0 {
tagmap[TAG_CHARSET] = charset
}
if info.Default != "NULL" {
tagmap[TAG_DEFAULT] = info.Default
}
if strings.HasSuffix(typeStr, "CHAR") {
c := NewTextColumn(info.Field, tagmap, false)
return &c
} else if strings.HasSuffix(typeStr, "TEXT") {
tagmap[TAG_TEXT_LENGTH] = typeStr[:len(typeStr)-4]
c := NewTextColumn(info.Field, tagmap, false)
return &c
} else if strings.HasSuffix(typeStr, "INT") {
if info.Extra == "auto_increment" {
tagmap[TAG_AUTOINCREMENT] = "true"
}
unsigned := false
if strings.HasSuffix(info.Type, " unsigned") {
unsigned = true
}
c := NewIntegerColumn(info.Field, typeStr, unsigned, tagmap, false)
return &c
} else if typeStr == "FLOAT" || typeStr == "DOUBLE" {
c := NewFloatColumn(info.Field, typeStr, tagmap, false)
return &c
} else if typeStr == "DECIMAL" {
if len(matches) > 3 {
precision, _ := strconv.Atoi(matches[3])
if precision > 0 {
tagmap[TAG_PRECISION] = fmt.Sprintf("%d", precision)
}
}
c := NewDecimalColumn(info.Field, tagmap, false)
return &c
} else if typeStr == "DATETIME" {
c := NewDateTimeColumn(info.Field, tagmap, false)
return &c
} else {
log.Errorf("unsupported type %s", typeStr)
return nil
}
}
func (ts *STableSpec) fetchColumnDefs() ([]IColumnSpec, error) {
sql := fmt.Sprintf("SHOW FULL COLUMNS IN %s", ts.name)
query := NewRawQuery(sql, "field", "type", "collation", "null", "key", "default", "extra", "privileges", "comment")
infos := make([]SSqlColumnInfo, 0)
err := query.All(&infos)
if err != nil {
return nil, err
}
specs := make([]IColumnSpec, 0)
for _, info := range infos {
specs = append(specs, info.toColumnSpec())
}
return specs, nil
}
func (ts *STableSpec) fetchIndexesAndConstraints() ([]STableIndex, []STableConstraint, error) {
sql := fmt.Sprintf("SHOW CREATE TABLE %s", ts.name)
query := NewRawQuery(sql, "table", "create table")
row := query.Row()
var name, defStr string
err := row.Scan(&name, &defStr)
if err != nil {
log.Errorf("fetch create table info fail %s", err)
return nil, nil, err
}
indexes := parseIndexes(defStr)
constraints := parseConstraints(defStr)
return indexes, constraints, nil
}
func compareColumnSpec(c1, c2 IColumnSpec) int {
return strings.Compare(c1.Name(), c2.Name())
}
func diffCols(cols1 []IColumnSpec, cols2 []IColumnSpec) ([]IColumnSpec, []IColumnSpec, []IColumnSpec) {
sort.Slice(cols1, func(i, j int) bool {
return compareColumnSpec(cols1[i], cols1[j]) < 0
})
sort.Slice(cols2, func(i, j int) bool {
return compareColumnSpec(cols2[i], cols2[j]) < 0
})
i := 0
j := 0
remove := make([]IColumnSpec, 0)
update := make([]IColumnSpec, 0)
add := make([]IColumnSpec, 0)
for i < len(cols1) || j < len(cols2) {
if i < len(cols1) && j < len(cols2) {
comp := compareColumnSpec(cols1[i], cols2[j])
if comp == 0 {
if cols1[i].DefinitionString() != cols2[j].DefinitionString() {
log.Infof("UPDATE: %s => %s", cols1[i].DefinitionString(), cols2[j].DefinitionString())
update = append(update, cols2[j])
}
i += 1
j += 1
} else if comp > 0 {
add = append(add, cols2[j])
j += 1
} else {
remove = append(remove, cols1[i])
i += 1
}
} else if i < len(cols1) {
remove = append(remove, cols1[i])
i += 1
} else if j < len(cols2) {
add = append(add, cols2[j])
j += 1
}
}
return remove, update, add
}
func diffIndexes2(exists []STableIndex, defs []STableIndex) (diff []STableIndex) {
diff = make([]STableIndex, 0)
for i := 0; i < len(exists); i += 1 {
findDef := false
for j := 0; j < len(defs); j += 1 {
if defs[j].IsIdentical(exists[i].columns...) {
findDef = true
break
}
}
if !findDef {
diff = append(diff, exists[i])
}
}
return
}
func diffIndexes(exists []STableIndex, defs []STableIndex) (added []STableIndex, removed []STableIndex) {
return diffIndexes2(defs, exists), diffIndexes2(exists, defs)
}
func (ts *STableSpec) SyncSQL() []string {
tables := GetTables()
in, _ := utils.InStringArray(ts.name, tables)
if !in {
log.Debugf("table %s not created yet", ts.name)
sql := ts.CreateSQL()
return []string{sql}
}
indexes, constraints, err := ts.fetchIndexesAndConstraints()
if err != nil {
log.Errorf("fetchIndexesAndConstraints fail %s", err)
return nil
}
ret := make([]string, 0)
cols, err := ts.fetchColumnDefs()
if err != nil {
log.Errorf("fetchColumnDefs fail: %s", err)
return nil
}
for _, constraint := range constraints {
sql := fmt.Sprintf("ALTER TABLE %s DROP FOREIGN KEY %s", ts.name, constraint.name)
ret = append(ret, sql)
log.Infof(sql)
}
addIndexes, removeIndexes := diffIndexes(indexes, ts.indexes)
for _, idx := range removeIndexes {
sql := fmt.Sprintf("DROP INDEX `%s` ON `%s`", idx.name, ts.name)
ret = append(ret, sql)
log.Infof(sql)
}
remove, update, add := diffCols(cols, ts.columns)
/* IGNORE DROP STATEMENT */
for _, col := range remove {
sql := fmt.Sprintf("ALTER TABLE `%s` DROP COLUMN `%s`;", ts.name, col.Name())
// ret = append(ret, sql)
log.Infof(sql)
}
for _, col := range update {
sql := fmt.Sprintf("ALTER TABLE `%s` MODIFY %s;", ts.name, col.DefinitionString())
ret = append(ret, sql)
}
for _, col := range add {
sql := fmt.Sprintf("ALTER TABLE `%s` ADD %s;", ts.name, col.DefinitionString())
ret = append(ret, sql)
}
for _, idx := range addIndexes {
sql := fmt.Sprintf("CREATE INDEX `%s` ON `%s` (%s)", idx.name, ts.name, strings.Join(idx.QuotedColumns(), ","))
ret = append(ret, sql)
log.Infof(sql)
}
return ret
}
func (ts *STableSpec) Sync() error {
sqls := ts.SyncSQL()
if sqls != nil {
for _, sql := range sqls {
_, err := _db.Exec(sql)
if err != nil {
log.Errorf("exec sql error %s: %s", sql, err)
return err
}
}
}
return nil
}
func (ts *STableSpec) CheckSync() {
sqls := ts.SyncSQL()
if len(sqls) > 0 {
for _, sql := range sqls {
fmt.Println(sql)
}
log.Fatalf("DB table %q not in sync", ts.name)
}
}