This repository has been archived by the owner on Sep 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
collection.go
419 lines (343 loc) · 9.74 KB
/
collection.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package api
import (
"encoding/json"
)
// Collection represents a structure composed of zero or more items.
type Collection struct {
PayloadBranch Payload `json:"branch" sql:"-"`
// Validator specific fields
Branch *Branch `json:"-" sql:"-"`
Items []*CollectionItem `json:"items" sql:"-"`
// Persister specific fields
ID int `json:"-"`
AccountID int `json:"-"`
BranchID int `json:"-" pg:",fk:Branch"`
}
// Unmarshal bytes in to the entity properties.
func (entity *Collection) Unmarshal(raw []byte) error {
err := json.Unmarshal(raw, entity)
if err != nil {
return err
}
if entity.PayloadBranch.Type != "" {
branch, err := entity.PayloadBranch.Entity()
if err != nil {
return err
}
entity.Branch = branch.(*Branch)
}
return err
}
// Marshal to payload structure
func (entity *Collection) Marshal() Payload {
if entity.Branch != nil {
entity.PayloadBranch = entity.Branch.Marshal()
}
return MarshalPayloadEntity("collection", entity)
}
// Valid checks the value(s) against an battery of tests.
func (entity *Collection) Valid() (bool, error) {
var stack ErrorStack
// Iterate through each property in `Items` validating them as we go.
for _, item := range entity.Items {
if ok, err := item.Valid(); !ok {
stack.Append("Item", err)
}
}
// Custom errors
if entity.PayloadBranch.Type != "" {
if ok, err := entity.Branch.Valid(); !ok {
stack.Append("Item", err)
} else {
if entity.Branch.Value != "No" {
stack.Append("Collection", ErrFieldInvalid{"Collection branch value is required"})
}
}
}
return !stack.HasErrors(), stack
}
// Save the Collection entity.
func (entity *Collection) Save(context DatabaseService, account int) (int, error) {
// Flush the collection contents prior to saving them.
// This ensures previously persisted data is not left around.
copy := &Collection{}
*copy = *entity
copy.Delete(context, account)
entity.AccountID = account
// If there is a branch payload but the branch if non-existent
// create one so it may be assigned to.
if entity.PayloadBranch.Type != "" && entity.Branch == nil {
entity.Branch = &Branch{}
}
if err := context.CheckTable(entity); err != nil {
return entity.ID, err
}
if err := entity.Find(context); err != nil {
return entity.ID, err
}
// Custom errors
if entity.PayloadBranch.Type != "" {
branchID, err := entity.Branch.Save(context, account)
if err != nil {
return 0, err
}
entity.BranchID = branchID
}
if err := context.Save(entity); err != nil {
return entity.ID, err
}
// Iterate through each property in `Items` saving them as we go.
for i, item := range entity.Items {
if _, err := item.Save(context, account, entity.ID, i+1); err != nil {
return entity.ID, err
}
}
return entity.ID, nil
}
// Delete the Collection entity.
func (entity *Collection) Delete(context DatabaseService, account int) (int, error) {
entity.AccountID = account
if err := context.CheckTable(entity); err != nil {
return entity.ID, err
}
if err := entity.Find(context); err != nil {
return entity.ID, err
}
entity.collectionItemIDs(context)
for i, item := range entity.Items {
if _, err := item.Delete(context, account, entity.ID, i+1); err != nil {
return entity.ID, err
}
}
if entity.ID != 0 {
if err := context.Delete(entity); err != nil {
return entity.ID, err
}
}
if entity.PayloadBranch.Type != "" {
if _, err := entity.Branch.Delete(context, account); err != nil {
return entity.ID, err
}
}
return entity.ID, nil
}
// Get the Collection entity.
func (entity *Collection) Get(context DatabaseService, account int) (int, error) {
entity.AccountID = account
if err := context.CheckTable(entity); err != nil {
return entity.ID, err
}
if err := entity.Find(context); err != nil {
return entity.ID, err
}
if entity.ID != 0 {
if err := context.Select(entity); err != nil {
return entity.ID, err
}
}
if entity.BranchID != 0 {
if _, err := entity.Branch.Get(context, account); err != nil {
return entity.ID, err
}
}
entity.collectionItemIDs(context)
for i, item := range entity.Items {
if _, err := item.Get(context, account, entity.ID, i+1); err != nil {
return entity.ID, err
}
}
return entity.ID, nil
}
// GetID returns the entity identifier.
func (entity *Collection) GetID() int {
return entity.ID
}
// SetID sets the entity identifier.
func (entity *Collection) SetID(id int) {
entity.ID = id
}
// collectionItemIDs the Collection item identifiers.
func (entity *Collection) collectionItemIDs(context DatabaseService) {
var count int
context.CountExpr(&CollectionItem{}, "max(index) as max", &count, "id = ?", entity.ID)
entity.Items = []*CollectionItem{}
for i := 0; i < count; i++ {
entity.Items = append(entity.Items, &CollectionItem{ID: entity.ID, Index: i + 1})
}
}
// Find the previous entity stored if one is available.
func (entity *Collection) Find(context DatabaseService) error {
context.Find(&Collection{ID: entity.ID, AccountID: entity.AccountID}, func(result interface{}) {
previous := result.(*Collection)
if previous.BranchID != 0 {
if entity.Branch == nil {
entity.Branch = &Branch{}
}
entity.Branch.ID = previous.BranchID
entity.BranchID = previous.BranchID
}
})
return nil
}
// CollectionItem is an item of named payloads directly used in a `Collection`.
type CollectionItem struct {
Item map[string]json.RawMessage `json:"Item" sql:"-"`
ID int `json:"-" sql:",pk"`
Index int `json:"-" sql:",pk"`
Name string `json:"-" sql:",pk"`
Type string `json:"-"`
ItemID int `json:"-"`
}
// Valid iterates through each named property of an item validating
// each payload.
func (ci *CollectionItem) Valid() (bool, error) {
err := ci.Each(func(name, entityType string, entity Entity, err error) error {
if err != nil {
return err
}
_, err = entity.Valid()
return err
})
return err != nil, err
}
// Save the collection item
func (ci *CollectionItem) Save(context DatabaseService, account, collectionID, index int) (int, error) {
ci.ID = collectionID
if err := context.CheckTable(&CollectionItem{}); err != nil {
return ci.ID, err
}
err := ci.Each(func(name, entityType string, entity Entity, err error) error {
// If a named payload was not able to be decoded then skip the saving
// bit.
if entityType == "" {
return nil
}
item := &CollectionItem{
ID: collectionID,
Index: index,
Name: name,
Type: entityType,
}
id, err := entity.Save(context, account)
if err != nil {
return err
}
item.ItemID = id
return context.Save(item)
})
return ci.ID, err
}
// Delete the collection item
func (ci *CollectionItem) Delete(context DatabaseService, account, collectionID, index int) (int, error) {
ci.ID = collectionID
if err := context.CheckTable(&CollectionItem{}); err != nil {
return ci.ID, err
}
ci.getItemPropertyNames(context)
err := ci.Each(func(name, entityType string, entity Entity, err error) error {
if err != nil {
return err
}
item := &CollectionItem{
ID: collectionID,
Index: index,
Name: name,
Type: entityType,
}
if err := context.CheckTable(entity); err != nil {
return err
}
id, err := entity.Delete(context, account)
if err != nil {
return err
}
item.ItemID = id
return context.Delete(item)
})
if err != nil {
return ci.ID, err
}
if ci.ID != 0 {
err := context.Raw("DELETE FROM collection_items WHERE id = ?", ci.ID)
if err != nil {
return ci.ID, err
}
}
return ci.ID, nil
}
// Get the collection item
func (ci *CollectionItem) Get(context DatabaseService, account, collectionID, index int) (int, error) {
ci.ID = collectionID
if err := context.CheckTable(&CollectionItem{}); err != nil {
return ci.ID, err
}
ci.getItemPropertyNames(context)
err := ci.Each(func(name, entityType string, entity Entity, err error) error {
item := &CollectionItem{
ID: collectionID,
Index: index,
Name: name,
Type: entityType,
}
if err := context.Select(item); err != nil {
return err
}
entity, _ = transform[item.Type]()
entity.SetID(item.ItemID)
if err := context.CheckTable(entity); err != nil {
return err
}
if _, err = entity.Get(context, account); err != nil {
return err
}
raw, _ := json.MarshalIndent(entity.Marshal(), "", " ")
ci.Item[name] = raw
return nil
})
return ci.ID, err
}
// GetID returns the entity identifier.
func (ci *CollectionItem) GetID() int {
return ci.ID
}
// SetID sets the entity identifier.
func (ci *CollectionItem) SetID(id int) {
ci.ID = id
}
// Each loops through each entity in the collection item performing a given action
func (ci CollectionItem) Each(action func(string, string, Entity, error) error) error {
var err error
for k, v := range ci.Item {
entityType, entity, err := getItemEntity(v)
if err = action(k, entityType, entity, err); err != nil {
break
}
}
return err
}
// getItemEntity marshals a raw JSON format to a entity
func getItemEntity(raw json.RawMessage) (string, Entity, error) {
// Decode JSON to a payload
payload := &Payload{}
err := json.Unmarshal(raw, payload)
if err != nil {
return "", nil, err
}
// Find the appropriate entity for the payload
entity, err := payload.Entity()
return payload.Type, entity, err
}
// getItemPropertyNames retrieves the number of items in the collection item and assigns
// property names so they may be filled.
func (ci *CollectionItem) getItemPropertyNames(context DatabaseService) {
propertyNames := []string{}
context.Array(&CollectionItem{}, "array_agg(name)", &propertyNames, "id = ?", ci.ID)
ci.Item = make(map[string]json.RawMessage)
for _, propertyName := range propertyNames {
ci.Item[propertyName] = []byte{}
}
}
// Find is not used for collection items. Please use the `Get` method.
func (ci *CollectionItem) Find(context DatabaseService) error {
return nil
}