-
Notifications
You must be signed in to change notification settings - Fork 0
/
callbacks.go
73 lines (52 loc) · 1.47 KB
/
callbacks.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
package consistently
import (
"reflect"
"github.com/jinzhu/gorm"
)
const (
tagKeyConsistently = "consistently"
tagValueVersion = "version"
)
func callbackConsistently(scope *gorm.Scope) {
if _, ok := scope.Get("gorm:update_column"); ok {
return
}
if scope.HasError() {
return
}
if scope.Value == nil {
return
}
for _, field := range scope.Fields() {
if val, ok := field.Tag.Lookup(tagKeyConsistently); !(ok && val == tagValueVersion) {
continue
}
saveVersion := field.Field.String()
if saveVersion != "" {
val := reflect.New(scope.IndirectValue().Type())
currentValue := scope.New(val.Interface())
scope.DB().First(currentValue.Value, scope.PrimaryKeyValue())
if scope.HasError() {
return
}
currentField, _ := currentValue.FieldByName(field.Name)
currentVersion := currentField.Field.String()
if currentVersion != saveVersion {
scope.Err(ErrVersionNotValid)
return
}
}
scope.SetColumn(field.Name, string(randASCIIBytes(20)))
return
}
}
// RegisterCallbacks register callback into GORM DB
func RegisterCallbacks(db *gorm.DB) {
callback := db.Callback()
if callback.Create().Get("consistently:before_create") == nil {
callback.Create().Before("gorm:before_create").Register("consistently:before_create", callbackConsistently)
}
if callback.Update().Get("consistently:before_update") == nil {
callback.Update().Before("gorm:before_update").Register("consistently:before_update", callbackConsistently)
}
}