-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathentity.go
86 lines (70 loc) · 1.56 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
package mysql
import (
"context"
"errors"
"github.com/go-qbit/model"
mysql "github.com/go-qbit/storage-mysql"
)
var (
ErrNotFound = errors.New("not found")
)
type Fabric struct {
table *mysql.BaseModel
field string
filter FilterFunc
}
type FilterFunc func(id interface{}) model.IExpression
type entity struct {
table *mysql.BaseModel
field string
filter model.IExpression
id interface{}
}
func New(table *mysql.BaseModel, field string, filter FilterFunc) *Fabric {
return &Fabric{
table: table,
field: field,
filter: filter,
}
}
func (f *Fabric) Get(id interface{}) *entity {
return &entity{
table: f.table,
field: f.field,
filter: f.filter(id),
id: id,
}
}
func (e *entity) StartAction(ctx context.Context) (context.Context, error) {
return e.table.GetDb().StartTransaction(ctx)
}
func (e *entity) GetState(ctx context.Context) (uint64, error) {
data, err := e.table.GetAll(ctx, []string{e.field}, model.GetAllOptions{
Filter: e.filter,
Limit: 1,
ForUpdate: true,
})
if err != nil {
return 0, err
}
if data.Len() == 0 {
return 0, ErrNotFound
}
return data.Data()[0][0].(uint64), nil
}
func (e *entity) SetState(ctx context.Context, newState uint64, params ...interface{}) error {
return e.table.Edit(ctx, e.filter, map[string]interface{}{
e.field: newState,
})
}
func (e *entity) EndAction(ctx context.Context, err error) error {
if err != nil {
_, _ = e.table.GetDb().Rollback(ctx)
return err
}
_, err = e.table.GetDb().Commit(ctx)
return err
}
func (e *entity) GetId() interface{} {
return e.id
}