-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
545 lines (511 loc) · 11.4 KB
/
main.go
File metadata and controls
545 lines (511 loc) · 11.4 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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package main
import (
"context"
"database/sql"
"encoding/json"
"flag"
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/manifoldco/promptui"
"golang.org/x/crypto/ssh"
"io/ioutil"
"net"
"os"
"strconv"
)
// ConfigStruct struct
type ConfigStruct struct {
Source ConfStruct
Target ConfStruct
}
// ConfStruct struct
type ConfStruct struct {
Mode string
Host string
Port interface{}
User string
Password string
PrivateKey string
DBHost string
DBPort interface{}
DBUser string
DBPassword string
Database string
Charset string
}
// Client struct
type Client struct {
client *ssh.Client
}
// ViaSSHDialer struct
type ViaSSHDialer struct {
client *ssh.Client
_ *context.Context
}
// ColumnStruct struct
type ColumnStruct struct {
Field string
Type string
Collation interface{}
Null string
Key string
Default interface{}
Extra string
Privileges string
Comment string
}
// Dial ssh dialer
func (v *ViaSSHDialer) Dial(context context.Context, addr string) (net.Conn, error) {
return v.client.Dial("tcp", addr)
}
var (
// Config struct
Config ConfigStruct
// Source source db
Source *sql.DB
// Target target db
Target *sql.DB
sourceTables = map[string]int{}
targetTables = map[string]int{}
sourceColumnTables = map[string]map[string]ColumnStruct{}
targetColumnTables = map[string]map[string]ColumnStruct{}
newColumnTables = map[string]map[string]ColumnStruct{}
)
func usage() {
fmt.Fprintf(os.Stderr,
`MySQL Diff
Usage: gmd <configfile>
Options:
`)
flag.PrintDefaults()
}
func main() {
h := false
flag.BoolVar(&h, "h", false, "this help")
flag.Parse()
flag.Usage = usage
if len(flag.Args()) == 0 {
h = true
}
if h {
flag.Usage()
return
}
file := flag.Args()[0]
decode(file)
}
func decode(file string) {
content, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println("config file does not exist")
return
}
json.Unmarshal(content, &Config)
run()
}
func formatPort(port interface{}) string {
if p, ok := port.(string); ok {
return p
}
if p, ok := port.(float64); ok {
return strconv.FormatFloat(p, 'f', 0, 64)
}
return ""
}
func run() {
var err error
Source, err = connect(true)
if err != nil {
fmt.Println("Source connect error:", err)
return
}
Target, err = connect(false)
if err != nil {
fmt.Println("Target connect error:", err)
return
}
var table string
rows, err := Source.Query("SHOW TABLES")
defer rows.Close()
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
rows.Scan(&table)
sourceTables[table] = 1
}
// target
rows, err = Target.Query("SHOW TABLES")
defer rows.Close()
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
rows.Scan(&table)
targetTables[table] = 1
}
// new table in source
for k := range sourceTables {
if targetTables[k] != 1 {
sourceTables[k] = -1
}
}
// redundant table in target
for k := range targetTables {
if sourceTables[k] == 0 {
renameOrDelete(k)
}
}
// diff
for k, v := range sourceTables {
if v == -1 {
create(k)
} else {
diff(k)
}
}
fmt.Println("Done")
}
func renameOrDelete(table string) {
lable := fmt.Sprintf("The table `%s` is existing on the target database but does not exist in the source database. Please select your operation", table)
prompt := promptui.Select{
Label: lable,
Items: []string{
"Skip",
"Delete the table `" + table + "`",
"Rename the table `" + table + "`",
},
}
index, _, _ := prompt.Run()
if index == 1 {
deleteTable(table)
} else if index == 2 {
renameTable(table)
}
}
func deleteTable(table string) {
lable := fmt.Sprintf("The table `%s` cannot be recovered after deletion, please confirm:", table)
prompt := promptui.Select{
Label: lable,
Items: []string{
"Go back to reselect",
"Delete the table `" + table + "`",
},
}
index, _, _ := prompt.Run()
if index == 1 {
deleteTableByName(table)
} else {
renameOrDelete(table)
}
}
func deleteTableByName(table string) {
_, err := Target.Exec("DROP TABLE `" + table + "`")
if err != nil {
fmt.Println(err)
renameOrDelete(table)
} else {
fmt.Printf("The table `%s` is deleted\n", table)
}
}
func renameTable(table string) {
prompt := promptui.Select{
Label: "Please select your operation",
Items: []string{
"Go back to reselect",
"Select a table name from the source database",
"Input a new table name",
},
}
index, _, _ := prompt.Run()
if index == 1 {
item := []string{
"Go back to reselect",
}
for k, v := range sourceTables {
if v == -1 {
item = append(item, k)
}
}
prompt := promptui.Select{
Label: "Please select a table name or back to reselect",
Items: item,
}
index, rename, _ := prompt.Run()
if index == 0 {
renameTable(table)
} else {
renameTableByName(table, rename, false)
}
} else if index == 2 {
prompt := promptui.Prompt{
Label: "Please input a new table name",
}
result, err := prompt.Run()
if err != nil {
fmt.Println(err)
renameTable(table)
} else {
renameTableByName(table, result, true)
}
} else {
renameOrDelete(table)
}
}
func renameTableByName(table, rename string, newname bool) {
sql := fmt.Sprintf("RENAME TABLE `%s` TO `%s`", table, rename)
_, err := Target.Exec(sql)
if err != nil {
fmt.Println(err)
renameTable(table)
return
}
if !newname {
sourceTables[rename] = 1
}
}
func diff(table string) {
fmt.Printf("Diff table `%s`...\n", table)
rows, err := Target.Query("SHOW FULL COLUMNS FROM `" + table + "`")
defer rows.Close()
if err != nil {
fmt.Println(err)
return
}
targetColumnTables[table] = map[string]ColumnStruct{}
for rows.Next() {
var column ColumnStruct
rows.Scan(
&column.Field,
&column.Type,
&column.Collation,
&column.Null,
&column.Key,
&column.Default,
&column.Extra,
&column.Privileges,
&column.Comment,
)
targetColumnTables[table][column.Field] = column
}
rows, err = Source.Query("SHOW FULL COLUMNS FROM `" + table + "`")
defer rows.Close()
if err != nil {
fmt.Println(err)
return
}
sourceColumnTables[table] = map[string]ColumnStruct{}
newColumnTables[table] = map[string]ColumnStruct{}
for rows.Next() {
var column ColumnStruct
rows.Scan(
&column.Field,
&column.Type,
&column.Collation,
&column.Null,
&column.Key,
&column.Default,
&column.Extra,
&column.Privileges,
&column.Comment,
)
sourceColumnTables[table][column.Field] = column
if targetColumnTables[table][column.Field].Field == "" {
newColumnTables[table][column.Field] = column
}
}
for k := range targetColumnTables[table] {
if sourceColumnTables[table][k].Field == "" {
renameOrDeleteColumn(k, table)
}
}
}
func renameOrDeleteColumn(column, table string) {
lable := fmt.Sprintf("The field `%s` is existing on the target table `%s` but does not exist in the source database. Please select your operation", column, table)
prompt := promptui.Select{
Label: lable,
Items: []string{
"Skip",
"Delete the field `" + column + "`",
"Rename the field `" + column + "`",
},
}
index, _, _ := prompt.Run()
if index == 1 {
deleteColumn(column, table)
} else if index == 2 {
renameColumn(column, table)
}
}
func deleteColumn(column, table string) {
lable := fmt.Sprintf("The field `%s` cannot be recovered after deletion, please confirm:", column)
prompt := promptui.Select{
Label: lable,
Items: []string{
"Go back to reselect",
"Delete the field `" + column + "`",
},
}
index, _, _ := prompt.Run()
if index == 1 {
deleteColumnFromTable(column, table)
} else {
renameOrDelete(table)
}
}
func renameColumn(column, table string) {
prompt := promptui.Select{
Label: "Please select your operation",
Items: []string{
"Go back to reselect",
"Select a field name from the source table `" + table + "`",
"Input a new field name",
},
}
index, _, _ := prompt.Run()
if index == 1 {
item := []string{
"Go back to reselect",
}
for k := range newColumnTables[table] {
item = append(item, k)
}
prompt := promptui.Select{
Label: "Please select a field name or back to reselect",
Items: item,
}
index, rename, _ := prompt.Run()
if index == 0 {
renameColumn(column, table)
} else {
renameColumnFromTable(column, rename, table, false)
}
} else if index == 2 {
prompt := promptui.Prompt{
Label: "Please input a new field name",
}
result, err := prompt.Run()
if err != nil {
fmt.Println(err)
renameColumn(column, table)
} else {
renameColumnFromTable(column, result, table, true)
}
} else {
renameOrDeleteColumn(column, table)
}
}
func deleteColumnFromTable(column, table string) {
sql := fmt.Sprintf("ALTER TABLE `%s` DROP `%s`", table, column)
_, err := Target.Exec(sql)
if err != nil {
fmt.Println(err)
renameOrDeleteColumn(column, table)
} else {
fmt.Printf("The field `%s` is deleted\n", column)
}
}
func renameColumnFromTable(column, rename, table string, newname bool) {
Type := targetColumnTables[table][column].Type
if !newname {
Type = sourceColumnTables[table][rename].Type
}
sql := fmt.Sprintf("ALTER TABLE `%s` CHANGE `%s` `%s` %s", table, column, rename, Type)
_, err := Target.Exec(sql)
if err != nil {
fmt.Println(err)
renameColumn(column, table)
return
}
if !newname {
delete(newColumnTables[table], rename)
}
}
func create(table string) {
fmt.Printf("Table `%s` does not exist, creating...\n", table)
var name, sql string
err := Source.QueryRow("SHOW CREATE TABLE `"+table+"`").Scan(&name, &sql)
if err != nil {
fmt.Printf("Table `%s` export failed\n", table)
return
}
_, err = Target.Exec(sql)
if err != nil {
fmt.Printf("Table `%s` create failed: %s\n", table, err)
return
}
fmt.Printf("Table `%s` create succeed\n", table)
}
func connect(source bool) (*sql.DB, error) {
conf := Config.Target
if source {
conf = Config.Source
}
port := formatPort(conf.Port)
dialer := conf.Mode
if conf.Mode == "ssh" {
dialer = "mysql+tcp"
var client *ssh.Client
var err error
if conf.PrivateKey != "" {
client, err = dialWithPrivateKey(conf.Host+":"+port, conf.User, conf.PrivateKey)
} else {
client, err = dialWithPassword(conf.Host+":"+port, conf.User, conf.Password)
}
if err != nil {
return nil, err
}
mysql.RegisterDialContext(dialer, (&ViaSSHDialer{client, nil}).Dial)
}
dbPort := formatPort(conf.DBPort)
conStr := conf.DBUser + ":" + conf.DBPassword + "@" + dialer + "(" + conf.DBHost + ":" + dbPort + ")/" + conf.Database + "?charset=" + conf.Charset
db, err := sql.Open("mysql", conStr)
if err != nil {
db.Close()
return nil, err
}
err = db.Ping()
if err != nil {
db.Close()
return nil, err
}
return db, nil
}
func dialWithPassword(addr, user, passwd string) (*ssh.Client, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(passwd),
},
HostKeyCallback: ssh.HostKeyCallback(
func(hostname string, target net.Addr, key ssh.PublicKey) error {
return nil
},
),
}
return ssh.Dial("tcp", addr, config)
}
func dialWithPrivateKey(addr, user, keyfile string) (*ssh.Client, error) {
key, err := ioutil.ReadFile(keyfile)
if err != nil {
return nil, err
}
signature, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signature),
},
HostKeyCallback: ssh.HostKeyCallback(
func(hostname string, target net.Addr, key ssh.PublicKey) error {
return nil
},
),
}
return ssh.Dial("tcp", addr, config)
}