-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconvert.go
280 lines (231 loc) · 6.68 KB
/
convert.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
/*
* Copyright (c) 2019 Mars Lee. All rights reserved.
*/
package genModels
import (
"fmt"
"log"
"os"
"os/exec"
"strings"
)
type SqlDriver interface {
SetDsn(dsn string, options ...interface{})
GetDsn() string
Connect() error
ReadTablesColumns(table string) []Column
GetTables() []string
GetDriverType() string
}
type Convert struct {
ModelPath string // save path
Style string // tab key save like gorm ,orm ,bee orm......
PackageName string // go package name
TablePrefix map[string]string //if table exists prefix
TableColumn map[string][]Column //key is table , value is Column list
IgnoreTables []string // ignore tables
Tables []string // all tables
Driver SqlDriver // impl SqlDriver instance
initOrm bool
}
//get real gen tables as []string
func (convert *Convert) getGenTables() []string {
tables := make([]string, 0)
convert.Tables = convert.Driver.GetTables()
for _, table := range convert.Tables {
isIgnore := false
for _, ignore := range convert.IgnoreTables {
if table == ignore {
isIgnore = true
break
}
}
if !isIgnore {
tables = append(tables, table)
}
}
return tables
}
//set table prefix
//if exists
//replace prefix to empty string
func (convert *Convert) SetTablePrefix(table, prefix string) {
convert.TablePrefix[table] = prefix
}
// set model save path
func (convert *Convert) SetModelPath(path string) {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
panic(fmt.Sprintf("path not exists with error:%v", err))
}
log.Println(fmt.Sprintf("path error:%v", err))
}
convert.ModelPath = path
}
// set model save path
func (convert *Convert) SetIgnoreTables(table ...string) {
convert.IgnoreTables = append(convert.IgnoreTables, table...)
}
// set model save path
func (convert *Convert) SetPackageName(name string) {
convert.PackageName = name
}
//run
//1. connect
//2. getTable
//3. getColumns
//4. build
//5. write file
func (convert *Convert) Run() {
err := convert.Driver.Connect()
if err != nil {
panic(err)
}
for _, tableRealName := range convert.getGenTables() {
prefix, ok := convert.TablePrefix[tableRealName]
if ok {
tableRealName = tableRealName[len(prefix):]
}
tableName := tableRealName
if len(tableName) < 0 {
continue
}
tableName = CamelCase(tableName, prefix, true)
columns := convert.Driver.ReadTablesColumns(tableRealName)
content := convert.build(tableName, tableRealName, prefix, columns)
convert.writeModel(tableRealName, content) //写文件
}
convert.writeInit()
}
//build content with table info
func (convert *Convert) build(tableName, tableRealName, prefix string, columns []Column) (content string) {
depth := 1
format := GetFormat(convert.Style)
content += "package " + convert.PackageName + "\n\n" //写包名
content += format.AutoImport(tableName)
content += "type " + tableName + " struct {\n"
primaryKey := ""
var primaryColumns Column
for _, v := range columns {
var comment string
if v.ColumnComment != "" {
comment = fmt.Sprintf(" // %s", v.ColumnComment)
}
content += fmt.Sprintf("%s%s %s %s%s\n",
Tab(depth), v.GetGoColumn(prefix, true), v.GetGoType(), v.GetTag(format), comment)
if v.IsPrimaryKey() {
primaryKey = v.ColumnName
primaryColumns = v
}
}
content += Tab(depth-1) + "}\n\n"
if primaryKey != "" {
content += fmt.Sprintf("// GetKey get real primary key name \nfunc (%s *%s) %s() string {\n",
LcFirst(tableName), tableName, "GetKey")
content += fmt.Sprintf("%sreturn \"%s\"\n",
Tab(depth), primaryKey)
content += "}\n\n\n"
content += fmt.Sprintf("// GetKeyProperty get primary key in model\nfunc (%s *%s) %s() %s {\n",
LcFirst(tableName), tableName, "GetKeyProperty", primaryColumns.GetGoType())
content += fmt.Sprintf("%sreturn %s.%s\n",
Tab(depth), LcFirst(tableName), CamelCase(primaryKey, prefix, true))
content += "}\n\n\n"
content += fmt.Sprintf("// SetKeyProperty set primary key \nfunc (%s *%s) %s(id %s) {\n",
LcFirst(tableName), tableName, "SetKeyProperty", primaryColumns.GetGoType())
content += fmt.Sprintf("%s %s.%s = id\n",
Tab(depth), LcFirst(tableName), CamelCase(primaryKey, prefix, true))
content += "}\n\n\n"
}
content += fmt.Sprintf("// TableName get real table name\nfunc (%s *%s) %s() string {\n",
LcFirst(tableName), tableName, "TableName")
content += fmt.Sprintf("%sreturn \"%s\"\n",
Tab(depth), tableRealName)
content += "}\n\n\n"
content += convert.buildCurd(tableName, format)
return content
}
func (convert *Convert) buildCurd(tableName string, format Format) string {
content := ""
tpl := format.GetFuncTemplate(convert.Style)
if tpl != "" {
tpl = strings.Replace(tpl, "{{entry}}", LcFirst(tableName), -1)
tpl = strings.Replace(tpl, "{{object}}", tableName, -1)
content += tpl
convert.initOrm = true
}
return content
}
//write file
func (convert *Convert) writeInit() {
if convert.initOrm {
format := GetFormat(convert.Style)
tpl := format.GetInitTemplate(convert.Style)
if tpl != "" {
tpl = strings.Replace(tpl, "{{package}}", convert.PackageName, -1)
tpl = strings.Replace(tpl, "{{dns}}", convert.Driver.GetDsn(), -1)
log.Printf("write init file start\n", )
filePath := fmt.Sprintf("%s/%s.go", convert.ModelPath, "init")
f, err := os.Create(filePath)
if err != nil {
log.Println("Can not write file" + filePath)
return
}
defer func() {
_ = f.Close()
}()
_, err = f.WriteString(tpl)
if err != nil {
log.Println("Can not write file" + filePath)
return
}
cmd := exec.Command("gofmt", "-w", filePath)
_ = cmd.Run()
log.Printf("write init file success\n")
}
}
}
//write file
func (convert *Convert) writeModel(name, content string) {
log.Printf("write model file %s start\n", name)
filePath := fmt.Sprintf("%s/%s.go", convert.ModelPath, name)
f, err := os.Create(filePath)
if err != nil {
log.Println("Can not write file" + filePath)
return
}
defer func() {
_ = f.Close()
}()
_, err = f.WriteString(content)
if err != nil {
log.Println("Can not write file" + filePath)
return
}
cmd := exec.Command("gofmt", "-w", filePath)
_ = cmd.Run()
log.Printf("write model file %s success\n", name)
}
func (convert *Convert) SetStyle(name string) {
convert.Style = name
}
func (convert *Convert) GetStyle() string {
if convert.Style == "" {
return "default"
}
return convert.Style
}
func GetDriver(dir, driver, dsn, style, packageName string) *Convert {
convert := &Convert{}
convert.SetPackageName(packageName)
convert.SetModelPath(dir)
switch driver {
case "mysql":
convert.Driver = &MysqlToGo{}
convert.Driver.SetDsn(dsn)
convert.SetStyle(style)
default:
panic(fmt.Sprintf("do not support this driver: %v\n", driver))
}
return convert
}