This repository has been archived by the owner on Nov 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathaction_ddl.go
104 lines (91 loc) · 1.74 KB
/
action_ddl.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
package main
import (
"os"
"path/filepath"
"github.com/urfave/cli"
"github.com/bradrydzewski/togo/parser"
"github.com/bradrydzewski/togo/template"
)
type migration struct {
Name string
Statements []*parser.Statement
}
type logger struct {
Enabled bool
Package string
}
type migrationParams struct {
Package string
Dialect string
Migrations []migration
Logger logger
}
var ddlCommand = cli.Command{
Name: "ddl",
Usage: "embed ddl statements",
Action: ddlAction,
Flags: []cli.Flag{
cli.StringFlag{
Name: "package",
Value: "ddl",
},
cli.StringFlag{
Name: "dialect",
Value: "sqlite3",
},
cli.StringFlag{
Name: "input",
Value: "files/*.sql",
},
cli.StringFlag{
Name: "output",
Value: "ddl_gen.go",
},
cli.BoolFlag{
Name: "log",
},
cli.StringFlag{
Name: "logger",
Value: "log", // log, logrus
},
},
}
func ddlAction(c *cli.Context) error {
pattern := c.Args().First()
if pattern == "" {
pattern = c.String("input")
}
matches, err := filepath.Glob(pattern)
if err != nil {
return err
}
params := migrationParams{
Package: c.String("package"),
Dialect: c.String("dialect"),
Logger: logger{
Enabled: c.Bool("log"),
Package: c.String("logger"),
},
}
parse := parser.New()
for _, match := range matches {
statements, perr := parse.ParseFile(match)
if perr != nil {
return perr
}
_, filename := filepath.Split(match)
params.Migrations = append(params.Migrations, migration{
Name: filename,
Statements: statements,
})
}
wr := os.Stdout
if output := c.String("output"); output != "" {
wr, err = os.Create(output)
if err != nil {
return err
}
defer wr.Close()
}
return template.Execute(wr, "ddl.tmpl", params)
}