This repository has been archived by the owner on Nov 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqldef.go
94 lines (80 loc) · 1.77 KB
/
sqldef.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
package sqldef
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/k0kubun/sqldef/adapter"
"github.com/sqldef/clickhousedef/schema"
)
type Options struct {
SqlFile string
DryRun bool
Export bool
SkipDrop bool
}
// Main function shared by `mysqldef` and `psqldef`
func Run(generatorMode schema.GeneratorMode, db adapter.Database, options *Options) {
currentDDLs, err := adapter.DumpDDLs(db)
if err != nil {
log.Fatal(fmt.Sprintf("Error on DumpDDLs: %s", err))
}
if options.Export {
if currentDDLs == "" {
fmt.Printf("-- No table exists --\n")
} else {
fmt.Printf("%s;\n", currentDDLs)
}
return
}
sql, err := readFile(options.SqlFile)
if err != nil {
log.Fatalf("Failed to read '%s': %s", options.SqlFile, err)
}
desiredDDLs := string(sql)
ddls, err := schema.GenerateIdempotentDDLs(generatorMode, desiredDDLs, currentDDLs)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if len(ddls) == 0 {
fmt.Println("-- Nothing is modified --")
return
}
if options.DryRun {
showDDLs(ddls, options.SkipDrop)
return
}
err = adapter.RunDDLs(db, ddls, options.SkipDrop)
if err != nil {
log.Fatal(err)
}
}
func readFile(filepath string) (string, error) {
var err error
var buf []byte
if filepath == "-" {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) != 0 {
return "", fmt.Errorf("stdin is not piped")
}
buf, err = ioutil.ReadAll(os.Stdin)
} else {
buf, err = ioutil.ReadFile(filepath)
}
if err != nil {
return "", err
}
return string(buf), nil
}
func showDDLs(ddls []string, skipDrop bool) {
fmt.Println("-- dry run --")
for _, ddl := range ddls {
if skipDrop && strings.Contains(ddl, "DROP") {
fmt.Printf("-- Skipped: %s;\n", ddl)
continue
}
fmt.Printf("%s;\n", ddl)
}
}