forked from jinzhu/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.go
302 lines (254 loc) · 6.89 KB
/
scope.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
package gorm
import (
"errors"
"fmt"
"github.com/jinzhu/gorm/dialect"
"go/ast"
"strings"
"time"
"reflect"
"regexp"
)
type Scope struct {
Value interface{}
Search *search
Sql string
SqlVars []interface{}
db *DB
startedTransaction bool
}
func (db *DB) NewScope(value interface{}) *Scope {
db.Value = value
return &Scope{db: db, Search: db.search, Value: value}
}
func (scope *Scope) callCallbacks(funcs []*func(s *Scope)) *Scope {
for _, f := range funcs {
(*f)(scope)
}
return scope
}
func (scope *Scope) New(value interface{}) *Scope {
return &Scope{db: scope.db.parent, Search: &search{}, Value: value}
}
func (scope *Scope) NewDB() *DB {
return scope.db.new()
}
func (scope *Scope) DB() sqlCommon {
return scope.db.db
}
func (scope *Scope) Dialect() dialect.Dialect {
return scope.db.parent.dialect
}
func (scope *Scope) Err(err error) error {
if err != nil {
scope.db.err(err)
}
return err
}
func (scope *Scope) HasError() bool {
return scope.db.hasError()
}
func (scope *Scope) PrimaryKey() string {
return "id"
}
func (scope *Scope) PrimaryKeyZero() bool {
return isBlank(reflect.ValueOf(scope.PrimaryKeyValue()))
}
func (scope *Scope) PrimaryKeyValue() interface{} {
data := reflect.Indirect(reflect.ValueOf(scope.Value))
if data.Kind() == reflect.Struct {
if field := data.FieldByName(snakeToUpperCamel(scope.PrimaryKey())); field.IsValid() {
return field.Interface()
}
}
return 0
}
func (scope *Scope) HasColumn(name string) bool {
data := reflect.Indirect(reflect.ValueOf(scope.Value))
if data.Kind() == reflect.Struct {
return data.FieldByName(name).IsValid()
} else if data.Kind() == reflect.Slice {
return reflect.New(data.Type().Elem()).Elem().FieldByName(name).IsValid()
}
return false
}
func (scope *Scope) SetColumn(column string, value interface{}) {
data := reflect.Indirect(reflect.ValueOf(scope.Value))
setFieldValue(data.FieldByName(snakeToUpperCamel(column)), value)
}
func (scope *Scope) CallMethod(name string) {
if fm := reflect.ValueOf(scope.Value).MethodByName(name); fm.IsValid() {
fi := fm.Interface()
if f, ok := fi.(func()); ok {
f()
} else if f, ok := fi.(func(s *Scope)); ok {
f(scope)
} else if f, ok := fi.(func(s *DB)); ok {
f(scope.db.new())
} else if f, ok := fi.(func() error); ok {
scope.Err(f())
} else if f, ok := fi.(func(s *Scope) error); ok {
scope.Err(f(scope))
} else if f, ok := fi.(func(s *DB) error); ok {
scope.Err(f(scope.db.new()))
} else {
scope.Err(errors.New(fmt.Sprintf("unsupported function %v", name)))
}
}
}
func (scope *Scope) AddToVars(value interface{}) string {
scope.SqlVars = append(scope.SqlVars, value)
return scope.Dialect().BinVar(len(scope.SqlVars))
}
func (scope *Scope) TableName() string {
if len(scope.Search.tableName) > 0 {
return scope.Search.tableName
} else {
data := reflect.Indirect(reflect.ValueOf(scope.Value))
if data.Kind() == reflect.Slice {
data = reflect.New(data.Type().Elem()).Elem()
}
if fm := data.MethodByName("TableName"); fm.IsValid() {
if v := fm.Call([]reflect.Value{}); len(v) > 0 {
if result, ok := v[0].Interface().(string); ok {
return result
}
}
}
str := toSnake(data.Type().Name())
if !scope.db.parent.singularTable {
pluralMap := map[string]string{"ch": "ches", "ss": "sses", "sh": "shes", "day": "days", "y": "ies", "x": "xes", "s?": "s"}
for key, value := range pluralMap {
reg := regexp.MustCompile(key + "$")
if reg.MatchString(str) {
return reg.ReplaceAllString(str, value)
}
}
}
return str
}
}
func (s *Scope) CombinedConditionSql() string {
return s.joinsSql() + s.whereSql() + s.groupSql() + s.havingSql() + s.orderSql() + s.limitSql() + s.offsetSql()
}
func (scope *Scope) SqlTagForField(field *Field) (tag string) {
value := field.Value
reflect_value := reflect.ValueOf(value)
if field.IsScanner() {
value = reflect_value.Field(0).Interface()
}
switch reflect_value.Kind() {
case reflect.Slice:
if _, ok := value.([]byte); !ok {
return
}
case reflect.Struct:
if !field.IsTime() && !field.IsScanner() {
return
}
}
if tag = field.Tag; len(tag) == 0 && tag != "-" {
if field.isPrimaryKey {
tag = scope.Dialect().PrimaryKeyTag(value, field.Size)
} else {
tag = scope.Dialect().SqlTag(value, field.Size)
}
if len(field.AddationalTag) > 0 {
tag = tag + " " + field.AddationalTag
}
}
return
}
func (scope *Scope) Fields() []*Field {
indirect_value := reflect.Indirect(reflect.ValueOf(scope.Value))
fields := []*Field{}
if !indirect_value.IsValid() {
return fields
}
scope_typ := indirect_value.Type()
for i := 0; i < scope_typ.NumField(); i++ {
field_struct := scope_typ.Field(i)
if field_struct.Anonymous || !ast.IsExported(field_struct.Name) {
continue
}
var field Field
field.Name = field_struct.Name
field.DBName = toSnake(field_struct.Name)
value := indirect_value.FieldByName(field_struct.Name)
field.Value = value.Interface()
field.IsBlank = isBlank(value)
tag, addational_tag, size := parseSqlTag(field_struct.Tag.Get(scope.db.parent.tagIdentifier))
field.Tag = tag
field.AddationalTag = addational_tag
field.Size = size
field.SqlTag = scope.SqlTagForField(&field)
if tag == "-" {
field.IsIgnored = true
}
// parse association
elem := reflect.Indirect(value)
typ := elem.Type()
switch elem.Kind() {
case reflect.Slice:
typ = typ.Elem()
if _, ok := field.Value.([]byte); !ok {
foreignKey := scope_typ.Name() + "Id"
if reflect.New(typ).Elem().FieldByName(foreignKey).IsValid() {
field.ForeignKey = foreignKey
}
field.AfterAssociation = true
}
case reflect.Struct:
if !field.IsTime() && !field.IsScanner() {
if scope.HasColumn(field.Name + "Id") {
field.ForeignKey = field.Name + "Id"
field.BeforeAssociation = true
} else {
foreignKey := scope_typ.Name() + "Id"
if reflect.New(typ).Elem().FieldByName(foreignKey).IsValid() {
field.ForeignKey = foreignKey
}
field.AfterAssociation = true
}
}
}
fields = append(fields, &field)
}
return fields
}
func (scope *Scope) Raw(sql string) {
scope.Sql = strings.Replace(sql, "$$", "?", -1)
}
func (scope *Scope) Exec() {
if !scope.HasError() {
_, err := scope.DB().Exec(scope.Sql, scope.SqlVars...)
scope.Err(err)
}
}
func (scope *Scope) Trace(t time.Time) {
if len(scope.Sql) > 0 {
scope.db.slog(scope.Sql, t, scope.SqlVars...)
}
}
func (scope *Scope) Begin() *Scope {
if db, ok := scope.DB().(sqlDb); ok {
if tx, err := db.Begin(); err == nil {
scope.db.db = interface{}(tx).(sqlCommon)
scope.startedTransaction = true
}
}
return scope
}
func (scope *Scope) CommitOrRollback() *Scope {
if scope.startedTransaction {
if db, ok := scope.db.db.(sqlTx); ok {
if scope.HasError() {
db.Rollback()
} else {
db.Commit()
}
scope.db.db = scope.db.parent.db
}
}
return scope
}