-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
506 lines (449 loc) · 10.9 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"database/sql"
"github.com/BurntSushi/toml"
_ "github.com/go-sql-driver/mysql"
)
type tomlConfig struct {
SchemaName1 string
SchemaName2 string
Servers map[string]database
}
type database struct {
Host string
Port string
User string
Password string
Name string
}
type column struct {
Name string
Type string
IsNullable string
Default interface{}
After string
}
var (
driverName string
dbConfig tomlConfig
dLog *log.Logger
)
func init() {
driverName = "mysql"
}
// Conn 连接数据库
func Conn(dataSourceName string) *sql.DB {
//连接数据库
db, err := sql.Open(driverName, dataSourceName)
if err != nil {
dLog.Println(err.Error())
os.Exit(-1)
}
if err := db.Ping(); err != nil {
panic("ERROR:" + err.Error())
}
return db
}
func getSource(db string) (source string) {
// dataSourceName = "用户名:密码@tcp(localhost:3306)/数据库名称?charset=utf8"
source = dbConfig.Servers[db].User +
":" +
dbConfig.Servers[db].Password +
"@tcp(" +
dbConfig.Servers[db].Host +
":" +
dbConfig.Servers[db].Port +
")/" +
dbConfig.Servers[db].Name +
"?charset=utf8"
return
}
func main() {
// 定义一个日志
logFile, err := os.Create("diff.log")
defer logFile.Close()
if err != nil {
log.Fatalln("open file error !")
}
// 创建一个日志对象
dLog = log.New(logFile, "[Info]", log.LstdFlags) //|log.Lshortfile)
//配置一个日志格式的前缀
dLog.SetPrefix("[Info]")
//配置log的Flag参数
dLog.SetFlags(dLog.Flags() | log.LstdFlags)
dLog.Println("开始执行……")
// 读取配置文件
if _, err := toml.DecodeFile("config.toml", &dbConfig); err != nil {
fmt.Println("解析错误:", err.Error())
return
}
// 获得一个sql连接
dLog.Printf("连接%s/%s数据库……", dbConfig.Servers["1"].Host, dbConfig.Servers["1"].Name)
schema1 := dbConfig.SchemaName1
db1 := Conn(getSource("1"))
defer db1.Close()
// 获得第二个sql连接
dLog.Printf("连接%s/%s数据库……", dbConfig.Servers["2"].Host, dbConfig.Servers["2"].Name)
schema2 := dbConfig.SchemaName2
db2 := Conn(getSource("2"))
defer db2.Close()
// 对比触发器
dLog.Println("对比触发器……")
TriggerDiff(db1, db2, schema1, schema2)
// 对比函数
dLog.Println("对比函数……")
FunctionDiff(db1, db2, schema1, schema2)
// 对比表
dLog.Println("对比表……")
ts, b := TableDiff(db1, db2, schema1, schema2)
if b {
// 对比列名
dLog.Println("对比列名……")
ColumnDiff(db1, db2, schema1, schema2, ts)
// 对比索引
dLog.Println("对比索引……")
IndexDiff(db1, db2, schema1, schema2, ts)
}
dLog.Println("执行结束……")
}
// TableDiff 对比表的不同
func TableDiff(db1, db2 *sql.DB, schema1, schema2 string) (t []string, b bool) {
tableName1, err := getTableName(db1, schema1)
if err != nil {
dLog.Fatalln(err.Error())
}
dLog.Println(dbConfig.Servers["1"].Host, "/", schema1, " 表名: ", tableName1)
tableName2, err := getTableName(db2, schema2)
if err != nil {
dLog.Fatalln(err.Error())
}
dLog.Println(dbConfig.Servers["2"].Host, "/", schema2, " 表名: ", tableName2)
if !isEqual(tableName1, tableName2) {
t = diffName(tableName1, tableName2)
dLog.Printf("两个数据库不同的表,共有%d个,分别是:%s", len(t), t)
return t, false
}
t = tableName1
dLog.Printf("两个数据库表相同")
return t, true
}
func getTableName(s *sql.DB, table string) (ts []string, err error) {
stm, perr := s.Prepare("select table_name from information_schema.tables where table_schema=? order by table_name")
if perr != nil {
err = perr
return
}
defer stm.Close()
q, qerr := stm.Query(table)
if qerr != nil {
err = qerr
return
}
defer q.Close()
for q.Next() {
var name string
if err := q.Scan(&name); err != nil {
log.Fatal(err)
}
ts = append(ts, name)
}
return
}
// TriggerDiff 对比触发器的不同
func TriggerDiff(db1, db2 *sql.DB, schema1, schema2 string) bool {
triggerName1, err := getTriggerName(db1, schema1)
if err != nil {
dLog.Fatalln(err.Error())
}
triggerName2, err := getTriggerName(db2, schema2)
if err != nil {
dLog.Fatalln(err.Error())
}
if !isEqual(triggerName1, triggerName2) {
dt := diffName(triggerName1, triggerName2)
dLog.Printf("两个数据库不同的触发器,共有%d个,分别是:%s", len(dt), dt)
return false
}
// dLog.Printf("两个数据库触发器相同")
return true
}
func getTriggerName(s *sql.DB, schema string) (ts []string, err error) {
stm, perr := s.Prepare("select TRIGGER_NAME from information_schema.triggers where TRIGGER_SCHEMA=? order by TRIGGER_NAME")
if perr != nil {
err = perr
return
}
defer stm.Close()
q, qerr := stm.Query(schema)
if qerr != nil {
err = qerr
return
}
defer q.Close()
for q.Next() {
var name string
if err := q.Scan(&name); err != nil {
log.Fatal(err)
}
ts = append(ts, name)
}
return
}
// FunctionDiff 对比函数的不同
func FunctionDiff(db1, db2 *sql.DB, schema1, schema2 string) bool {
functionName1, err := getFunctionName(db1, schema1)
if err != nil {
dLog.Fatalln(err.Error())
}
functionName2, err := getFunctionName(db2, schema2)
if err != nil {
dLog.Fatalln(err.Error())
}
dLog.Println(functionName1)
dLog.Println(functionName2)
if !isEqual(functionName1, functionName2) {
dt := diffName(functionName1, functionName2)
dLog.Printf("两个数据库不同的函数,共有%d个,分别是:%s", len(dt), dt)
return false
}
// dLog.Printf("两个数据库函数相同")
return true
}
func getFunctionName(s *sql.DB, schema string) (ts []string, err error) {
stm, perr := s.Prepare("select ROUTINE_NAME from information_schema.routines where ROUTINE_SCHEMA=? and ROUTINE_TYPE='FUNCTION' order by ROUTINE_NAME")
if perr != nil {
err = perr
return
}
defer stm.Close()
q, qerr := stm.Query(schema)
if qerr != nil {
err = qerr
return
}
defer q.Close()
for q.Next() {
var name string
if err := q.Scan(&name); err != nil {
log.Fatal(err)
}
ts = append(ts, name)
}
return
}
func genAlterSql(t string, col column) string {
var after string
if col.After != "" {
after = fmt.Sprintf(" AFTER `%s`", col.After)
}
var isNull string
if col.IsNullable == "YES" {
isNull = " NULL"
} else {
isNull = " NOT NULL"
}
var defaultValue string
if col.Default == nil {
defaultValue = " DEFAULT NULL"
} else if col.Default != "" {
defaultValue = fmt.Sprintf(" DEFAULT '%s'", col.Default)
}
return fmt.Sprintf("ALTER TABLE `%s` ADD COLUMN `%s` %s%s%s%s;", t, col.Name, col.Type, isNull, defaultValue, after)
}
// ColumnDiff 对比函数的不同
func ColumnDiff(db1, db2 *sql.DB, schema1, schema2 string, table []string) {
for _, t := range table {
columnName1, err := getColumnName(db1, schema1, t)
if err != nil {
dLog.Fatalln(err.Error())
}
columnName2, err := getColumnName(db2, schema2, t)
if err != nil {
dLog.Fatalln(err.Error())
}
if !columnIsEqual(columnName1, columnName2) {
// dt := diffName(columnName1, columnName2)
// dLog.Printf("两个数据库%s表,有不同的列,共有%d个,分别是:%s", t, len(dt), dt)
col1, col2 := columnDiff(columnName1, columnName2)
dLog.Printf("%s数据库%s表,列不相同:%d", schema1, t, len(col1))
for _, col := range col1 {
dLog.Printf(genAlterSql(t, col))
}
dLog.Printf("%s数据库%s表,列不相同:%d", schema2, t, len(col2))
for _, col := range col2 {
dLog.Printf(genAlterSql(t, col))
}
} else {
//dLog.Printf("两个数据库%s表,列相同", t)
}
}
}
func getColumnName(s *sql.DB, schema, table string) (ts []column, err error) {
stm, perr := s.Prepare("select COLUMN_NAME,column_type,column_default,is_nullable from information_schema.columns where TABLE_SCHEMA=? and TABLE_NAME=? order by ordinal_position asc")
if perr != nil {
err = perr
return
}
defer stm.Close()
q, qerr := stm.Query(schema, table)
if qerr != nil {
err = qerr
return
}
defer q.Close()
ts = make([]column, 0)
var after string
for q.Next() {
var column_name string
var column_type string
var column_default interface{}
var is_nullable string
if err := q.Scan(&column_name, &column_type, &column_default, &is_nullable); err != nil {
log.Fatal(err)
}
col := column{}
col.Name = column_name
col.Type = column_type
col.IsNullable = is_nullable
col.Default = column_default
if after == "" {
col.After = ""
} else {
col.After = after
}
after = col.Name
ts = append(ts, col)
}
return
}
// IndexDiff 对比函数的不同
func IndexDiff(db1, db2 *sql.DB, schema1, schema2 string, table []string) {
for _, t := range table {
indexName1, err := getIndexName(db1, schema1, t)
if err != nil {
dLog.Fatalln(err.Error())
}
indexName2, err := getIndexName(db2, schema2, t)
if err != nil {
dLog.Fatalln(err.Error())
}
if !isEqual(indexName1, indexName2) {
dt := diffName(indexName1, indexName2)
dLog.Printf("两个数据库%s表,有不同的索引,共有%d个,分别是:%s", t, len(dt), dt)
} else {
// dLog.Printf("两个数据库%s表,索引相同", t)
}
}
}
func getIndexName(s *sql.DB, schema, table string) (ts []string, err error) {
stm, perr := s.Prepare("select INDEX_NAME from information_schema.STATISTICS where TABLE_SCHEMA=? and TABLE_NAME=? order by INDEX_NAME")
if perr != nil {
err = perr
return
}
defer stm.Close()
q, qerr := stm.Query(schema, table)
if qerr != nil {
err = qerr
return
}
defer q.Close()
for q.Next() {
var name string
if err := q.Scan(&name); err != nil {
log.Fatal(err)
}
ts = append(ts, name)
}
return
}
func columnIsEqual(x, y []column) bool {
if len(x) != len(y) {
return false
}
for _, col1 := range x {
isExist := false
for _, col2 := range y {
if col2.Name == col1.Name {
isExist = true
break
}
}
if isExist == false {
return false
}
}
return true
}
func columnDiff(x, y []column) (x1, x2 []column) {
//生成语句
//先判断x,y没有的语句
for _, col1 := range x {
isExist := false
for _, col2 := range y {
if col1.Name == col2.Name {
isExist = true
break
}
}
if isExist == false {
//生成语句
x2 = append(x2, col1)
}
}
for _, col1 := range y {
isExist := false
for _, col2 := range x {
if col1.Name == col2.Name {
isExist = true
break
}
}
if isExist == false {
//生成语句
x1 = append(x1, col1)
}
}
return
}
func isEqual(x, y []string) bool {
if len(x) != len(y) {
return false
}
for i := range x {
if x[i] != y[i] {
return false
}
}
return true
}
func diffName(a, b []string) []string {
c := a[:0]
m := make(map[string]int)
for _, s := range a {
m[s] = 1
}
// 交集
n := make(map[string]int)
for _, s := range b {
if _, ok := m[s]; ok {
n[s] = 1
}
}
// 与a不同
for _, s := range a {
if _, ok := n[s]; !ok {
c = append(c, s)
}
}
// 与b不同
for _, s := range b {
if _, ok := n[s]; !ok {
c = append(c, s)
}
}
return c
}