-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoperation.go
101 lines (87 loc) · 2.13 KB
/
operation.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
package nrgorm
import "strings"
import "github.com/jinzhu/gorm"
import "fmt"
type operation int
const (
operationUnknown operation = iota
operationQuery
operationCreate
operationUpdate
operationDelete
)
const (
namespace = "nrgorm"
)
func operations() []operation {
return []operation{
operationQuery,
operationCreate,
operationUpdate,
operationDelete,
operationUnknown,
}
}
func (op operation) String() string {
switch op {
case operationQuery:
return "SELECT"
case operationCreate:
return "INSERT"
case operationUpdate:
return "UPDATE"
case operationDelete:
return "DELETE"
default:
return ""
}
}
func (op operation) Kind() string {
switch op {
case operationQuery:
return "query"
case operationCreate:
return "create"
case operationUpdate:
return "update"
case operationDelete:
return "delete"
default:
return "row_query"
}
}
func (op operation) Name(sql string) string {
if op == operationUnknown {
return strings.Split(sql, " ")[0]
}
return op.String()
}
func (op operation) callbackProcessor(db *gorm.DB) *gorm.CallbackProcessor {
switch op {
case operationQuery:
return db.Callback().Query()
case operationCreate:
return db.Callback().Create()
case operationUpdate:
return db.Callback().Update()
case operationDelete:
return db.Callback().Delete()
default:
return db.Callback().RowQuery()
}
}
func (op operation) registerBeforeCallback(db *gorm.DB, dbName string, callback func(*gorm.Scope)) {
op.callbackProcessor(db).Before(op.callbackName()).Register(op.beforeCallbackName(dbName), callback)
}
func (op operation) registerAfterCallback(db *gorm.DB, dbName string, callback func(*gorm.Scope)) {
op.callbackProcessor(db).After(op.callbackName()).Register(op.afterCallbackName(dbName), callback)
}
func (op operation) callbackName() string {
return fmt.Sprintf("gorm:%s", op.Kind())
}
func (op operation) beforeCallbackName(dbName string) string {
return fmt.Sprintf("%s:%s:%s_%s", namespace, dbName, op.callbackName(), "before")
}
func (op operation) afterCallbackName(dbName string) string {
return fmt.Sprintf("%s:%s:%s_%s", namespace, dbName, op.callbackName(), "after")
}