/
dbtogo.go
317 lines (271 loc) · 7.42 KB
/
dbtogo.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
package main
import (
"bytes"
"database/sql"
"fmt"
"go/parser"
"go/printer"
"go/token"
"io"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"bitbucket.org/pkg/inflect"
"github.com/codegangsta/cli"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/jackc/pgx/stdlib"
_ "github.com/mattn/go-sqlite3"
)
// var (
// BUILTINS = []string{"break", "default", "func", "interface", "select",
// "case", " defer", "go", "map", "struct",
// "chan", " else", " goto", " package", "switch",
// "const", "fallthrough", "if", "range", "type",
// "continue", "for", "import", "return", "var"}
// )
var (
default_template = `// GENERATED BY dbtogo (github.com/kdar/dbtogo); DO NOT EDIT
// ---args: {{join .SafeArgs " "}}
package {{.Package}}
{{define "columns"}}{{$len:=len .}}{{range $i, $v := .}}{{$v.Name|capitalize}}{{if lt $i (sub $len 1)}},{{end}}{{end}}{{end}}
{{define "values"}}{{$len:=len .}}{{range $i, $v := .}}:{{$v.Name|capitalize}}{{if lt $i (sub $len 1)}},{{end}}{{end}}{{end}}
import "database/sql"
var InsertStmts = map[string]string{
{{range $_, $table := .Tables}} "{{$table.Name}}": "INSERT INTO {{$table.Name}} ({{template "columns" $table.Fields}}) VALUES ({{template "values" $table.Fields}})",
{{end}}}
{{range $_, $table := .Tables}}
type {{$table.Name}} struct {
{{range $_, $field := $table.Fields}} {{$field.Name|capitalize}} {{$field|typenull}}
{{end}}}
{{end}}`
)
// capitalize the first letter of the string
func capitalize(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
// remove all underscores from the string
func nounderscore(s string) string {
return strings.Replace(s, "_", "", -1)
}
// "go fmt"'s the code
func format(w io.Writer, code []byte) error {
fset := token.NewFileSet()
ast, err := parser.ParseFile(fset, "", code, parser.ParseComments)
if err != nil {
return err
}
cfg := &printer.Config{Tabwidth: 8}
err = cfg.Fprint(w, fset, ast)
if err != nil {
return err
}
return nil
}
func render(writer io.Writer, md *Metadata, file string) error {
funcMap := template.FuncMap{
"tolower": strings.ToLower,
"join": strings.Join,
"capitalize": capitalize,
"nounderscore": nounderscore,
"underscore": inflect.Underscore,
"camelize": inflect.Camelize,
"camelizedownfirst": inflect.CamelizeDownFirst,
"pluralize": inflect.Pluralize,
"singularize": inflect.Singularize,
"tableize": inflect.Tableize,
"typeify": inflect.Typeify,
"addacronym": func(a string) string { inflect.AddAcronym(a); return "" },
"addhuman": func(a, b string) string { inflect.AddHuman(a, b); return "" },
"addirregular": func(a, b string) string { inflect.AddIrregular(a, b); return "" },
"addplural": func(a, b string) string { inflect.AddPlural(a, b); return "" },
"addsingular": func(a, b string) string { inflect.AddSingular(a, b); return "" },
"adduncountable": func(a string) string { inflect.AddUncountable(a); return "" },
"add": func(x, y int) int {
return x + y
},
"sub": func(x, y int) int {
return x - y
},
"typenull": func(f Field) string {
t := f.Type.String()
if !strings.HasPrefix(t, "[]") {
switch t {
case "bool", "float64", "int64", "string":
t = "sql.Null" + capitalize(t)
default:
t = "*" + t
}
}
return t
},
"typepointer": func(f Field) string {
t := f.Type.String()
if !strings.HasPrefix(t, "[]") {
t = "*" + t
}
return t
},
}
tplName := filepath.Base(file)
tpl := template.New("output").Funcs(funcMap)
var t *template.Template
var err error
if file == "" {
tplName = "output"
t, err = tpl.Parse(default_template)
} else {
t, err = tpl.ParseFiles(file)
}
if err != nil {
return err
}
return t.ExecuteTemplate(writer, tplName, md)
}
func cliDbAction(cmd string) func(c *cli.Context) {
return func(c *cli.Context) {
var err error
dsn := os.Getenv("DBTOGO_DSN")
if c.Args().Present() {
dsn = c.Args().Get(0)
}
if dsn == "" {
log.Fatal("Missing DSN on the command line or the DBTOGO_DSN env")
}
db, err := sql.Open(cmd, dsn)
if err != nil {
log.Fatal(err)
}
var md *Metadata
switch cmd {
case "mssql":
md, err = mssql(db)
case "mysql":
md, err = mysql(db)
case "pgx":
md, err = postgresql(db)
case "sqlite3":
md, err = sqlite3(db)
}
if err != nil {
log.Fatal(err)
}
md.Package = "model"
for i, v := range os.Args {
if i != 0 {
v = strconv.Quote(v)
}
md.Args = append(md.Args, v)
}
if c.Args().Present() {
md.SafeArgs = md.Args[:len(md.Args)-1]
}
file := os.Stdout
switch c.GlobalString("o") {
case "-", "":
default:
file, err = os.Create(c.GlobalString("o"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
}
buffer := &bytes.Buffer{}
render(buffer, md, c.GlobalString("tpl"))
if !c.GlobalBool("nofmt") {
err = format(file, buffer.Bytes())
if err != nil {
log.Fatal(err)
}
} else {
io.Copy(file, buffer)
}
}
}
func newTplAction(c *cli.Context) {
fmt.Println(default_template)
}
func main() {
cli.AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} [global options] command [command options] [arguments...]
COMMANDS:
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
{{end}}
GLOBAL OPTIONS:
{{range .Flags}}{{.}}
{{end}}
DATABASES:
mssql http://github.com/denisenkom/go-mssqldb
mysql http://github.com/go-sql-driver/mysql
postgresql http://github.com/jackc/pgx/stdlib
sqlite3 http://github.com/mattn/go-sqlite3
`
cli.CommandHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
dbtogo {{.Name}} [command options] [DSN]
If you want to omit the DSN on the command line,
put your DSN in the DBTOGO_DSN environment variable.
OPTIONS:
{{range .Flags}}{{.}}
{{end}}
EXAMPLE:
dbtogo {{.Name}} {{if eq .Name "mysql"}}mysqluser:pass@tcp(host:port)/db{{end}}{{if eq .Name "postgresql"}}postgres://user:pass@localhost:5432/db?sslmode=disable{{end}}{{if eq .Name "sqlite3"}}./foo.db{{end}}
`
app := cli.NewApp()
app.Name = "dbtogo"
app.Usage = "turns database tables into go code"
app.Version = "1.0.0"
app.Flags = []cli.Flag{
cli.StringFlag{Name: "tpl", Value: "", Usage: "template to use in rendering code"},
cli.BoolFlag{Name: "nofmt", Usage: "don't use go fmt to format code"},
cli.StringFlag{Name: "o", Value: "-", Usage: "where to output code. defaults to stdout"},
}
// app.Action = func(c *cli.Context) {
// println("Hello friend!")
// }
app.Commands = []cli.Command{
{
Name: "newtpl",
Usage: "outputs a new template you can use",
Description: "",
Action: newTplAction,
},
{
Name: "mysql",
Usage: "connects to a mysql database",
Description: "",
Action: cliDbAction("mysql"),
},
{
Name: "sqlite3",
Usage: "connects to a sqlite3 database",
Description: "",
Action: cliDbAction("sqlite3"),
},
{
Name: "mssql",
Usage: "connects to a Microsoft SQL database",
Description: "",
Action: cliDbAction("mssql"),
},
{
Name: "postgresql",
Usage: "connects to a postgresql database",
Description: "",
Action: cliDbAction("pgx"),
},
}
app.Run(os.Args)
}