-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsetting.go
444 lines (371 loc) · 8.41 KB
/
setting.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
package foog
import(
"fmt"
"database/sql"
"strings"
"errors"
"os"
"log"
"sync"
_ "github.com/go-sql-driver/mysql"
)
type SettingRule struct{
Name string
Table string
Index string
Value string
Field string
Where string
Order string
FieldSkip string
}
type column struct {
Field string
Type string
Table string
Comment string
}
type desc struct{
Name string
Table string
Where string
Order string
Fields []string
Indexs []string
Values []string
FieldSkip []string
Columns []column
BaseType string
BaseTypeCode string
IndexType string
IndexTypeList []string
}
var typesMap = map[string]string{
"int": "int",
"integer": "int",
"tinyint": "int",
"smallint": "int",
"mediumint": "int",
"bigint": "int",
"int unsigned": "int",
"integer unsigned": "int",
"tinyint unsigned": "int",
"smallint unsigned": "int",
"mediumint unsigned": "int",
"bigint unsigned": "int",
"bit": "int",
"bool": "bool",
"enum": "string",
"set": "string",
"varchar": "string",
"char": "string",
"tinytext": "string",
"mediumtext": "string",
"text": "string",
"longtext": "string",
"blob": "string",
"tinyblob": "string",
"mediumblob": "string",
"longblob": "string",
"date": "string",
"datetime": "string",
"timestamp": "string",
"time": "string",
"float": "float64",
"double": "float64",
"decimal": "float64",
"binary": "string",
"varbinary": "string",
}
var (
dbHost string
dbUser string
dbPass string
dbName string
dbInst *sql.DB
mutex sync.RWMutex
indexs map[string]interface{}
)
func SetSetting(host, user, pass, dbname string){
dbHost = host
dbUser = user
dbPass = pass
dbName = dbname
indexs = make(map[string]interface{})
}
func GetSettingDB()(*sql.DB, error){
if dbInst != nil{
return dbInst, nil
}
var (
dsn string
err error
)
dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", dbUser, dbPass, dbHost, dbName)
dbInst, err = sql.Open("mysql", dsn)
if err != nil{
return nil, err
}
return dbInst, nil
}
func CleanSetting(){
mutex.Lock()
defer mutex.Unlock()
indexs = make(map[string]interface{})
}
func StoreSetting(key string, val interface{}){
mutex.Lock()
defer mutex.Unlock()
indexs[key] = val
}
func LoadSetting(key string)(interface{}, bool){
mutex.RLock()
defer mutex.RUnlock()
v, found := indexs[key]
if !found {
log.Println("setting miss", key)
}
return v, found
}
func MakeSetting(path string, rules []SettingRule)bool{
db, err := GetSettingDB()
if err != nil{
log.Println("[ERROR]", err)
return false
}
for _, r := range rules{
//query table schema
query := fmt.Sprintf(`SELECT COLUMN_NAME,DATA_TYPE,TABLE_NAME,COLUMN_COMMENT
FROM information_schema.COLUMNS
WHERE table_schema = DATABASE() AND TABLE_NAME='%s'`, r.Table)
rows, err := db.Query(query)
if err != nil{
log.Println("[ERROR]", "query setting failed, name=" + r.Name + ", sql=" + query)
return false
}
defer rows.Close()
//init desc
d := &desc{}
d.Name = r.Name
d.Table = r.Table
d.Where = r.Where
d.Order = r.Order
if len(r.Field) > 0{
d.Fields = strings.Split(r.Field, ",")
}
if len(r.Index) > 0{
d.Indexs = strings.Split(r.Index, ",")
}
if len(r.Value) > 0{
d.Values = strings.Split(r.Value, ",")
}
if len(r.FieldSkip) > 0{
d.FieldSkip = strings.Split(r.FieldSkip, ",")
}
//fetch columns
d.Columns = make([]column, 0, 10)
for rows.Next() {
col := column{}
if err := rows.Scan(&col.Field, &col.Type, &col.Table, &col.Comment); err != nil {
log.Println("[ERROR]", err)
return false
}
if len(d.Fields) > 0 && !inArray(d.Fields, col.Field){
continue
}
if len(d.FieldSkip) > 0 && inArray(d.FieldSkip, col.Field){
continue
}
d.Columns = append(d.Columns, col)
}
//make base struct
err = genStruct(d)
if err != nil{
log.Println("[ERROR] gen struct failed", err)
return false
}
//make index struct
err = genIndex(d)
if err != nil{
log.Println("[ERROR] gen index failed", err)
return false
}
//make go file
code, err := genCode(d)
if err != nil{
log.Println("[ERROR] gan code failed", err)
return false
}
f, err := os.OpenFile(path + "/" + r.Name + ".go", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil{
log.Println("[ERROR] write file failed", err)
return false
}
defer f.Close()
f.WriteString(code)
log.Println("generate succed", r.Name)
}
return true
}
func genStruct(d *desc)error{
d.BaseType = "Type_" + d.Name
d.BaseTypeCode = "type " + d.BaseType + " struct{\n"
for _, col := range d.Columns {
colName := ucfirst(col.Field)
d.BaseTypeCode+= "\t" + colName + "\t\t" + typesMap[col.Type] + " //" + col.Comment + "\n"
}
d.BaseTypeCode+= "}"
return nil
}
func genIndex(d *desc)error{
if len(d.Indexs) < 1{
return errors.New("Invalid index, name=" + d.Name)
}
d.IndexTypeList = make([]string, len(d.Indexs))
for k, v := range d.Indexs {
col, ok := getColumnByName(d.Columns, v)
if !ok {
return errors.New("field not found by index:" + v)
}
d.IndexTypeList[k] = "map[" + typesMap[col.Type] + "]"
d.IndexType+= "map[" + typesMap[col.Type] + "]"
}
d.IndexType+= d.BaseType
return nil
}
func genCode(d *desc)(string, error){
field := ""
sep := ""
for _, col := range d.Columns{
field+= sep + "`" + col.Field + "`"
sep = ","
}
where := ""
if d.Where != ""{
where = " WHERE " + d.Where
}
order := ""
if d.Order != "" {
order = " ORDER BY " + d.Order
}
indexchecker := ""
indexlevel := ""
for k, v := range d.Indexs {
colName := ucfirst(v)
indexlevel+= "[row." + colName + "]"
if k < len(d.Indexs) - 1 {
childtype := ""
for i := k + 1; i < len(d.Indexs); i++{
childtype+= d.IndexTypeList[i]
}
childtype+= d.BaseType
indexchecker+= "\n\t\tif _, found := ret" + indexlevel + "; !found{\n"
indexchecker+= "\t\t\tret" + indexlevel + " = make(" + childtype + ")\n"
indexchecker+= "\t\t}\n"
}
}
scanstr := ""
fieldNullType := ""
fieldNullFill := ""
sep = ""
for _, col := range d.Columns{
colName := ucfirst(col.Field)
colType := typesMap[col.Type]
tmpName := "_" + ucfirst(col.Field)
tmpType := ucfirst(colType)
if colType == "int"{
tmpType+= "64"
}
fieldNullType+= "\t\tvar " + tmpName + " sql.Null" + tmpType + "\n"
scanstr+= sep + "&" + tmpName
if colType == "int"{
fieldNullFill+= "\t\trow." + colName + " = int(" + tmpName+"."+tmpType+")\n"
}else{
fieldNullFill+= "\t\trow." + colName + " = " + tmpName+"."+tmpType+"\n"
}
sep = ", "
}
tags := map[string]string{
"name": d.Name,
"basetype": d.BaseType,
"basestruct": d.BaseTypeCode,
"indextype": d.IndexType,
"table": "`" + d.Table + "`",
"field": field,
"where": where,
"order": order,
"scanstr": scanstr,
"indexchecker": indexchecker,
"indexlevel": indexlevel,
"fieldnulltype": fieldNullType,
"fieldnullfill": fieldNullFill,
}
temp :=
`//
//WARNING!!!!!Dont modify this file, it is auto generated by tool
//
package setting
import(
"github.com/scgywx/foog"
"database/sql"
)
${basestruct}
func Load_${name}()(${indextype}, error){
v, found := foog.LoadSetting("${name}")
if found {
return v.(${indextype}), nil
}
db, err := foog.GetSettingDB()
if err != nil{
return nil, err
}
rows, err := db.Query("SELECT ${field} FROM ${table} ${where} ${order}")
if err != nil{
return nil, err
}
var ret = make(${indextype})
for rows.Next() {
${fieldnulltype}
if err := rows.Scan(${scanstr}); err != nil {
return nil, err
}
var row ${basetype}
${fieldnullfill}
${indexchecker}
ret${indexlevel} = row
}
foog.StoreSetting("${name}", ret)
return ret, nil
}`
for k, v := range tags{
temp = strings.ReplaceAll(temp, "${"+k+"}", v)
}
return temp, nil
}
func getColumnByName(fields []column, name string)(column, bool){
for _, v := range fields{
if name == v.Field{
return v, true
}
}
return column{}, false
}
func inArray(arr []string, s string)bool{
for _,v := range arr{
if v == s{
return true
}
}
return false
}
func ucfirst(str string)string{
if len(str) < 1{
return ""
}
bytes := []byte(str)
if bytes[0] >= 97 && bytes[0] <= 122{
bytes[0]-= 32
str = string(bytes)
}
return str
}