-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathtable.go
440 lines (379 loc) · 12 KB
/
table.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package dynamodb
import (
"fmt"
"strings"
SDK "github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/evalphobia/aws-sdk-go-wrapper/private/pointers"
)
const batchWriteItemMax = 25
// Table is a wapper struct for DynamoDB table
type Table struct {
service *DynamoDB
name string
nameWithPrefix string
design *TableDesign
putSpool []*SDK.PutItemInput
errorItems []*SDK.PutItemInput
}
// ---------------------------------
// table
// ---------------------------------
// NewTable returns initialized *Table.
func NewTable(svc *DynamoDB, name string) (*Table, error) {
tableName := svc.prefix + name
desc, err := svc.DescribeTable(tableName)
if err != nil {
return nil, err
}
design := newTableDesignFromDescription(desc)
return &Table{
service: svc,
name: name,
nameWithPrefix: tableName,
design: design,
}, nil
}
// NewTableWithDesign returns initialized *Table.
func NewTableWithDesign(svc *DynamoDB, design *TableDesign) (*Table, error) {
tableName := design.name
name := strings.Replace(tableName, svc.prefix, "", 1)
return &Table{
service: svc,
name: name,
nameWithPrefix: tableName,
design: design,
}, nil
}
// NewTableWithoutDesign returns initialized *Table without table design.
func NewTableWithoutDesign(svc *DynamoDB, name string) *Table {
tableName := svc.prefix + name
return &Table{
service: svc,
name: name,
nameWithPrefix: tableName,
}
}
// GetDesign gets table design.
func (t *Table) GetDesign() *TableDesign {
return t.design
}
// SetDesign sets table design.
func (t *Table) SetDesign(design *TableDesign) {
t.design = design
}
// RefreshDesign returns refreshed table design.
func (t *Table) RefreshDesign() (*TableDesign, error) {
desc, err := t.service.DescribeTable(t.nameWithPrefix)
if err != nil {
return nil, err
}
t.design = newTableDesignFromDescription(desc)
return t.design, nil
}
// UpdateThroughput updates the r/w ProvisionedThroughput.
func (t *Table) UpdateThroughput(r int64, w int64) error {
t.design.SetThroughput(r, w)
return t.updateThroughput()
}
// UpdateWriteThroughput updates the write ProvisionedThroughput.
func (t *Table) UpdateWriteThroughput(w int64) error {
t.design.SetThroughput(t.design.readCapacity, w)
return t.updateThroughput()
}
// UpdateReadThroughput updates the read ProvisionedThroughput.
func (t *Table) UpdateReadThroughput(r int64) error {
t.design.SetThroughput(r, t.design.writeCapacity)
return t.updateThroughput()
}
// updateThroughput updates dynamodb table provisioned throughput
func (t *Table) updateThroughput() error {
_, err := t.service.client.UpdateTable(&SDK.UpdateTableInput{
TableName: pointers.String(t.nameWithPrefix),
ProvisionedThroughput: &SDK.ProvisionedThroughput{
ReadCapacityUnits: pointers.Long64(t.design.readCapacity),
WriteCapacityUnits: pointers.Long64(t.design.writeCapacity),
},
})
if err != nil {
t.service.Errorf("error on `UpdateTable` operation; table=%s; error=%s", t.nameWithPrefix, err.Error())
return err
}
// refresh table information
design, err := t.RefreshDesign()
if err != nil {
return err
}
t.design = design
return nil
}
// ---------------------------------
// Put
// ---------------------------------
// AddItem adds an item to the write-waiting list (writeItem)
func (t *Table) AddItem(item *PutItem) {
w := &SDK.PutItemInput{
TableName: pointers.String(t.nameWithPrefix),
ReturnConsumedCapacity: pointers.String("TOTAL"),
Item: item.data,
Expected: item.conditions,
}
t.putSpool = append(t.putSpool, w)
t.service.addWriteTable(t)
}
// Put executes put operation from the write-waiting list (writeItem)
func (t *Table) Put() error {
errList := newErrors()
// save items in spool
for _, item := range t.putSpool {
err := t.validatePutItem(item)
if err != nil {
errList.Add(err)
continue
}
_, err = t.service.client.PutItem(item)
if err != nil {
errList.Add(err)
t.errorItems = append(t.errorItems, item)
}
}
t.putSpool = nil
if errList.HasError() {
t.service.Errorf("errors on `Put` operations; table=%s; errors=[%s];", t.nameWithPrefix, errList.Error())
return errList
}
return nil
}
// BatchPut executes BatchWriteItem operation from the write-waiting list (writeItem)
func (t *Table) BatchPut() error {
errList := newErrors()
errorSpoolIndices := make([]int, 0, len(t.putSpool))
for index, item := range t.putSpool {
err := t.validatePutItem(item)
if err != nil {
errList.Add(err)
// add to ignore list
errorSpoolIndices = append(errorSpoolIndices, index)
continue
}
}
t.removeErroredSpoolByIndices(errorSpoolIndices)
input := new(SDK.BatchWriteItemInput)
writeRequests := t.spoolToWriteRequests()
for i := 0; i < len(writeRequests); i++ {
input.SetRequestItems(writeRequests[i])
if _, err := t.service.client.BatchWriteItem(input); err != nil {
errList.Add(err)
}
}
t.putSpool = nil
if errList.HasError() {
t.service.Errorf("errors on `Put` operations; table=%s; errors=[%s];", t.nameWithPrefix, errList.Error())
return errList
}
return nil
}
// removeErroredSpoolByIndices removes elements which have index in validation error indices list from putSpool.
func (t *Table) removeErroredSpoolByIndices(errorSpoolIndices []int) {
for i := len(errorSpoolIndices) - 1; i >= 0; i-- {
removeIndex := errorSpoolIndices[i]
firstHalf, latterHalf := t.putSpool[:removeIndex], t.putSpool[removeIndex+1:]
t.putSpool = append(firstHalf, latterHalf...)
}
}
// check if exists all primary keys in the item to write it.
func (t *Table) validatePutItem(item *SDK.PutItemInput) error {
hashKey := t.design.GetHashKeyName()
itemAttrs := item.Item
if _, ok := itemAttrs[hashKey]; !ok {
return fmt.Errorf("error on `validatePutItem`; No such hash key; table=%s; hashkey=%s", t.nameWithPrefix, hashKey)
}
rangeKey := t.design.GetRangeKeyName()
if rangeKey == "" {
return nil
}
if _, ok := itemAttrs[rangeKey]; !ok {
return fmt.Errorf("error on `validatePutItem`; No such range key; table=%s; rangekey=%s", t.nameWithPrefix, rangeKey)
}
return nil
}
func (t *Table) spoolToWriteRequests() []map[string][]*SDK.WriteRequest {
requestChunkCount := 1 + (len(t.putSpool) / batchWriteItemMax)
writeRequestsChunks := make([]map[string][]*SDK.WriteRequest, 0, requestChunkCount)
for chunkNumber := 0; chunkNumber < requestChunkCount; chunkNumber++ {
offsetInSpool := batchWriteItemMax * chunkNumber
if offsetInSpool >= len(t.putSpool) {
break
}
writeRequests := make([]*SDK.WriteRequest, 0, batchWriteItemMax)
for itemInChunk := 0; itemInChunk < batchWriteItemMax && offsetInSpool+itemInChunk < len(t.putSpool); itemInChunk++ {
spoolIndex := batchWriteItemMax*chunkNumber + itemInChunk
wr := new(SDK.WriteRequest)
wr.SetPutRequest(&SDK.PutRequest{Item: t.putSpool[spoolIndex].Item})
writeRequests = append(writeRequests, wr)
}
result := make(map[string][]*SDK.WriteRequest)
result[t.nameWithPrefix] = writeRequests
writeRequestsChunks = append(writeRequestsChunks, result)
}
return writeRequestsChunks
}
// ---------------------------------
// Scan
// ---------------------------------
// Scan executes Scan operation.
func (t *Table) Scan() (*QueryResult, error) {
cond := t.NewConditionList()
cond.SetLimit(1000)
return t.scan(cond, &SDK.ScanInput{})
}
// ScanWithCondition executes Scan operation with given condition.
func (t *Table) ScanWithCondition(cond *ConditionList) (*QueryResult, error) {
return t.scan(cond, &SDK.ScanInput{})
}
// scan executes Scan operation.
func (t *Table) scan(cond *ConditionList, in *SDK.ScanInput) (*QueryResult, error) {
if cond.HasFilter() {
in.FilterExpression = cond.FormatFilter()
in.ExpressionAttributeValues = cond.FormatValues()
in.ExpressionAttributeNames = cond.FormatNames()
}
if cond.HasIndex() {
in.IndexName = pointers.String(cond.index)
}
if cond.HasLimit() {
in.Limit = pointers.Long64(cond.limit)
}
if cond.isConsistent {
in.ConsistentRead = pointers.Bool(cond.isConsistent)
}
in.ExclusiveStartKey = cond.startKey
in.TableName = pointers.String(t.nameWithPrefix)
req, err := t.service.client.Scan(in)
if err != nil {
t.service.Errorf("error on `Scan` operation; table=%s; error=%s;", t.nameWithPrefix, err.Error())
return nil, err
}
res := &QueryResult{
Items: req.Items,
LastEvaluatedKey: req.LastEvaluatedKey,
Count: *req.Count,
ScannedCount: *req.ScannedCount,
}
return res, nil
}
// ---------------------------------
// Query
// ---------------------------------
// Query executes Query operation.
func (t *Table) Query(cond *ConditionList) (*QueryResult, error) {
return t.query(cond, &SDK.QueryInput{})
}
// Count executes Query operation and get Count.
func (t *Table) Count(cond *ConditionList) (*QueryResult, error) {
return t.query(cond, &SDK.QueryInput{
Select: pointers.String(SelectCount),
})
}
func (t *Table) query(cond *ConditionList, in *SDK.QueryInput) (*QueryResult, error) {
if !cond.HasCondition() {
err := fmt.Errorf("condition is missing, you must specify at least one condition")
t.service.Errorf("error on `query`; table=%s; error=%s", t.nameWithPrefix, err.Error())
return nil, err
}
in.KeyConditionExpression = cond.FormatCondition()
in.FilterExpression = cond.FormatFilter()
in.ExpressionAttributeValues = cond.FormatValues()
in.ExpressionAttributeNames = cond.FormatNames()
if cond.HasIndex() {
in.IndexName = pointers.String(cond.index)
}
if cond.HasLimit() {
in.Limit = pointers.Long64(cond.limit)
}
if cond.isConsistent {
in.ConsistentRead = pointers.Bool(cond.isConsistent)
}
if cond.isDesc {
in.ScanIndexForward = pointers.Bool(false)
}
in.ExclusiveStartKey = cond.startKey
in.TableName = pointers.String(t.nameWithPrefix)
req, err := t.service.client.Query(in)
if err != nil {
t.service.Errorf("error on `Query` operation; table=%s; error=%s", t.nameWithPrefix, err.Error())
return nil, err
}
res := &QueryResult{
Items: req.Items,
LastEvaluatedKey: req.LastEvaluatedKey,
Count: *req.Count,
ScannedCount: *req.ScannedCount,
}
return res, nil
}
// NewConditionList returns initialized *ConditionList.
func (t *Table) NewConditionList() *ConditionList {
return NewConditionList(t.design.GetKeyAttributes())
}
// ---------------------------------
// Get
// ---------------------------------
// GetOne retrieves a single item by GetOne(HashKey [, RangeKey])
func (t *Table) GetOne(hashValue interface{}, rangeValue ...interface{}) (map[string]interface{}, error) {
in := &SDK.GetItemInput{
TableName: pointers.String(t.nameWithPrefix),
Key: t.design.keyAttributeValue(hashValue, rangeValue...),
}
req, err := t.service.client.GetItem(in)
switch {
case err != nil:
t.service.Errorf("error on `GetItem` operation; table=%s; error=%s", t.nameWithPrefix, err.Error())
return nil, err
case req.Item == nil:
return nil, nil
}
return UnmarshalAttributeValue(req.Item), nil
}
// ---------------------------------
// Delete
// ---------------------------------
// Delete deletes the item.
func (t *Table) Delete(hashValue interface{}, rangeValue ...interface{}) error {
in := &SDK.DeleteItemInput{
TableName: pointers.String(t.nameWithPrefix),
Key: t.design.keyAttributeValue(hashValue, rangeValue...),
}
_, err := t.service.client.DeleteItem(in)
if err != nil {
t.service.Errorf("error on `DeleteItem` operation; table=%s; error=%s", t.nameWithPrefix, err.Error())
return err
}
return nil
}
// ForceDeleteAll deltes all data in the table.
// This performs scan all item and delete it each one by one.
func (t *Table) ForceDeleteAll() error {
hashkey := t.design.GetHashKeyName()
rangekey := t.design.GetRangeKeyName()
result, err := t.Scan()
if err != nil {
return err
}
errData := newErrors()
for _, item := range result.ToSliceMap() {
var e error
switch rangekey {
case "":
e = t.Delete(item[hashkey])
default:
e = t.Delete(item[hashkey], item[rangekey])
}
if e != nil {
errData.Add(e)
}
}
if errData.HasError() {
return errData
}
return nil
}