-
Notifications
You must be signed in to change notification settings - Fork 249
/
db.go
97 lines (87 loc) · 1.96 KB
/
db.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
package codegen
import (
"bufio"
"github.com/sirupsen/logrus"
"github.com/unionj-cloud/go-doudou/version"
"os"
"path/filepath"
"strings"
"text/template"
)
var dbTmpl = `/**
* Generated by go-doudou {{.Version}}.
* You can edit it as your need.
*/
package db
import (
"{{.ConfigPackage}}"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/iancoleman/strcase"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
func NewDb(conf config.DbConfig) (*sqlx.DB, error) {
conn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s",
conf.User,
conf.Passwd,
conf.Host,
conf.Port,
conf.Schema,
conf.Charset)
conn += "&loc=Asia%2FShanghai&parseTime=True"
db, err := sqlx.Connect(conf.Driver, conn)
if err != nil {
return nil, errors.Wrap(err, "database connection failed")
}
db.MapperFunc(strcase.ToSnake)
return db, nil
}
`
var MkdirAll = os.MkdirAll
var Open = os.Open
var Create = os.Create
var Stat = os.Stat
// GenDb generates db connection code
func GenDb(dir string) {
var (
err error
dbfile string
f *os.File
tpl *template.Template
dbDir string
modfile string
modName string
firstLine string
)
dbDir = filepath.Join(dir, "db")
if err = MkdirAll(dbDir, os.ModePerm); err != nil {
panic(err)
}
dbfile = filepath.Join(dbDir, "db.go")
if _, err = Stat(dbfile); os.IsNotExist(err) {
modfile = filepath.Join(dir, "go.mod")
if f, err = Open(modfile); err != nil {
panic(err)
}
reader := bufio.NewReader(f)
firstLine, _ = reader.ReadString('\n')
modName = strings.TrimSpace(strings.TrimPrefix(firstLine, "module"))
if f, err = Create(dbfile); err != nil {
panic(err)
}
defer f.Close()
if tpl, err = template.New("db.go.tmpl").Parse(dbTmpl); err != nil {
panic(err)
}
_ = tpl.Execute(f, struct {
ConfigPackage string
Version string
}{
ConfigPackage: modName + "/config",
Version: version.Release,
})
} else {
logrus.Warnf("file %s already exists", dbfile)
}
}