forked from qor/qor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callbacks.go
106 lines (93 loc) · 2.6 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
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
package publish
import (
"fmt"
"github.com/jinzhu/gorm"
)
func isDraftMode(scope *gorm.Scope) bool {
if draftMode, ok := scope.Get("publish:draft_mode"); ok {
if isDraft, ok := draftMode.(bool); ok && isDraft {
return true
}
}
return false
}
func setTableAndPublishStatus(ensureDraftMode bool) func(*gorm.Scope) {
return func(scope *gorm.Scope) {
if scope.Value == nil {
return
}
if isPublishableModel(scope.Value) {
scope.InstanceSet("publish:supported_model", true)
if ensureDraftMode {
scope.Set("publish:force_draft_mode", true)
scope.Search.Table(draftTableName(scope.TableName()))
// Only set publish status when updating data from draft tables
if isDraftMode(scope) {
if attrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
updateAttrs := attrs.(map[string]interface{})
updateAttrs["publish_status"] = DIRTY
scope.InstanceSet("gorm:update_attrs", updateAttrs)
} else {
scope.SetColumn("PublishStatus", DIRTY)
}
}
}
}
}
}
func getModeAndNewScope(scope *gorm.Scope) (isProduction bool, clone *gorm.Scope) {
if draftMode, ok := scope.Get("publish:draft_mode"); !ok || !draftMode.(bool) {
if _, ok := scope.InstanceGet("publish:supported_model"); ok {
table := originalTableName(scope.TableName())
clone := scope.New(scope.Value)
clone.Search.Table(table)
return true, clone
}
}
return false, nil
}
func syncToProductionAfterCreate(scope *gorm.Scope) {
if !scope.HasError() {
if ok, clone := getModeAndNewScope(scope); ok {
gorm.Create(clone)
}
}
}
func syncToProductionAfterUpdate(scope *gorm.Scope) {
if !scope.HasError() {
if ok, clone := getModeAndNewScope(scope); ok {
if updateAttrs, ok := scope.InstanceGet("gorm:update_attrs"); ok {
table := originalTableName(scope.TableName())
clone.Search = scope.Search
clone.Search.Table(table)
clone.InstanceSet("gorm:update_attrs", updateAttrs)
}
gorm.Update(clone)
}
}
}
func syncToProductionAfterDelete(scope *gorm.Scope) {
if !scope.HasError() {
if ok, clone := getModeAndNewScope(scope); ok {
gorm.Delete(clone)
}
}
}
func deleteScope(scope *gorm.Scope) {
if !scope.HasError() {
_, supportedModel := scope.InstanceGet("publish:supported_model")
isDraftMode, ok := scope.Get("publish:draft_mode")
if supportedModel && (ok && isDraftMode.(bool)) {
scope.Raw(
fmt.Sprintf("UPDATE %v SET deleted_at=%v, publish_status=%v %v",
scope.QuotedTableName(),
scope.AddToVars(gorm.NowFunc()),
scope.AddToVars(DIRTY),
scope.CombinedConditionSql(),
))
scope.Exec()
} else {
gorm.Delete(scope)
}
}
}