/
resolver.go
344 lines (293 loc) · 12.2 KB
/
resolver.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package publish
import (
"database/sql"
"fmt"
"reflect"
"strings"
"github.com/jinzhu/gorm"
)
type resolver struct {
Records []interface{}
Dependencies map[string]*dependency
DB *gorm.DB
}
type dependency struct {
Type reflect.Type
ManyToManyRelations []*gorm.Relationship
PrimaryValues [][]interface{}
}
func includeValue(value []interface{}, values [][]interface{}) bool {
for _, v := range values {
if fmt.Sprintf("%v", v) == fmt.Sprintf("%v", value) {
return true
}
}
return false
}
func (resolver *resolver) AddDependency(dep *dependency) {
name := dep.Type.String()
var newPrimaryKeys [][]interface{}
// append primary keys to dependency
if d, ok := resolver.Dependencies[name]; ok {
for _, primaryKey := range dep.PrimaryValues {
if !includeValue(primaryKey, d.PrimaryValues) {
newPrimaryKeys = append(newPrimaryKeys, primaryKey)
d.PrimaryValues = append(d.PrimaryValues, primaryKey)
}
}
} else {
resolver.Dependencies[name] = dep
newPrimaryKeys = dep.PrimaryValues
}
if len(newPrimaryKeys) > 0 {
resolver.GetDependencies(dep, newPrimaryKeys)
}
}
func (resolver *resolver) GetDependencies(dep *dependency, primaryKeys [][]interface{}) {
value := reflect.New(dep.Type)
fromScope := resolver.DB.NewScope(value.Interface())
draftDB := resolver.DB.Set("publish:draft_mode", true).Unscoped()
for _, field := range fromScope.Fields() {
if relationship := field.Relationship; relationship != nil {
if isPublishableModel(field.Field.Interface()) {
toType := modelType(field.Field.Interface())
toScope := draftDB.NewScope(reflect.New(toType).Interface())
draftTable := draftTableName(toScope.TableName())
var dependencyKeys [][]interface{}
var rows *sql.Rows
var err error
if relationship.Kind == "belongs_to" || relationship.Kind == "has_many" {
sql := fmt.Sprintf("%v IN (?) and publish_status = ?", relationship.ForeignDBName)
rows, err = draftDB.Table(draftTable).Select(toScope.PrimaryKey()).Where(sql, primaryKeys, DIRTY).Rows()
} else if relationship.Kind == "has_one" {
fromTable := fromScope.TableName()
fromPrimaryKey := fromScope.PrimaryKey()
toTable := toScope.TableName()
toPrimaryKey := toScope.PrimaryKey()
sql := fmt.Sprintf("%v.%v IN (select %v.%v from %v where %v.%v IN (?)) and %v.publish_status = ?",
toTable, toPrimaryKey, fromTable, relationship.ForeignDBName, fromTable, fromTable, fromPrimaryKey, toTable)
rows, err = draftDB.Table(draftTable).Select(toTable+"."+toPrimaryKey).Where(sql, primaryKeys, DIRTY).Rows()
}
if rows != nil && err == nil {
for rows.Next() {
var primaryValues = make([]interface{}, len(toScope.PrimaryFields()))
rows.Scan(primaryValues...)
dependencyKeys = append(dependencyKeys, primaryValues)
}
resolver.AddDependency(&dependency{Type: toType, PrimaryValues: dependencyKeys})
}
}
if relationship.Kind == "many_to_many" {
dep.ManyToManyRelations = append(dep.ManyToManyRelations, relationship)
}
}
}
}
func (resolver *resolver) GenerateDependencies() {
var addToDependencies = func(data interface{}) {
if isPublishableModel(data) {
scope := resolver.DB.NewScope(data)
var primaryValues []interface{}
for _, field := range scope.PrimaryFields() {
primaryValues = append(primaryValues, field.Field.Interface())
}
resolver.AddDependency(&dependency{Type: modelType(data), PrimaryValues: [][]interface{}{primaryValues}})
}
}
for _, record := range resolver.Records {
reflectValue := reflect.Indirect(reflect.ValueOf(record))
if reflectValue.Kind() == reflect.Slice {
for i := 0; i < reflectValue.Len(); i++ {
addToDependencies(reflectValue.Index(i).Interface())
}
} else {
addToDependencies(record)
}
}
}
func (resolver *resolver) Publish() error {
resolver.GenerateDependencies()
tx := resolver.DB.Begin()
for _, dep := range resolver.Dependencies {
value := reflect.New(dep.Type).Elem()
productionScope := resolver.DB.Set("publish:draft_mode", false).NewScope(value.Addr().Interface())
productionTable := productionScope.TableName()
draftTable := draftTableName(productionTable)
productionPrimaryKey := scopePrimaryKeys(productionScope, productionTable)
draftPrimaryKey := scopePrimaryKeys(productionScope, draftTable)
var columns []string
for _, field := range productionScope.Fields() {
if field.IsNormal {
columns = append(columns, field.DBName)
}
}
var productionColumns, draftColumns []string
for _, column := range columns {
productionColumns = append(productionColumns, productionScope.Quote(column))
draftColumns = append(draftColumns, productionScope.Quote(column))
}
if len(dep.PrimaryValues) > 0 {
// delete old records
deleteSql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", productionTable, productionPrimaryKey, toQueryMarks(dep.PrimaryValues))
tx.Exec(deleteSql, toQueryValues(dep.PrimaryValues)...)
// insert new records
publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
productionTable, strings.Join(productionColumns, " ,"), strings.Join(draftColumns, " ,"),
draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))
tx.Exec(publishSql, toQueryValues(dep.PrimaryValues)...)
// publish join table data
for _, relationship := range dep.ManyToManyRelations {
productionTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", false))
draftTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", true))
var productionJoinKeys, draftJoinKeys []string
var productionCondition, draftCondition string
for _, foreignKey := range relationship.JoinTableHandler.SourceForeignKeys() {
productionJoinKeys = append(productionJoinKeys, fmt.Sprintf("%v.%v", productionTable, productionScope.Quote(foreignKey.DBName)))
draftJoinKeys = append(draftJoinKeys, fmt.Sprintf("%v.%v", draftTable, productionScope.Quote(foreignKey.DBName)))
}
if len(productionJoinKeys) > 1 {
productionCondition = fmt.Sprintf("(%v)", strings.Join(productionJoinKeys, ","))
draftCondition = fmt.Sprintf("(%v)", strings.Join(draftJoinKeys, ","))
} else {
productionCondition = strings.Join(productionJoinKeys, ",")
draftCondition = strings.Join(draftJoinKeys, ",")
}
sql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", productionTable, productionCondition, toQueryMarks(dep.PrimaryValues))
tx.Exec(sql, toQueryValues(dep.PrimaryValues)...)
rows, _ := tx.Raw(fmt.Sprintf("SELECT * FROM %s", draftTable)).Rows()
joinColumns, _ := rows.Columns()
rows.Close()
if len(joinColumns) == 0 {
continue
}
var productionJoinTableColumns, draftJoinTableColumns []string
for _, column := range joinColumns {
productionJoinTableColumns = append(productionJoinTableColumns, productionScope.Quote(column))
draftJoinTableColumns = append(draftJoinTableColumns, productionScope.Quote(column))
}
publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
productionTable, strings.Join(productionJoinTableColumns, " ,"), strings.Join(draftJoinTableColumns, " ,"),
draftTable, draftCondition, toQueryMarks(dep.PrimaryValues))
tx.Exec(publishSql, toQueryValues(dep.PrimaryValues)...)
}
// set status to published
updateStateSql := fmt.Sprintf("UPDATE %v SET publish_status = ? WHERE %v IN (%v)", draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))
var params = []interface{}{bool(PUBLISHED)}
params = append(params, toQueryValues(dep.PrimaryValues)...)
tx.Exec(updateStateSql, params...)
}
}
if err := tx.Error; err == nil {
return tx.Commit().Error
} else {
tx.Rollback()
return err
}
}
func (resolver *resolver) Discard() error {
resolver.GenerateDependencies()
tx := resolver.DB.Begin()
for _, dep := range resolver.Dependencies {
value := reflect.New(dep.Type).Elem()
productionScope := resolver.DB.Set("publish:draft_mode", false).NewScope(value.Addr().Interface())
productionTable := productionScope.TableName()
draftTable := draftTableName(productionTable)
productionPrimaryKey := scopePrimaryKeys(productionScope, productionTable)
draftPrimaryKey := scopePrimaryKeys(productionScope, draftTable)
var columns []string
for _, field := range productionScope.Fields() {
if field.IsNormal {
columns = append(columns, field.DBName)
}
}
var productionColumns, draftColumns []string
for _, column := range columns {
productionColumns = append(productionColumns, productionScope.Quote(column))
draftColumns = append(draftColumns, productionScope.Quote(column))
}
// delete data from draft db
deleteSql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", draftTable, draftPrimaryKey, toQueryMarks(dep.PrimaryValues))
tx.Exec(deleteSql, toQueryValues(dep.PrimaryValues)...)
// delete join table
for _, relationship := range dep.ManyToManyRelations {
productionTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", false))
draftTable := relationship.JoinTableHandler.Table(tx.Set("publish:draft_mode", true))
var productionJoinKeys, draftJoinKeys []string
var productionCondition, draftCondition string
for _, foreignKey := range relationship.JoinTableHandler.SourceForeignKeys() {
productionJoinKeys = append(productionJoinKeys, fmt.Sprintf("%v.%v", productionTable, productionScope.Quote(foreignKey.DBName)))
draftJoinKeys = append(draftJoinKeys, fmt.Sprintf("%v.%v", draftTable, productionScope.Quote(foreignKey.DBName)))
}
if len(productionJoinKeys) > 1 {
productionCondition = fmt.Sprintf("(%v)", strings.Join(productionJoinKeys, ","))
draftCondition = fmt.Sprintf("(%v)", strings.Join(draftJoinKeys, ","))
} else {
productionCondition = strings.Join(productionJoinKeys, ",")
draftCondition = strings.Join(draftJoinKeys, ",")
}
sql := fmt.Sprintf("DELETE FROM %v WHERE %v IN (%v)", draftTable, draftCondition, toQueryMarks(dep.PrimaryValues))
tx.Exec(sql, toQueryValues(dep.PrimaryValues)...)
rows, _ := tx.Raw(fmt.Sprintf("select * from %v", draftTable)).Rows()
joinColumns, _ := rows.Columns()
rows.Close()
if len(joinColumns) == 0 {
continue
}
var productionJoinTableColumns, draftJoinTableColumns []string
for _, column := range joinColumns {
productionJoinTableColumns = append(productionJoinTableColumns, productionScope.Quote(column))
draftJoinTableColumns = append(draftJoinTableColumns, productionScope.Quote(column))
}
publishSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
draftTable, strings.Join(draftJoinTableColumns, " ,"), strings.Join(productionJoinTableColumns, " ,"),
productionTable, productionCondition, toQueryMarks(dep.PrimaryValues))
tx.Exec(publishSql, toQueryValues(dep.PrimaryValues)...)
}
// copy data from production to draft
discardSql := fmt.Sprintf("INSERT INTO %v (%v) SELECT %v FROM %v WHERE %v IN (%v)",
draftTable, strings.Join(draftColumns, " ,"),
strings.Join(productionColumns, " ,"), productionTable,
productionPrimaryKey, toQueryMarks(dep.PrimaryValues))
tx.Exec(discardSql, toQueryValues(dep.PrimaryValues)...)
}
if err := tx.Error; err == nil {
return tx.Commit().Error
} else {
tx.Rollback()
return err
}
}
func scopePrimaryKeys(scope *gorm.Scope, tableName string) string {
var primaryKeys []string
for _, field := range scope.PrimaryFields() {
key := fmt.Sprintf("%v.%v", scope.Quote(tableName), scope.Quote(field.DBName))
primaryKeys = append(primaryKeys, key)
}
if len(primaryKeys) > 1 {
return fmt.Sprintf("(%v)", strings.Join(primaryKeys, ","))
}
return strings.Join(primaryKeys, "")
}
func toQueryMarks(primaryValues [][]interface{}) string {
var results []string
for _, primaryValue := range primaryValues {
var marks []string
for range primaryValue {
marks = append(marks, "?")
}
if len(marks) > 1 {
results = append(results, fmt.Sprintf("(%v)", strings.Join(marks, ",")))
} else {
results = append(results, strings.Join(marks, ""))
}
}
return strings.Join(results, ",")
}
func toQueryValues(primaryValues [][]interface{}) (values []interface{}) {
for _, primaryValue := range primaryValues {
for _, value := range primaryValue {
values = append(values, value)
}
}
return values
}