forked from bradrydzewski/togo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction_sql.go
78 lines (67 loc) · 1.31 KB
/
action_sql.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
package main
import (
"os"
"path/filepath"
"github.com/urfave/cli"
"github.com/bradrydzewski/togo/parser"
"github.com/bradrydzewski/togo/template"
)
type sqlParams struct {
Package string
Dialect string
Statements []*parser.Statement
}
var sqlCommand = cli.Command{
Name: "sql",
Usage: "embed sql statements",
Action: sqlAction,
Flags: []cli.Flag{
cli.StringFlag{
Name: "package",
Value: "sql",
},
cli.StringFlag{
Name: "dialect",
Value: "sqlite3",
},
cli.StringFlag{
Name: "input",
Value: "files/*.sql",
},
cli.StringFlag{
Name: "output",
Value: "sql_gen.go",
},
},
}
func sqlAction(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 := sqlParams{
Package: c.String("package"),
Dialect: c.String("dialect"),
}
parse := parser.New()
for _, match := range matches {
statements, perr := parse.ParseFile(match)
if perr != nil {
return perr
}
params.Statements = append(params.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, "sql.tmpl", params)
}