-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
373 lines (351 loc) · 9.27 KB
/
cli.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
_ "embed"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/ssgo/dao/dao"
"github.com/ssgo/db"
"github.com/ssgo/log"
"github.com/ssgo/u"
_ "modernc.org/sqlite"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
//
//type ValidFieldConfig struct {
// Field string
// Type string
// ValidOperator string
// ValidValue string
// ValidSetOperator string
// ValidSetValue string
// InvalidSetOperator string
// InvalidSetValue string
//}
type DaoConfig struct {
VersionField string
ValidFields []dao.ValidFieldConfig
Db []string
}
//type TableDesc struct {
// Field string
// Type string
// Null string
// Key string
// Default *string
// Extra string
// After string
//}
//
//type TableIndex struct {
// Non_unique int
// Key_name string
// Seq_in_index int
// Column_name string
//}
//
//type DaoData struct {
// DBName string
// VersionField string
// Tables []string
// FixedTables []string
//}
//
////go:embed a_config.go.tpl
//var configTpl string // 当前目录,解析为string类型
//
////go:embed dao/a_table.go.tpl
//var tableTpl string // 当前目录,解析为string类型
//
////go:embed dao/a_er.html
//var erTpl string // 当前目录,解析为string类型
//
////type AA string
////
////const (
//// A1 AA = "111"
//// A2 AA = "222"
////)
//
//type FieldData struct {
// Name string
// Type string
// Default string
// Options map[string]string
//}
//
//type IndexField struct {
// Name string
// Where string
// Args string
// Params string
// ItemArgs string
// StringArgs string
//}
//
//type TableData struct {
// DBName string
// TableName string
// FixedTableName string
// IsAutoId bool
// AutoIdField string
// AutoIdFieldType string
// PrimaryKey *IndexField
// UniqueKeys map[string]*IndexField
// IndexKeys map[string]*IndexField
// Fields []FieldData
// PointFields []FieldData
// //FieldsWithoutAutoId []FieldData
// SelectFields string
// ValidField string
// ValidWhere string
// ValidSet string
// InvalidSet string
// VersionField string
// HasVersion bool
// AutoGenerated []string
// AutoGeneratedOnUpdate []string
//}
//
//type FindingDBConfig struct {
// DB string
//}
func getDBs(args []string) []string {
dbs := make([]string, 0)
filters := make(map[string]bool)
if args != nil {
for i := 0; i < len(args); i++ {
if strings.Contains(args[i], "://") {
dbs = append(dbs, args[i])
} else {
filters[args[i]] = true
}
}
}
if len(dbs) == 0 || len(filters) > 0 {
dbExists := map[string]bool{}
// 优先查找 env.yml
if u.FileExists("env.yml") {
lines, err := u.ReadFileLines("env.yml")
if err == nil {
for _, line := range lines {
if strings.Contains(line, "mysql://") {
if strings.ContainsRune(line, '?') {
line = line[0:strings.IndexByte(line, '?')]
}
dbName := line[strings.LastIndexByte(line, '/')+1:]
if len(filters) == 0 || filters[dbName] {
if !dbExists[dbName] {
dbExists[dbName] = true
dbs = append(dbs, "mysql://"+strings.Split(line, "mysql://")[1])
}
}
}
}
}
}
// 查找更多的
files, err := u.ReadDir(".")
if err == nil {
for _, file := range files {
if file.Name[0] == '.' || !strings.HasSuffix(file.Name, ".yml") || file.Name == "env.yml" {
continue
}
lines, err := u.ReadFileLines(file.Name)
if err == nil {
for _, line := range lines {
tag := ""
if strings.Contains(line, "mysql://") {
tag = "mysql://"
} else if strings.Contains(line, "postgres://") {
tag = "postgres://"
} else if strings.Contains(line, "oci8://") {
tag = "oci8://"
} else if strings.Contains(line, "mssql://") {
tag = "mssql://"
} else if strings.Contains(line, "sqlite3://") {
tag = "sqlite3://"
} else if strings.Contains(line, "sqlite://") {
tag = "sqlite://"
} else {
continue
}
if strings.Contains(line, tag) {
if strings.ContainsRune(line, '?') {
line = line[0:strings.IndexByte(line, '?')]
}
dbName := line[strings.LastIndexByte(line, '/')+1:]
if len(filters) == 0 || filters[dbName] {
if !dbExists[dbName] {
dbExists[dbName] = true
dbs = append(dbs, tag+strings.Split(line, tag)[1])
}
}
}
}
}
}
}
}
return dbs
}
//func fixParamName(in string) string {
// switch in {
// case "type":
// return "typ"
// }
// return in
//}
//
//func fixJoinParams(elems []string, sep string) string {
// a := make([]string, len(elems))
// for i := len(elems) - 1; i >= 0; i-- {
// a[i] = fixParamName(elems[i])
// }
// return strings.Join(a, sep)
//}
func main() {
if len(os.Args) == 1 {
printUsage()
return
}
conf := DaoConfig{}
if u.FileExists("dao.yml") {
_ = u.LoadYaml("dao.yml", &conf)
}
if conf.Db == nil {
if os.Args[1] == "-i" && len(os.Args) > 3 {
conf.Db = getDBs(os.Args[3:])
} else if len(os.Args) > 2 {
conf.Db = getDBs(os.Args[2:])
} else {
conf.Db = getDBs(nil)
}
}
if conf.VersionField == "" {
conf.VersionField = dao.DefaultVersionField
}
if conf.ValidFields == nil {
conf.ValidFields = dao.DefaultValidFields
}
numberTester := regexp.MustCompile("^[0-9]+$")
for k, validFieldInfo := range conf.ValidFields {
if !numberTester.MatchString(validFieldInfo.ValidValue) {
conf.ValidFields[k].ValidValue = "'" + validFieldInfo.ValidValue + "'"
}
if !numberTester.MatchString(validFieldInfo.InvalidSetValue) {
conf.ValidFields[k].InvalidSetValue = "'" + validFieldInfo.InvalidSetValue + "'"
}
}
op := os.Args[1]
switch op {
case "-t":
if conf.Db == nil {
fmt.Println("no dsn found")
printUsage()
return
}
for _, dsn := range conf.Db {
conn := db.GetDB(dsn, nil)
r := conn.Query("SHOW TABLES")
if r.Error != nil {
fmt.Println("failed to connect to db ", u.Red(r.Error.Error()))
return
}
dbPath := conn.Config.DB + "Dao"
fmt.Println(conn.Config.DB)
for _, table := range r.StringsOnC1() {
if strings.HasPrefix(table, "_") || strings.HasPrefix(table, ".") {
continue
}
dbFile := path.Join(dbPath, "a_"+table+".go")
exists := u.FileExists(dbFile)
fmt.Println(" -", table, u.StringIf(exists, u.Green("OK"), u.Dim("Lost")))
}
}
case "-u":
if conf.Db == nil {
fmt.Println("no dsn found")
printUsage()
return
}
for _, dsn := range conf.Db {
conn := db.GetDB(dsn, nil)
_ = dao.MakeDaoFromDBWithOption(conn, conf.VersionField, conf.ValidFields, nil)
}
case "-c":
erInFile := "er.txt"
if len(os.Args) > 2 {
erInFile = os.Args[2]
}
dbName := strings.SplitN(filepath.Base(erInFile), ".", 2)[0]
if len(os.Args) > 3 {
dbName = os.Args[3]
}
desc := u.ReadFileN(erInFile)
_ = dao.MakeDaoFromDescWithOption(desc, dbName, conf.VersionField, conf.ValidFields, nil)
case "-i":
if conf.Db == nil || len(conf.Db) == 0 {
fmt.Println("no dsn found")
printUsage()
return
}
erInFile := "er.txt"
if len(os.Args) > 2 {
erInFile = os.Args[2]
}
desc := u.ReadFileN(erInFile)
conn := db.GetDB(conf.Db[0], log.DefaultLogger)
_ = dao.MakeDBFromDesc(conn, desc, nil)
case "-er":
erInFile := "er.txt"
erOutFile := "er.html"
if len(os.Args) > 2 {
erInFile = os.Args[2]
}
dbName := strings.SplitN(filepath.Base(erInFile), ".", 2)[0]
if len(os.Args) > 3 {
dbName = os.Args[3]
}
if len(os.Args) > 4 {
erOutFile = os.Args[4]
} else {
erOutFile = dbName + ".html"
}
desc := u.ReadFileN(erInFile)
dao.MakeERFile(desc, dbName, erOutFile, nil)
default:
printUsage()
}
}
func printUsage() {
fmt.Println("Usage:")
fmt.Println(" dao")
fmt.Println(" " + u.Cyan("-t [dsn]") + " " + u.White("测试数据库连接,并检查已经生成的对象"))
fmt.Println(" " + u.Cyan("-u [dsn]") + " " + u.White("从数据库创建或更新DAO对象"))
fmt.Println(" " + u.Cyan("-i [erFile] [dsn]") + " " + u.White("从描述文件导入数据结构"))
fmt.Println(" " + u.Cyan("-c [erFile] [dbname]") + " " + u.White("从描述文件创建或更新DAO对象"))
fmt.Println(" " + u.Cyan("-er [erFile] [dbname] [output file]") + " " + u.White("从描述文件创建ER图"))
fmt.Println(" dsn " + u.White("mysql://、postgres://、oci8://、mssql://、sqlite3://、sqlite:// 等开头数据库描述,如未指定尝试从*.yml中查找"))
fmt.Println("")
fmt.Println("Samples:")
fmt.Println(" " + u.Cyan("dao -t"))
fmt.Println(" " + u.Cyan("dao -t dbname"))
fmt.Println(" " + u.Cyan("dao -t mysql://user:password@host:port/db"))
fmt.Println(" " + u.Cyan("dao -u"))
fmt.Println(" " + u.Cyan("dao -u dbname"))
fmt.Println(" " + u.Cyan("dao -u mysql://user:password@host:port/db"))
fmt.Println(" " + u.Cyan("dao -i"))
fmt.Println(" " + u.Cyan("dao -i er.txt"))
fmt.Println(" " + u.Cyan("dao -i er.txt dbname"))
fmt.Println(" " + u.Cyan("dao -i er.txt mysql://user:password@host:port/db"))
fmt.Println(" " + u.Cyan("dao -c er.txt"))
fmt.Println(" " + u.Cyan("dao -c er.txt dbname"))
fmt.Println(" " + u.Cyan("dao -er er.txt"))
fmt.Println(" " + u.Cyan("dao -er er.txt dbname"))
fmt.Println(" " + u.Cyan("dao -er er.txt dbname dbname.html"))
fmt.Println("")
}