forked from GoAdminGroup/go-admin
/
generator.go
459 lines (396 loc) · 14.1 KB
/
generator.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package tools
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"path/filepath"
"regexp"
"strings"
"text/template"
"github.com/vafinvr/go-admin/modules/db/dialect"
"github.com/vafinvr/go-admin/modules/language"
"github.com/vafinvr/go-admin/modules/db"
"github.com/vafinvr/go-admin/modules/utils"
"github.com/vafinvr/go-admin/template/types/form"
)
type Param struct {
Connection string `json:"connection"`
Driver string `json:"driver"`
Package string `json:"package"`
Table string `json:"table"`
RowTable string `json:"row_table"`
TableTitle string `json:"table_title"`
TableName string `json:"table_name"`
HideFilterArea bool `json:"hide_filter_area"`
HideNewButton bool `json:"hide_new_button"`
HideExportButton bool `json:"hide_export_button"`
HideEditButton bool `json:"hide_edit_button"`
HideDeleteButton bool `json:"hide_delete_button"`
HideDetailButton bool `json:"hide_detail_button"`
HideFilterButton bool `json:"hide_filter_button"`
HideRowSelector bool `json:"hide_row_selector"`
HidePagination bool `json:"hide_pagination"`
HideQueryInfo bool `json:"hide_query_info"`
FilterFormLayout form.Layout `json:"filter_form_layout"`
HideContinueEditCheckBox bool `json:"hide_continue_edit_check_box"`
HideContinueNewCheckBox bool `json:"hide_continue_new_check_box"`
HideResetButton bool `json:"hide_reset_button"`
HideBackButton bool `json:"hide_back_button"`
TablePageTitle string `json:"table_title"`
TableDescription string `json:"table_description"`
FormTitle string `json:"form_title"`
FormDescription string `json:"form_description"`
DetailTitle string `json:"detail_title"`
DetailDescription string `json:"detail_description"`
ExtraImport string `json:"extra_import"`
ExtraCode string `json:"extra_code"`
Fields Fields `json:"fields"`
FormFields Fields `json:"form_fields"`
DetailFields Fields `json:"detail_fields"`
DetailDisplay uint8 `json:"detail_display"`
Output string `json:"output"`
}
type Config struct {
Connection string `json:"connection"`
Driver string `json:"driver"`
Package string `json:"package"`
Table string `json:"table"`
Schema string `json:"schema"`
Output string `json:"output"`
Conn db.Connection `json:"conn"`
HideFilterArea bool `json:"hide_filter_area"`
HideNewButton bool `json:"hide_new_button"`
HideExportButton bool `json:"hide_export_button"`
HideEditButton bool `json:"hide_edit_button"`
HideDeleteButton bool `json:"hide_delete_button"`
HideDetailButton bool `json:"hide_detail_button"`
HideFilterButton bool `json:"hide_filter_button"`
HideRowSelector bool `json:"hide_row_selector"`
HidePagination bool `json:"hide_pagination"`
HideQueryInfo bool `json:"hide_query_info"`
FilterFormLayout form.Layout `json:"filter_form_layout"`
ExtraImport string `json:"extra_import"`
TableTitle string `json:"table_title"`
TableDescription string `json:"table_description"`
FormTitle string `json:"form_title"`
FormDescription string `json:"form_description"`
DetailTitle string `json:"detail_title"`
DetailDescription string `json:"detail_description"`
HideContinueEditCheckBox bool `json:"hide_continue_edit_check_box"`
HideContinueNewCheckBox bool `json:"hide_continue_new_check_box"`
HideResetButton bool `json:"hide_reset_button"`
HideBackButton bool `json:"hide_back_button"`
DetailDisplay uint8 `json:"detail_display"`
ExtraCode string `json:"extra_code"`
}
func fixedTable(table string) string {
if utils.InArray(keyWords, table) {
return table + "_"
}
return table
}
var keyWords = []string{"import", "package", "chan", "const", "func", "interface", "map", "struct", "type",
"var", "break", "case", "continue", "default", "defer", "else", "fallthrough", "for", "go", "goto", "if",
"range", "return", "select", "switch"}
func NewParam(cfg Config) *Param {
ta := camelcase(cfg.Table)
dbTable := cfg.Table
if cfg.Schema != "" {
dbTable = cfg.Schema + "." + cfg.Table
}
fields := getFieldsFromConn(cfg.Conn, dbTable, cfg.Driver)
tt := strings.Title(ta)
return &Param{
Connection: cfg.Connection,
Driver: cfg.Driver,
Package: cfg.Package,
Table: fixedTable(ta),
TableTitle: tt,
TableName: dbTable,
HideFilterArea: cfg.HideFilterArea,
HideNewButton: cfg.HideNewButton,
HideExportButton: cfg.HideExportButton,
HideEditButton: cfg.HideEditButton,
HideDeleteButton: cfg.HideDeleteButton,
HideDetailButton: cfg.HideDetailButton,
HideFilterButton: cfg.HideFilterButton,
HideRowSelector: cfg.HideRowSelector,
HidePagination: cfg.HidePagination,
HideQueryInfo: cfg.HideQueryInfo,
FilterFormLayout: cfg.FilterFormLayout,
HideContinueEditCheckBox: cfg.HideContinueEditCheckBox,
HideContinueNewCheckBox: cfg.HideContinueNewCheckBox,
HideResetButton: cfg.HideResetButton,
HideBackButton: cfg.HideBackButton,
RowTable: cfg.Table,
Fields: fields,
FormFields: fields,
DetailDisplay: cfg.DetailDisplay,
Output: cfg.Output,
ExtraImport: cfg.ExtraImport,
ExtraCode: cfg.ExtraCode,
TablePageTitle: utils.SetDefault(cfg.TableTitle, "", tt),
TableDescription: utils.SetDefault(cfg.TableDescription, "", tt),
FormTitle: utils.SetDefault(cfg.FormTitle, "", tt),
FormDescription: utils.SetDefault(cfg.FormDescription, "", tt),
}
}
func NewParamWithFields(cfg Config, fields ...Fields) *Param {
ta := camelcase(cfg.Table)
dbTable := cfg.Table
if cfg.Schema != "" {
dbTable = cfg.Schema + "." + cfg.Table
}
if len(cfg.Output) > 0 && cfg.Output[len(cfg.Output)-1] == '/' {
cfg.Output = cfg.Output[:len(cfg.Output)-1]
}
tt := strings.Title(ta)
detailFields := make(Fields, 0)
if len(fields) > 2 {
detailFields = fields[2]
}
return &Param{
Connection: cfg.Connection,
Driver: cfg.Driver,
Package: cfg.Package,
Table: ta,
TableTitle: tt,
TableName: dbTable,
RowTable: cfg.Table,
Fields: fields[0],
FormFields: fields[1],
DetailFields: detailFields,
HideFilterArea: cfg.HideFilterArea,
HideNewButton: cfg.HideNewButton,
HideExportButton: cfg.HideExportButton,
HideEditButton: cfg.HideEditButton,
HideDeleteButton: cfg.HideDeleteButton,
HideDetailButton: cfg.HideDetailButton,
HideFilterButton: cfg.HideFilterButton,
HideRowSelector: cfg.HideRowSelector,
HidePagination: cfg.HidePagination,
HideQueryInfo: cfg.HideQueryInfo,
FilterFormLayout: cfg.FilterFormLayout,
HideContinueEditCheckBox: cfg.HideContinueEditCheckBox,
HideContinueNewCheckBox: cfg.HideContinueNewCheckBox,
HideResetButton: cfg.HideResetButton,
HideBackButton: cfg.HideBackButton,
DetailDisplay: cfg.DetailDisplay,
Output: cfg.Output,
ExtraImport: cfg.ExtraImport,
ExtraCode: cfg.ExtraCode,
TablePageTitle: utils.SetDefault(cfg.TableTitle, "", tt),
TableDescription: utils.SetDefault(cfg.TableDescription, "", tt),
FormTitle: utils.SetDefault(cfg.FormTitle, "", tt),
FormDescription: utils.SetDefault(cfg.FormDescription, "", tt),
DetailTitle: utils.SetDefault(cfg.DetailTitle, "", tt),
DetailDescription: utils.SetDefault(cfg.DetailDescription, "", tt),
}
}
type Fields []Field
type Field struct {
Head string `json:"head"`
Name string `json:"name"`
DBType string `json:"db_type"`
FormType string `json:"form_type"`
Filterable bool `json:"filterable"`
Sortable bool `json:"sortable"`
InfoEditable bool `json:"info_editable"`
Editable bool `json:"editable"`
Hide bool `json:"hide"`
FormHide bool `json:"form_hide"`
EditHide bool `json:"edit_hide"`
CreateHide bool `json:"create_hide"`
Default string `json:"default"`
CanAdd bool `json:"can_add"`
ExtraFun string `json:"extra_fun"`
}
func Generate(param *Param) error {
t, err := template.New("table_model").Parse(tableModelTmpl)
if err != nil {
return err
}
buf := new(bytes.Buffer)
err = t.Execute(buf, param)
if err != nil {
return err
}
c, err := format.Source(buf.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile(filepath.FromSlash(param.Output)+"/"+param.RowTable+".go", c, 0644)
}
const (
commentStrEnd = "example end"
tablesEnd = "generators end"
)
func GenerateTables(outputPath, packageName string, tables []string, isNew bool) error {
if len(outputPath) > 0 && outputPath[len(outputPath)-1] == '/' {
outputPath = outputPath[:len(outputPath)-1]
}
outputPath = filepath.FromSlash(outputPath)
fileExist := utils.FileExist(outputPath + "/tables.go")
if !isNew && !fileExist {
return nil
}
var (
tableStr = ""
commentStr = ""
tablesContentByte []byte
tablesContent string
err error
)
if fileExist {
tablesContentByte, err = ioutil.ReadFile(outputPath + "/tables.go")
if err != nil {
return err
}
tablesContent = string(tablesContentByte)
}
for i := 0; i < len(tables); i++ {
lowerTable := strings.ToLower(tables[i])
if !strings.Contains(tablesContent, `"`+lowerTable+`"`) {
tableStr += fmt.Sprintf(`
"%s": Get%sTable, `, lowerTable, strings.Title(camelcase(tables[i])))
if commentStr != "" {
commentStr += `
`
}
commentStr += fmt.Sprintf(`// "%s" => http://localhost:9033/admin/info/%s`, lowerTable, lowerTable)
}
}
commentStr += `
//
// ` + commentStrEnd
tableStr += `
// ` + tablesEnd
content := ""
if tablesContent != "" && strings.Contains(tablesContent, "/") {
replacer := strings.NewReplacer(`// `+commentStrEnd, commentStr, `// `+tablesEnd, tableStr)
tablesContent = replacer.Replace(tablesContent)
keep := `// example:
//`
keep2 := `,
// ` + tablesEnd
replacer2 := strings.NewReplacer(keep, keep, keep2, keep2,
`//
//
`, "//", `//
//`, "//", `//
// "`, `// "`,
`,
`, ",")
content = replacer2.Replace(tablesContent)
} else {
content = fmt.Sprintf(`// This file is generated by GoAdmin CLI adm.
package %s
import "github.com/vafinvr/go-admin/plugins/admin/modules/table"
// The key of Generators is the prefix of table info url.
// The corresponding value is the Form and Table data.
//
// http://{{config.Domain}}:{{Port}}/{{config.Prefix}}/info/{{key}}
//
// example:
//
%s
var Generators = map[string]table.Generator{
%s
}
`, packageName, commentStr, tableStr)
}
c, err := format.Source([]byte(content))
if err != nil {
return err
}
return ioutil.WriteFile(outputPath+"/tables.go", c, 0644)
}
func InsertPermissionOfTable(conn db.Connection, table string) {
table = strings.ToLower(table)
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("query", "generator"), table+"_query", "GET", "/info/"+table)
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("show edit form page", "generator"), table+"_show_edit", "GET",
"/info/"+table+"/edit")
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("show create form page", "generator"), table+"_show_create", "GET",
"/info/"+table+"/new")
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("edit", "generator"), table+"_edit", "POST",
"/edit/"+table)
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("create", "generator"), table+"_create", "POST",
"/new/"+table)
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("delete", "generator"), table+"_delete", "POST",
"/delete/"+table)
InsertPermissionInfoDB(conn, table+" "+language.GetWithScope("export", "generator"), table+"_export", "POST",
"/export/"+table)
}
func InsertPermissionInfoDB(conn db.Connection, name, slug, httpMethod, httpPath string) {
checkExist, err := db.WithDriver(conn).Table("goadmin_permissions").
Where("slug", "=", slug).
First()
if db.CheckError(err, db.QUERY) {
panic(err)
}
if checkExist != nil {
return
}
_, err = db.WithDriver(conn).Table("goadmin_permissions").
Insert(dialect.H{
"name": name,
"slug": slug,
"http_method": httpMethod,
"http_path": httpPath,
})
if db.CheckError(err, db.INSERT) {
panic(err)
}
}
func camelcase(s string) string {
arr := strings.Split(s, "_")
var res = ""
for i := 0; i < len(arr); i++ {
if i == 0 {
res += arr[i]
} else {
res += strings.Title(arr[i])
}
}
return res
}
func getType(typeName string) string {
r, _ := regexp.Compile(`\(.*?\)`)
typeName = r.ReplaceAllString(typeName, "")
r2, _ := regexp.Compile(`unsigned(.*)`)
return strings.TrimSpace(strings.Title(strings.ToLower(r2.ReplaceAllString(typeName, ""))))
}
func getFieldsFromConn(conn db.Connection, table, driver string) Fields {
columnsModel, _ := db.WithDriver(conn).Table(table).ShowColumns()
fields := make(Fields, len(columnsModel))
fieldField := "Field"
typeField := "Type"
if driver == "postgresql" {
fieldField = "column_name"
typeField = "udt_name"
}
if driver == "sqlite" {
fieldField = "name"
typeField = "type"
}
if driver == "mssql" {
fieldField = "column_name"
typeField = "data_type"
}
for i, model := range columnsModel {
typeName := getType(model[typeField].(string))
fields[i] = Field{
Head: strings.Title(model[fieldField].(string)),
Name: model[fieldField].(string),
DBType: typeName,
CanAdd: true,
Editable: true,
FormType: form.GetFormTypeFromFieldType(db.DT(strings.ToUpper(typeName)), model[fieldField].(string)),
}
if model[fieldField].(string) == "id" {
fields[i].Filterable = true
}
}
return fields
}