init.go
2.2 KB
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
package pg
import (
"fmt"
"reflect"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
"github.com/linmadan/egglib-go/persistent/pg/hooks"
)
var DB *pg.DB
func init() {
DB = pg.Connect(&pg.Options{
User: constant.POSTGRESQL_USER,
Password: constant.POSTGRESQL_PASSWORD,
Database: constant.POSTGRESQL_DB_NAME,
Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
})
if !constant.DISABLE_SQL_GENERATE_PRINT {
DB.AddQueryHook(hooks.SqlGeneratePrintHook{})
}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{
(*models.Device)(nil),
(*models.Product)(nil),
(*models.ProductAttendanceRecord)(nil),
(*models.ProductCalendar)(nil),
(*models.ProductGroup)(nil),
(*models.ProductJob)(nil),
(*models.ProductPlan)(nil),
(*models.ProductRecord)(nil),
(*models.UnitConversion)(nil),
(*models.Workshop)(nil),
(*models.MaterialK3cloud)(nil),
(*models.MaterialGroupK3cloud)(nil),
(*models.PrdMoK3cloud)(nil),
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
if !constant.DISABLE_SQL_GENERATE_COMMENT {
AddComments(DB, model)
}
}
}
}
func AddComments(db *pg.DB, model interface{}) {
tableName := db.Model(model).TableModel().Table().SQLName
columnsMap := make(map[string]*orm.Field)
columns := db.Model(model).TableModel().Table().Fields
for _, item := range columns {
columnsMap[item.GoName] = item
}
valueOf := reflect.TypeOf(model)
for i := 0; i < valueOf.Elem().NumField(); i++ {
field := valueOf.Elem().Field(i)
comment := field.Tag.Get("comment")
if comment != "" {
if field.Name == "tableName" {
_, _ = db.Exec(fmt.Sprintf("COMMENT ON TABLE %s IS '%s';", tableName, comment))
} else {
if columnField, ok := columnsMap[field.Name]; ok {
_, _ = db.Exec(fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", tableName, columnField.SQLName, comment))
}
}
}
}
}