-
Notifications
You must be signed in to change notification settings - Fork 39
/
model.go
332 lines (275 loc) · 7.67 KB
/
model.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
package gosql
import (
"context"
"fmt"
"log"
"reflect"
"strconv"
)
var (
mapper = NewReflectMapper("db")
// Insert database automatically updates fields
AUTO_CREATE_TIME_FIELDS = []string{
"create_time",
"create_at",
"created_at",
"update_time",
"update_at",
"updated_at",
}
// Update database automatically updates fields
AUTO_UPDATE_TIME_FIELDS = []string{
"update_time",
"update_at",
"updated_at",
}
)
// Model interface
type IModel interface {
TableName() string
PK() string
}
type Builder struct {
model interface{}
modelReflectValue reflect.Value
modelEntity IModel
db *DB
ctx context.Context
SQLBuilder
modelWrapper *ModelWrapper
}
// Model construct SQL from Struct
func Model(model interface{}) *Builder {
return &Builder{
model: model,
db: &DB{database: Sqlx(defaultLink)},
}
}
// Model construct SQL from Struct with context
func (b *Builder) Model(model interface{}) *Builder {
b.model = model
return b
}
// Model construct SQL from Struct with context
func WithContext(ctx context.Context) *Builder {
w := Use(defaultLink)
return &Builder{db: w, SQLBuilder: SQLBuilder{dialect: newDialect(w.DriverName())}, ctx: ctx}
}
// ShowSQL output single sql
func (b *Builder) ShowSQL() *Builder {
b.db.logging = true
return b
}
func (b *Builder) initModel() {
if b.model == nil {
log.Panicf("model argument must not nil")
} else if m, ok := b.model.(IModel); ok {
b.modelEntity = m
b.table = m.TableName()
b.modelReflectValue = reflect.ValueOf(m)
b.dialect = newDialect(b.db.DriverName())
} else {
value := reflect.ValueOf(b.model)
if value.Kind() != reflect.Ptr {
log.Panicf("model argument must pass a pointer, not a value %#v", b.model)
}
if value.IsNil() {
log.Panicf("model argument cannot be nil pointer passed")
}
tp := reflect.Indirect(value).Type()
// If b.model is *interface{} have to do a second Elem
//
// For example,
// var m interface{}
// mm := make([]*Model,0)
// mm = append(mm, &Model{Id:1})
// m = mm
// reflect.Indirect(reflect.ValueOf(&m)).Elem().Type().Kind() == reflect.Slice
if tp.Kind() == reflect.Interface {
tp = reflect.Indirect(value).Elem().Type()
}
if tp.Kind() != reflect.Slice {
log.Panicf("model argument must slice, but get %#v", b.model)
}
tpEl := tp.Elem()
// Compatible with []*Struct or []Struct
if tpEl.Kind() == reflect.Ptr {
tpEl = tpEl.Elem()
}
if m, ok := reflect.New(tpEl).Interface().(IModel); ok {
b.modelEntity = m
b.table = m.TableName()
b.modelReflectValue = reflect.ValueOf(m)
b.dialect = newDialect(b.db.DriverName())
} else {
log.Panicf("model argument must implementation IModel interface or slice []IModel and pointer,but get %#v", b.model)
}
}
}
// Hint is set TDDL "/*+TDDL:slave()*/"
func (b *Builder) Hint(hint string) *Builder {
b.hint = hint
return b
}
// ForceIndex
func (b *Builder) ForceIndex(i string) *Builder {
b.forceIndex = i
return b
}
// Where for example Where("id = ? and name = ?",1,"test")
func (b *Builder) Where(str string, args ...interface{}) *Builder {
b.SQLBuilder.Where(str, args...)
return b
}
// Select filter column
func (b *Builder) Select(fields string) *Builder {
b.fields = fields
return b
}
// Limit
func (b *Builder) Limit(i int) *Builder {
b.limit = strconv.Itoa(i)
return b
}
// Offset
func (b *Builder) Offset(i int) *Builder {
b.offset = strconv.Itoa(i)
return b
}
// OrderBy for example "id desc"
func (b *Builder) OrderBy(str string) *Builder {
b.order = str
return b
}
func (b *Builder) reflectModel(autoTime []string) map[string]reflect.Value {
fields := mapper.FieldMap(b.modelReflectValue)
if autoTime != nil {
structAutoTime(fields, autoTime)
}
return fields
}
// Relation association table builder handle
func (b *Builder) Relation(fieldName string, fn BuilderChainFunc) *Builder {
if b.db.RelationMap == nil {
b.db.RelationMap = make(map[string]BuilderChainFunc)
}
b.db.RelationMap[fieldName] = fn
return b
}
// All get data row from to Struct
func (b *Builder) Get(zeroValues ...string) (err error) {
b.initModel()
m := zeroValueFilter(b.reflectModel(nil), zeroValues)
// If where is empty, the primary key where condition is generated automatically
b.generateWhere(m)
if b.modelWrapper != nil {
return b.db.Get(b.modelWrapper, b.queryString(), b.args...)
}
return b.db.Get(b.model, b.queryString(), b.args...)
}
// All get data rows from to Struct
func (b *Builder) All() (err error) {
b.initModel()
if b.modelWrapper != nil {
return b.db.Select(b.modelWrapper, b.queryString(), b.args...)
}
return b.db.Select(b.model, b.queryString(), b.args...)
}
// Create data from to Struct
func (b *Builder) Create() (lastInsertId int64, err error) {
b.initModel()
hook := NewHook(b.ctx, b.db)
hook.callMethod("BeforeChange", b.modelReflectValue)
hook.callMethod("BeforeCreate", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
fields := b.reflectModel(AUTO_CREATE_TIME_FIELDS)
m := structToMap(fields)
result, err := b.db.Exec(b.insertString(m), b.args...)
if err != nil {
return 0, err
}
hook.callMethod("AfterCreate", b.modelReflectValue)
hook.callMethod("AfterChange", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
lastId, err := result.LastInsertId()
if err != nil {
return 0, err
}
if v, ok := fields[b.modelEntity.PK()]; ok {
fillPrimaryKey(v, lastId)
}
return lastId, err
}
func (b *Builder) generateWhere(m map[string]interface{}) {
for k, v := range m {
b.Where(fmt.Sprintf("%s=%s", k, b.dialect.Placeholder()), v)
}
}
func (b *Builder) generateWhereForPK(m map[string]interface{}) {
pk := b.modelEntity.PK()
pval, has := m[pk]
if b.where == "" && has {
b.Where(fmt.Sprintf("%s=%s", pk, b.dialect.Placeholder()), pval)
delete(m, pk)
}
}
// gosql.Model(&User{Id:1,Status:0}).Update("status")
func (b *Builder) Update(zeroValues ...string) (affected int64, err error) {
b.initModel()
hook := NewHook(b.ctx, b.db)
hook.callMethod("BeforeChange", b.modelReflectValue)
hook.callMethod("BeforeUpdate", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
fields := b.reflectModel(AUTO_UPDATE_TIME_FIELDS)
m := zeroValueFilter(fields, zeroValues)
// If where is empty, the primary key where condition is generated automatically
b.generateWhereForPK(m)
result, err := b.db.Exec(b.updateString(m), b.args...)
if err != nil {
return 0, err
}
hook.callMethod("AfterUpdate", b.modelReflectValue)
hook.callMethod("AfterChange", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
return result.RowsAffected()
}
// gosql.Model(&User{Id:1}).Delete()
func (b *Builder) Delete(zeroValues ...string) (affected int64, err error) {
b.initModel()
hook := NewHook(b.ctx, b.db)
hook.callMethod("BeforeChange", b.modelReflectValue)
hook.callMethod("BeforeDelete", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
m := zeroValueFilter(b.reflectModel(nil), zeroValues)
// If where is empty, the primary key where condition is generated automatically
b.generateWhere(m)
result, err := b.db.Exec(b.deleteString(), b.args...)
if err != nil {
return 0, err
}
hook.callMethod("AfterDelete", b.modelReflectValue)
hook.callMethod("AfterChange", b.modelReflectValue)
if hook.HasError() {
return 0, hook.Error()
}
return result.RowsAffected()
}
// gosql.Model(&User{}).Where("status = 0").Count()
func (b *Builder) Count(zeroValues ...string) (num int64, err error) {
b.initModel()
m := zeroValueFilter(b.reflectModel(nil), zeroValues)
// If where is empty, the primary key where condition is generated automatically
b.generateWhere(m)
err = b.db.Get(&num, b.countString(), b.args...)
return num, err
}