forked from PolarPanda611/trinity
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
174 lines (158 loc) · 4.83 KB
/
Copy pathdb.go
File metadata and controls
174 lines (158 loc) · 4.83 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
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
package trinity
import (
"fmt"
"log"
"math/rand"
"strings"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq" //pg
uuid "github.com/satori/go.uuid"
)
//InitDatabase create db connection
/**
* initial db connection
*/
func (t *Trinity) InitDatabase() {
var dbconnection string
switch t.setting.GetDBType() {
case "mysql":
var dbconn strings.Builder
// 向builder中写入字符 / 字符串
dbconn.Write([]byte(t.setting.GetDBUser()))
dbconn.WriteByte(':')
dbconn.Write([]byte(t.setting.GetDBPassword()))
dbconn.Write([]byte("@/"))
dbconn.Write([]byte(t.setting.GetDBName()))
dbconn.WriteByte('?')
dbconn.Write([]byte(t.setting.GetDBOption()))
dbconnection = dbconn.String()
break
case "postgres":
dbconnection = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s %s",
t.setting.GetDBHost(),
t.setting.GetDBPort(),
t.setting.GetDBUser(),
t.setting.GetDBPassword(),
t.setting.GetDBName(),
t.setting.GetDBOption(),
)
break
}
db, err := gorm.Open(t.setting.GetDBType(), dbconnection)
db.SetLogger(&NilLogger{})
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return t.setting.GetTablePrefix() + defaultTableName
}
if err != nil {
log.Fatalf("models.Setup err: %v", err)
}
db.LogMode(t.setting.GetDebug())
db.SingularTable(true)
db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampAndUUIDForCreateCallback)
db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback)
db.Callback().Delete().Replace("gorm:delete", deleteCallback)
db.DB().SetMaxIdleConns(t.setting.GetDbMaxIdleConn())
db.DB().SetMaxOpenConns(t.setting.GetDbMaxOpenConn())
t.db = db
}
// GetDB get db instance
func (t *Trinity) GetDB() *gorm.DB {
t.mu.RLock()
d := t.db
t.mu.RUnlock()
return d
}
// updateTimeStampForCreateCallback will set `CreatedOn`, `ModifiedOn` when creating
func updateTimeStampAndUUIDForCreateCallback(scope *gorm.Scope) {
if !scope.HasError() {
userIDInterface, _ := scope.Get("UserID")
userID, _ := userIDInterface.(int64)
nowTime := GetCurrentTime()
if createTimeField, ok := scope.FieldByName("CreatedTime"); ok {
if createTimeField.IsBlank {
createTimeField.Set(nowTime)
}
}
if createUserIDField, ok := scope.FieldByName("CreateUserID"); ok {
if createUserIDField.IsBlank {
createUserIDField.Set(userID)
}
}
if idField, ok := scope.FieldByName("ID"); ok {
idField.Set(GenerateSnowFlakeID(int64(rand.Intn(100))))
}
if modifyTimeField, ok := scope.FieldByName("UpdatedTime"); ok {
if modifyTimeField.IsBlank {
modifyTimeField.Set(nowTime)
}
}
if updateUserIDField, ok := scope.FieldByName("UpdateUserID"); ok {
if updateUserIDField.IsBlank {
updateUserIDField.Set(userID)
}
}
if updateDVersionField, ok := scope.FieldByName("DVersion"); ok {
if updateDVersionField.IsBlank {
updateDVersionField.Set(uuid.NewV4().String())
}
}
}
}
// updateTimeStampForUpdateCallback will set `ModifiedOn` when updating
func updateTimeStampForUpdateCallback(scope *gorm.Scope) {
if !scope.HasError() {
userID, _ := scope.Get("UserID")
var updateAttrs = map[string]interface{}{}
if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
updateAttrs = attrs.(map[string]interface{})
updateAttrs["updated_time"] = GetCurrentTime()
updateAttrs["update_user_id"] = userID
updateAttrs["d_version"] = uuid.NewV4().String()
scope.InstanceSet("gorm:update_attrs", updateAttrs)
}
}
}
// deleteCallback will set `DeletedOn` where deleting
func deleteCallback(scope *gorm.Scope) {
if !scope.HasError() {
userID, ok := scope.Get("UserID")
if !ok {
userID = nil
}
var extraOption string
if str, ok := scope.Get("gorm:delete_option"); ok {
extraOption = fmt.Sprint(str)
}
deletedAtField, hasDeletedAtField := scope.FieldByName("deleted_time")
deleteUserIDField, hasDeleteUserIDField := scope.FieldByName("DeleteUserID")
dVersionField, hasDVersionField := scope.FieldByName("d_version")
if !scope.Search.Unscoped && hasDeletedAtField && hasDVersionField && hasDeleteUserIDField {
scope.Raw(fmt.Sprintf(
"UPDATE %v SET %v=%v,%v=%v,%v=%v%v%v",
scope.QuotedTableName(),
scope.Quote(deletedAtField.DBName),
scope.AddToVars(GetCurrentTime()),
scope.Quote(deleteUserIDField.DBName),
scope.AddToVars(userID),
scope.Quote(dVersionField.DBName),
scope.AddToVars(uuid.NewV4().String()),
addExtraSpaceIfExist(scope.CombinedConditionSql()),
addExtraSpaceIfExist(extraOption),
)).Exec()
} else {
scope.Raw(fmt.Sprintf(
"DELETE FROM %v%v%v",
scope.QuotedTableName(),
addExtraSpaceIfExist(scope.CombinedConditionSql()),
addExtraSpaceIfExist(extraOption),
)).Exec()
}
}
}
// addExtraSpaceIfExist adds a separator
func addExtraSpaceIfExist(str string) string {
if str != "" {
return " " + str
}
return ""
}