-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathentity.go
548 lines (458 loc) · 12.2 KB
/
entity.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package entity
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"sync"
"time"
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
)
const (
// EventUnknown 未定义事件
EventUnknown Event = iota
// EventBeforeInsert before insert entity
EventBeforeInsert
// EventAfterInsert after insert entity
EventAfterInsert
// EventBeforeUpdate before update entity
EventBeforeUpdate
// EventAfterUpdate after update entity
EventAfterUpdate
// EventBeforeDelete before delete entity
EventBeforeDelete
// EventAfterDelete after delete entity
EventAfterDelete
)
var (
// ErrConflict 发生了数据冲突
ErrConflict = errors.New("record conflict")
// ErrNotFound 记录未找到错误
ErrNotFound = errors.New("record not found")
// ReadTimeout 读取entity数据的默认超时时间
ReadTimeout = 3 * time.Second
// WriteTimeout 写入entity数据的默认超时时间
WriteTimeout = 3 * time.Second
entities = &sync.Map{}
mapper = reflectx.NewMapper("db")
)
// Event 存储事件
type Event int
// Entity 实体对象接口
type Entity interface {
TableName() string
}
// EventHook 事件风格钩子
type EventHook interface {
OnEntityEvent(ctx context.Context, ev Event) error
}
// BeforeInsertHook 在插入前调用
type BeforeInsertHook interface {
BeforeInsert(ctx context.Context) error
}
// AfterInsertHook 在插入后调用
type AfterInsertHook interface {
AfterInsert(ctx context.Context) error
}
// BeforeUpdateHook 在更新前调用
type BeforeUpdateHook interface {
BeforeUpdate(ctx context.Context) error
}
// AfterUpdateHook 在更新后调用
type AfterUpdateHook interface {
AfterUpdate(ctx context.Context) error
}
// BeforeDeleteHook 在删除前调用
type BeforeDeleteHook interface {
BeforeDelete(ctx context.Context) error
}
// AfterDeleteHook 在删除后调用
type AfterDeleteHook interface {
AfterDelete(ctx context.Context) error
}
// Column 字段信息
type Column struct {
StructField string
DBField string
PrimaryKey bool
AutoIncrement bool
RefuseUpdate bool
ReturningInsert bool
ReturningUpdate bool
}
func (c Column) String() string {
return c.DBField
}
// Metadata 元数据
type Metadata struct {
Type reflect.Type
TableName string
Columns []Column
PrimaryKeys []Column
hasReturningInsert bool
hasReturningUpdate bool
}
// NewMetadata 构造实体对象元数据
func NewMetadata(ent Entity) (*Metadata, error) {
columns := getColumns(ent)
md := &Metadata{
Type: reflectx.Deref(reflect.TypeOf(ent)),
TableName: ent.TableName(),
Columns: columns,
PrimaryKeys: []Column{},
}
if len(md.Columns) == 0 {
return nil, fmt.Errorf("empty entity %q", md.Type)
}
for _, col := range md.Columns {
if col.ReturningInsert {
md.hasReturningInsert = true
}
if col.ReturningUpdate {
md.hasReturningUpdate = true
}
if col.PrimaryKey {
md.PrimaryKeys = append(md.PrimaryKeys, col)
}
}
if len(md.PrimaryKeys) == 0 {
return nil, fmt.Errorf("undefined entity %q primary key", md.Type)
}
return md, nil
}
func getMetadata(ent Entity) (*Metadata, error) {
t := reflectx.Deref(reflect.TypeOf(ent))
if v, ok := entities.Load(t); ok {
return v.(*Metadata), nil
}
md, err := NewMetadata(ent)
if err != nil {
return nil, err
}
entities.Store(t, md)
return md, nil
}
func getColumns(ent Entity) []Column { // revive:disable-line
sm := mapper.TypeMap(reflectx.Deref(reflect.TypeOf(ent)))
cols := []Column{}
for _, fi := range getFields(sm.Tree) {
col := Column{
StructField: fi.Field.Name,
DBField: fi.Name,
}
for key := range fi.Options {
switch key {
case "primaryKey", "primary_key":
col.PrimaryKey = true
col.RefuseUpdate = true
case "refuseUpdate", "refuse_update":
col.RefuseUpdate = true
case "returning":
col.ReturningInsert = true
col.ReturningUpdate = true
col.RefuseUpdate = true
case "returningInsert", "returning_insert":
col.ReturningInsert = true
case "returningUpdate", "returning_update":
col.ReturningUpdate = true
col.RefuseUpdate = true
case "autoIncrement", "auto_increment":
col.AutoIncrement = true
col.RefuseUpdate = true
}
}
cols = append(cols, col)
}
return cols
}
// 从反射信息内,解析字段属性
func getFields(node *reflectx.FieldInfo) []*reflectx.FieldInfo {
fields := []*reflectx.FieldInfo{}
for _, fi := range node.Children {
if fi == nil {
continue
}
if fi.Embedded {
fields = append(fields, getFields(fi)...)
} else {
fields = append(fields, fi)
}
}
// root node
if node.Parent == nil {
// replace duplicate name
filter := map[string]*reflectx.FieldInfo{}
for _, v := range fields {
filter[v.Name] = v
}
fields = fields[:0]
for _, v := range filter {
fields = append(fields, v)
}
}
return fields
}
// Load 从数据库载入entity
func Load(ctx context.Context, ent Entity, db DB) error {
ctx, cancel := context.WithTimeout(ctx, ReadTimeout)
defer cancel()
cv, cacheable := ent.(Cacheable)
if cacheable {
if loaded, err := loadCache(ctx, cv); err != nil {
return fmt.Errorf("load from cache, %w", err)
} else if loaded {
return nil
}
}
if err := doLoad(ctx, ent, db); err != nil {
return err
}
if cacheable {
if err := SaveCache(ctx, cv); err != nil {
return fmt.Errorf("save cache, %w", err)
}
}
return nil
}
// Insert 插入新entity
func Insert(ctx context.Context, ent Entity, db DB) (int64, error) {
ctx, cancel := context.WithTimeout(ctx, WriteTimeout)
defer cancel()
if err := beforeInsert(ctx, ent); err != nil {
return 0, fmt.Errorf("before insert, %w", err)
}
lastID, err := doInsert(ctx, ent, db)
if err != nil {
if isConflictError(err, dbDriver(db)) {
return 0, ErrConflict
}
return 0, err
}
if err := afterInsert(ctx, ent); err != nil {
return 0, fmt.Errorf("after insert, %w", err)
}
return lastID, nil
}
// Update 更新entity
func Update(ctx context.Context, ent Entity, db DB) error {
ctx, cancel := context.WithTimeout(ctx, WriteTimeout)
defer cancel()
if err := beforeUpdate(ctx, ent); err != nil {
return fmt.Errorf("before update, %w", err)
}
if err := doUpdate(ctx, ent, db); err != nil {
if isConflictError(err, dbDriver(db)) {
return ErrConflict
}
return err
}
if v, ok := ent.(Cacheable); ok {
if err := DeleteCache(ctx, v); err != nil {
return fmt.Errorf("delete cache, %w", err)
}
}
if err := afterUpdate(ctx, ent); err != nil {
return fmt.Errorf("after update, %w", err)
}
return nil
}
// Delete 删除entity
func Delete(ctx context.Context, ent Entity, db DB) error {
ctx, cancel := context.WithTimeout(ctx, WriteTimeout)
defer cancel()
if err := beforeDelete(ctx, ent); err != nil {
return fmt.Errorf("before delete, %w", err)
}
if err := doDelete(ctx, ent, db); err != nil {
return err
}
if v, ok := ent.(Cacheable); ok {
if err := DeleteCache(ctx, v); err != nil {
return fmt.Errorf("delete cache, %w", err)
}
}
if err := afterDelete(ctx, ent); err != nil {
return fmt.Errorf("after delete, %w", err)
}
return nil
}
// PrepareInsertStatement is a prepared insert statement for entity
type PrepareInsertStatement struct {
md *Metadata
stmt *sqlx.NamedStmt
dbDriver string
}
// PrepareInsert returns a prepared insert statement for Entity
func PrepareInsert(ctx context.Context, ent Entity, db DB) (*PrepareInsertStatement, error) {
md, err := getMetadata(ent)
if err != nil {
return nil, fmt.Errorf("get metadata, %w", err)
}
query := getStatement(commandInsert, md, dbDriver(db))
stmt, err := db.PrepareNamedContext(ctx, query)
if err != nil {
return nil, err
}
return &PrepareInsertStatement{
md: md,
stmt: stmt,
dbDriver: dbDriver(db),
}, nil
}
// Close closes the prepared statement
func (pis *PrepareInsertStatement) Close() error {
return pis.stmt.Close()
}
// ExecContext executes a prepared insert statement using the Entity passed.
func (pis *PrepareInsertStatement) ExecContext(ctx context.Context, ent Entity) (lastID int64, err error) {
ctx, cancel := context.WithTimeout(ctx, WriteTimeout)
defer cancel()
if err := beforeInsert(ctx, ent); err != nil {
return 0, fmt.Errorf("before insert, %w", err)
}
lastID, err = pis.execContext(ctx, ent)
if err != nil {
if isConflictError(err, pis.dbDriver) {
return 0, ErrConflict
}
return 0, err
}
if err := afterInsert(ctx, ent); err != nil {
return 0, fmt.Errorf("after insert, %w", err)
}
return lastID, nil
}
func (pis *PrepareInsertStatement) execContext(ctx context.Context, ent Entity) (lastID int64, err error) {
if pis.md.hasReturningInsert {
err := pis.stmt.QueryRowxContext(ctx, ent).StructScan(ent)
return 0, err
}
result, err := pis.stmt.ExecContext(ctx, ent)
if err != nil {
return 0, err
} else if pis.dbDriver == driverPostgres {
// postgresql不支持LastInsertId特性
return 0, nil
}
lastID, err = result.LastInsertId()
if err != nil {
return 0, fmt.Errorf("get last insert id, %w", err)
}
return lastID, nil
}
// PrepareUpdateStatement is a prepared update statement for entity
type PrepareUpdateStatement struct {
md *Metadata
stmt *sqlx.NamedStmt
dbDriver string
}
// PrepareUpdate returns a prepared update statement for Entity
func PrepareUpdate(ctx context.Context, ent Entity, db DB) (*PrepareUpdateStatement, error) {
md, err := getMetadata(ent)
if err != nil {
return nil, fmt.Errorf("get metadata, %w", err)
}
driver := dbDriver(db)
query := getStatement(commandUpdate, md, driver)
stmt, err := db.PrepareNamedContext(ctx, query)
if err != nil {
return nil, err
}
return &PrepareUpdateStatement{
md: md,
stmt: stmt,
dbDriver: driver,
}, nil
}
// Close closes the prepared statement
func (pus *PrepareUpdateStatement) Close() error {
return pus.stmt.Close()
}
// ExecContext executes a prepared update statement using the Entity passed.
func (pus *PrepareUpdateStatement) ExecContext(ctx context.Context, ent Entity) error {
ctx, cancel := context.WithTimeout(ctx, WriteTimeout)
defer cancel()
if err := beforeUpdate(ctx, ent); err != nil {
return fmt.Errorf("before update, %w", err)
}
if err := pus.execContext(ctx, ent); err != nil {
if isConflictError(err, pus.dbDriver) {
return ErrConflict
}
return err
}
if v, ok := ent.(Cacheable); ok {
if err := DeleteCache(ctx, v); err != nil {
return fmt.Errorf("delete cache, %w", err)
}
}
if err := afterUpdate(ctx, ent); err != nil {
return fmt.Errorf("after update, %w", err)
}
return nil
}
func (pus *PrepareUpdateStatement) execContext(ctx context.Context, ent Entity) error {
if pus.md.hasReturningUpdate {
return pus.stmt.QueryRowxContext(ctx, ent).StructScan(ent)
}
result, err := pus.stmt.ExecContext(ctx, ent)
if err != nil {
return err
}
if n, err := result.RowsAffected(); err != nil {
return fmt.Errorf("get affected rows, %w", err)
} else if n == 0 {
return sql.ErrNoRows
}
return nil
}
func beforeInsert(ctx context.Context, ent Entity) error {
if v, ok := ent.(BeforeInsertHook); ok {
return v.BeforeInsert(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventBeforeInsert)
}
return nil
}
func afterInsert(ctx context.Context, ent Entity) error {
if v, ok := ent.(AfterInsertHook); ok {
return v.AfterInsert(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventAfterInsert)
}
return nil
}
func beforeUpdate(ctx context.Context, ent Entity) error {
if v, ok := ent.(BeforeUpdateHook); ok {
return v.BeforeUpdate(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventBeforeUpdate)
}
return nil
}
func afterUpdate(ctx context.Context, ent Entity) error {
if v, ok := ent.(AfterUpdateHook); ok {
return v.AfterUpdate(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventAfterUpdate)
}
return nil
}
func beforeDelete(ctx context.Context, ent Entity) error {
if v, ok := ent.(BeforeDeleteHook); ok {
return v.BeforeDelete(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventBeforeDelete)
}
return nil
}
func afterDelete(ctx context.Context, ent Entity) error {
if v, ok := ent.(AfterDeleteHook); ok {
return v.AfterDelete(ctx)
} else if v, ok := ent.(EventHook); ok {
return v.OnEntityEvent(ctx, EventAfterDelete)
}
return nil
}