forked from mijia/modelq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (79 loc) · 2.54 KB
/
main.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
package main
import (
"bytes"
"flag"
"fmt"
"log"
"os/exec"
"runtime"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
"github.com/mijia/modelq/drivers"
"github.com/mijia/modelq/gmq"
)
func main() {
var targetDb, tableNames, packageName string
var tmplName string
var driver, schemaName string
var touchTimestamp bool
var pCount int
flag.StringVar(&targetDb, "db", "", "Target database source string: e.g. root@tcp(127.0.0.1:3306)/test?charset=utf-8")
flag.StringVar(&tableNames, "tables", "", "You may specify which tables the models need to be created, e.g. \"user,article,blog\"")
flag.StringVar(&packageName, "pkg", "", "Go source code package for generated models")
flag.StringVar(&driver, "driver", "mysql", "Current supported drivers include mysql, postgres")
flag.StringVar(&schemaName, "schema", "", "Schema for postgresql, database name for mysql")
flag.BoolVar(&touchTimestamp, "dont-touch-timestamp", false, "Should touch the datetime fields with default value or on update")
flag.StringVar(&tmplName, "template", "", "Passing the template to generate code, or use the default one")
flag.IntVar(&pCount, "p", 4, "Parallell running for code generator")
flag.BoolVar(&gmq.Debug, "debug", false, "Debug on/off")
flag.Parse()
runtime.GOMAXPROCS(pCount)
if targetDb == "" {
fmt.Println("Please provide the target database source.")
fmt.Println("Usage:")
flag.PrintDefaults()
return
}
if packageName == "" {
printUsages("Please provide the go source code package name for generated models.")
return
}
if driver != "mysql" && driver != "postgres" {
printUsages("Current supported drivers include mysql, postgres.")
return
}
if schemaName == "" {
printUsages("Please provide the schema name.")
return
}
dbSchema, err := drivers.LoadDatabaseSchema(driver, targetDb, schemaName, tableNames)
if err != nil {
log.Println("Cannot load table schemas from database.")
log.Fatal(err)
}
codeConfig := &CodeConfig{
packageName: packageName,
touchTimestamp: touchTimestamp,
template: tmplName,
}
codeConfig.MustCompileTemplate()
generateModels(schemaName, dbSchema, *codeConfig)
formatCodes(packageName)
}
func formatCodes(pkg string) {
log.Println("Running gofmt *.go")
var out bytes.Buffer
cmd := exec.Command("gofmt", "-w", pkg)
cmd.Stderr = &out
if err := cmd.Run(); err != nil {
log.Println(out.String())
log.Fatalf("Fail to run gofmt package, %s", err)
}
}
func printUsages(message ...interface{}) {
for _, x := range message {
fmt.Println(x)
}
fmt.Println("\nUsage:")
flag.PrintDefaults()
}