-
Notifications
You must be signed in to change notification settings - Fork 10
/
publish.go
261 lines (218 loc) · 8.16 KB
/
publish.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
package publish
import (
"fmt"
"strings"
"github.com/jinzhu/gorm"
"github.com/qor/admin"
"github.com/qor/qor"
"github.com/qor/qor/resource"
"github.com/qor/qor/utils"
"github.com/qor/worker"
"reflect"
)
const (
// PUBLISHED publish status published
PUBLISHED = false
// DIRTY publish status dirty
DIRTY = true
publishDraftMode = "publish:draft_mode"
publishEvent = "publish:publish_event"
)
type publishInterface interface {
GetPublishStatus() bool
SetPublishStatus(bool)
}
// PublishEventInterface defined publish event itself's interface
type PublishEventInterface interface {
Publish(*gorm.DB) error
Discard(*gorm.DB) error
}
// Status publish status, need to be embedded in your models to get the publish feature
type Status struct {
PublishStatus bool
}
// GetPublishStatus get publish status
func (s Status) GetPublishStatus() bool {
return s.PublishStatus
}
// SetPublishStatus set publish status
func (s *Status) SetPublishStatus(status bool) {
s.PublishStatus = status
}
// ConfigureQorResource configure qor resource for qor admin
func (s Status) ConfigureQorResource(res resource.Resourcer) {
if res, ok := res.(*admin.Resource); ok {
if res.GetMeta("PublishStatus") == nil {
res.IndexAttrs(res.IndexAttrs(), "-PublishStatus")
res.NewAttrs(res.NewAttrs(), "-PublishStatus")
res.EditAttrs(res.EditAttrs(), "-PublishStatus")
res.ShowAttrs(res.ShowAttrs(), "-PublishStatus", false)
}
}
}
// Publish defined a publish struct
type Publish struct {
DB *gorm.DB
SearchHandler func(db *gorm.DB, context *qor.Context) *gorm.DB
WorkerScheduler *worker.Worker
logger LoggerInterface
deleteCallback func(*gorm.Scope)
}
// IsDraftMode check if current db in draft mode
func IsDraftMode(db *gorm.DB) bool {
if draftMode, ok := db.Get(publishDraftMode); ok {
if isDraft, ok := draftMode.(bool); ok && isDraft {
return true
}
}
return false
}
// IsPublishEvent check if current model is a publish event model
func IsPublishEvent(model interface{}) (ok bool) {
if model != nil {
_, ok = reflect.New(utils.ModelType(model)).Interface().(PublishEventInterface)
}
return
}
// IsPublishableModel check if current model is a publishable
func IsPublishableModel(model interface{}) (ok bool) {
if model != nil {
_, ok = reflect.New(utils.ModelType(model)).Interface().(publishInterface)
}
return
}
var injectedJoinTableHandler = map[reflect.Type]bool{}
// New initialize a publish instance
func New(db *gorm.DB) *Publish {
tableHandler := gorm.DefaultTableNameHandler
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
tableName := tableHandler(db, defaultTableName)
if db != nil {
if IsPublishableModel(db.Value) {
// Set join table handler
typ := utils.ModelType(db.Value)
if !injectedJoinTableHandler[typ] {
injectedJoinTableHandler[typ] = true
scope := db.NewScope(db.Value)
for _, field := range scope.GetModelStruct().StructFields {
if many2many := utils.ParseTagOption(field.Tag.Get("gorm"))["MANY2MANY"]; many2many != "" {
db.SetJoinTableHandler(db.Value, field.Name, &publishJoinTableHandler{})
db.AutoMigrate(db.Value)
}
}
}
var forceDraftTable bool
if forceDraft, ok := db.Get("publish:force_draft_table"); ok {
if forceMode, ok := forceDraft.(bool); ok && forceMode {
forceDraftTable = true
}
}
if IsDraftMode(db) || forceDraftTable {
return DraftTableName(tableName)
}
}
}
return tableName
}
db.AutoMigrate(&PublishEvent{})
db.Callback().Create().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
db.Callback().Create().Before("gorm:commit_or_rollback_transaction").
Register("publish:sync_to_production_after_create", syncCreateFromProductionToDraft)
db.Callback().Create().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)
db.Callback().Delete().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
deleteCallback := db.Callback().Delete().Get("gorm:delete")
db.Callback().Delete().Replace("gorm:delete", deleteScope)
db.Callback().Delete().Before("gorm:commit_or_rollback_transaction").
Register("publish:sync_to_production_after_delete", syncDeleteFromProductionToDraft)
db.Callback().Delete().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)
db.Callback().Update().Before("gorm:begin_transaction").Register("publish:set_table_to_draft", setTableAndPublishStatus(true))
db.Callback().Update().Before("gorm:commit_or_rollback_transaction").
Register("publish:sync_to_production", syncUpdateFromProductionToDraft)
db.Callback().Update().Before("gorm:commit_or_rollback_transaction").Register("gorm:create_publish_event", createPublishEvent)
db.Callback().RowQuery().Before("gorm:row_query").Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))
db.Callback().Query().Before("gorm:query").Register("publish:set_table_in_draft_mode", setTableAndPublishStatus(false))
searchHandler := func(db *gorm.DB, context *qor.Context) *gorm.DB {
return db.Unscoped()
}
return &Publish{SearchHandler: searchHandler, DB: db, deleteCallback: deleteCallback, logger: Logger}
}
// DraftTableName get draft table name of passed in string
func DraftTableName(table string) string {
return OriginalTableName(table) + "_draft"
}
// OriginalTableName get original table name of passed in string
func OriginalTableName(table string) string {
return strings.TrimSuffix(table, "_draft")
}
// AutoMigrate run auto migrate in draft tables
func (pb *Publish) AutoMigrate(values ...interface{}) {
for _, value := range values {
tableName := pb.DB.NewScope(value).TableName()
pb.DraftDB().Table(DraftTableName(tableName)).AutoMigrate(value)
}
}
// ProductionDB get db in production mode
func (pb Publish) ProductionDB() *gorm.DB {
return pb.DB.Set(publishDraftMode, false)
}
// DraftDB get db in draft mode
func (pb Publish) DraftDB() *gorm.DB {
return pb.DB.Set(publishDraftMode, true)
}
// Logger set logger that used to print publish logs
func (pb Publish) Logger(l LoggerInterface) *Publish {
return &Publish{
WorkerScheduler: pb.WorkerScheduler,
DB: pb.DB,
logger: l,
deleteCallback: pb.deleteCallback,
}
}
func (pb Publish) newResolver(records ...interface{}) *resolver {
return &resolver{publish: pb, Records: records, DB: pb.DB, Dependencies: map[string]*dependency{}}
}
// Publish publish records
func (pb Publish) Publish(records ...interface{}) {
pb.newResolver(records...).Publish()
}
// Discard discard records
func (pb Publish) Discard(records ...interface{}) {
pb.newResolver(records...).Discard()
}
func (pb Publish) search(db *gorm.DB, res *admin.Resource, ids [][]string) *gorm.DB {
var primaryKeys []string
var primaryValues [][][]interface{}
var scope = db.NewScope(res.Value)
for _, primaryField := range scope.PrimaryFields() {
primaryKeys = append(primaryKeys, fmt.Sprintf("%v.%v", scope.TableName(), primaryField.DBName))
}
for _, id := range ids {
var primaryValue [][]interface{}
for idx, value := range id {
primaryValue = append(primaryValue, []interface{}{primaryKeys[idx], value})
}
primaryValues = append(primaryValues, primaryValue)
}
sql := fmt.Sprintf("%v IN (%v)", toQueryCondition(scope, primaryKeys), toQueryMarks(primaryValues))
return pb.SearchHandler(db, nil).Where(sql, toQueryValues(primaryValues)...)
}
func (pb Publish) searchWithPublishIDs(db *gorm.DB, Admin *admin.Admin, publishIDs []string) (results []interface{}) {
var values = map[string][][]string{}
for _, publishID := range publishIDs {
if primaryValues := strings.Split(publishID, "__"); len(primaryValues) >= 2 {
name := primaryValues[0]
values[name] = append(values[name], primaryValues[1:])
}
}
for name, value := range values {
res := Admin.GetResource(name)
result := res.NewSlice()
if pb.search(db, res, value).Find(result).Error == nil {
resultValues := reflect.Indirect(reflect.ValueOf(result))
for i := 0; i < resultValues.Len(); i++ {
results = append(results, resultValues.Index(i).Interface())
}
}
}
return
}