-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdomino.go
More file actions
2149 lines (1845 loc) · 52.8 KB
/
Copy pathdomino.go
File metadata and controls
2149 lines (1845 loc) · 52.8 KB
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package domino
import (
"context"
"errors"
"math"
"reflect"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
/*DynamoDBIFace is the interface to the underlying aws dynamo db api*/
type DynamoDBIFace interface {
CreateTableWithContext(aws.Context, *dynamodb.CreateTableInput, ...request.Option) (*dynamodb.CreateTableOutput, error)
DeleteTableWithContext(aws.Context, *dynamodb.DeleteTableInput, ...request.Option) (*dynamodb.DeleteTableOutput, error)
GetItemWithContext(aws.Context, *dynamodb.GetItemInput, ...request.Option) (*dynamodb.GetItemOutput, error)
BatchGetItemWithContext(aws.Context, *dynamodb.BatchGetItemInput, ...request.Option) (*dynamodb.BatchGetItemOutput, error)
PutItemWithContext(aws.Context, *dynamodb.PutItemInput, ...request.Option) (*dynamodb.PutItemOutput, error)
QueryWithContext(aws.Context, *dynamodb.QueryInput, ...request.Option) (*dynamodb.QueryOutput, error)
ScanWithContext(aws.Context, *dynamodb.ScanInput, ...request.Option) (*dynamodb.ScanOutput, error)
UpdateItemWithContext(aws.Context, *dynamodb.UpdateItemInput, ...request.Option) (*dynamodb.UpdateItemOutput, error)
DeleteItemWithContext(aws.Context, *dynamodb.DeleteItemInput, ...request.Option) (*dynamodb.DeleteItemOutput, error)
BatchWriteItemWithContext(aws.Context, *dynamodb.BatchWriteItemInput, ...request.Option) (*dynamodb.BatchWriteItemOutput, error)
TransactGetItemsWithContext(aws.Context, *dynamodb.TransactGetItemsInput, ...request.Option) (*dynamodb.TransactGetItemsOutput, error)
TransactWriteItemsWithContext(aws.Context, *dynamodb.TransactWriteItemsInput, ...request.Option) (*dynamodb.TransactWriteItemsOutput, error)
}
type DynamoDBValue map[string]*dynamodb.AttributeValue
// Loader is the interface that specifies the ability to deserialize and load data from dynamodb attrbiute value map
type Loader interface {
LoadDynamoDBValue(av DynamoDBValue) (err error)
}
func deserializeTo(av DynamoDBValue, item interface{}) (err error) {
if len(av) <= 0 {
return
}
switch t := (item).(type) {
case Loader:
err = t.LoadDynamoDBValue(av)
default:
err = dynamodbattribute.UnmarshalMap(av, item)
}
return
}
// ToValue is the interface that specifies the ability to serialize data to a value that can be persisted in dynamodb
type ToValue interface {
ToDynamoDBValue() (bm interface{})
}
func serialize(item interface{}) (av map[string]*dynamodb.AttributeValue, err error) {
switch t := item.(type) {
case ToValue:
av, err = dynamodbattribute.MarshalMap(t.ToDynamoDBValue())
default:
av, err = dynamodbattribute.MarshalMap(item)
}
return
}
func marshal(m map[string]interface{}) (o map[string]*dynamodb.AttributeValue) {
if len(m) <= 0 {
return
}
o = map[string]*dynamodb.AttributeValue{}
for k, v := range m {
switch t := v.(type) {
case *dynamodb.AttributeValue:
o[k] = t
default:
var err error
if o[k], err = dynamodbattribute.Marshal(t); err != nil {
panic(err)
}
}
}
return
}
const (
dS = "S"
dSS = "SS"
dN = "N"
dNS = "NS"
dB = "B"
dBS = "BS"
dBOOL = "BOOL"
dNULL = "NULL"
dL = "L"
dM = "M"
)
const (
ProjectionTypeALL = "ALL"
ProjectionTypeINCLUDE = "INCLUDE"
ProjectionTypeKEYS_ONLY = "KEYS_ONLY"
)
const (
DynamoBatchSize = 10
)
var (
BatchSizeExceededError = errors.New("TransactItems batch size maximum of 10 exceeded. Reduce the number of items to write.")
)
/*DynamoTable is a static table definition representing a dynamo table*/
type DynamoTable struct {
Name string
PartitionKey DynamoFieldIFace
RangeKey DynamoFieldIFace //Optional param. If no range key set to EmptyDynamoField()
GlobalSecondaryIndexes []GlobalSecondaryIndex
LocalSecondaryIndexes []LocalSecondaryIndex
}
type DynamoFieldIFace interface {
Name() string
Type() string
IsEmpty() bool
}
type DynamoField struct {
name string
_type string
empty bool //If true, this represents an empty field
}
type dynamoValueField struct {
DynamoField
}
type dynamoCollectionField struct {
DynamoField
}
type dynamoListField struct {
dynamoCollectionField
}
type dynamoSetField struct {
dynamoCollectionField
}
type dynamoMapField struct {
DynamoField
}
func (d DynamoField) Name() string {
return d.name
}
func (d DynamoField) Type() string {
return d._type
}
func (d DynamoField) IsEmpty() bool {
return d.empty
}
/*Empty - An empty dynamo field*/
type Empty struct {
DynamoField
}
/*Numeric - A numeric dynamo field*/
type Numeric struct {
dynamoValueField
}
/*NumericSet - A numeric set dynamo field*/
type NumericSet struct {
dynamoSetField
}
/*String - A string dynamo field*/
type String struct {
dynamoValueField
}
/*StringSet - A string set dynamo field*/
type StringSet struct {
dynamoSetField
}
/*Binary - A binary dynamo field*/
type Binary struct {
dynamoValueField
}
/*BinarySet - A binary dynamo field*/
type BinarySet struct {
dynamoSetField
}
/*Bool - A boolean dynamo field*/
type Bool struct {
dynamoValueField
}
/*List - A list dynamo field*/
type List struct {
dynamoListField
}
/*Map - A map dynamo field*/
type Map struct {
dynamoMapField
}
/*EmptyField ... A constructor for an empty dynamo field*/
func EmptyField() Empty {
return Empty{
DynamoField{
empty: true,
_type: dNULL,
},
}
}
/*NumericField ... A constructor for a numeric dynamo field*/
func NumericField(name string) Numeric {
return Numeric{
dynamoValueField{
DynamoField{
name: name,
_type: dN,
},
},
}
}
/*NumericSetField ... A constructor for a numeric set dynamo field*/
func NumericSetField(name string) NumericSet {
return NumericSet{
dynamoSetField{
dynamoCollectionField{
DynamoField{
name: name,
_type: dNS,
},
},
},
}
}
/*StringField ... A constructor for a string dynamo field*/
func StringField(name string) String {
return String{
dynamoValueField{
DynamoField{
name: name,
_type: dS,
},
},
}
}
/*StringField ... A constructor for a string dynamo field*/
func BoolField(name string) Bool {
return Bool{
dynamoValueField{
DynamoField{
name: name,
_type: dBOOL,
},
},
}
}
/*BinaryField ... A constructor for a binary dynamo field*/
func BinaryField(name string) Binary {
return Binary{
dynamoValueField{
DynamoField{
name: name,
_type: dB,
},
},
}
}
/*BinarySetField ... A constructor for a binary set dynamo field*/
func BinarySetField(name string) BinarySet {
return BinarySet{
dynamoSetField{
dynamoCollectionField{
DynamoField{
name: name,
_type: dBS,
},
},
},
}
}
/*StringSetField ... A constructor for a string set dynamo field*/
func StringSetField(name string) StringSet {
return StringSet{
dynamoSetField{
dynamoCollectionField{
DynamoField{
name: name,
_type: dSS,
},
},
},
}
}
/*ListField ... A constructor for a list dynamo field*/
func ListField(name string) List {
return List{
dynamoListField{
dynamoCollectionField{
DynamoField{
name: name,
_type: dL,
},
},
},
}
}
/*MapField ... A constructor for a map dynamo field*/
func MapField(name string) Map {
return Map{
dynamoMapField{
DynamoField{
name: name,
_type: dL,
},
},
}
}
/*LocalSecondaryIndex ... Represents a dynamo local secondary index*/
type LocalSecondaryIndex struct {
Name string
PartitionKey DynamoFieldIFace
SortKey DynamoFieldIFace
ProjectionType string
NonKeyAttributes []DynamoFieldIFace
}
/*GlobalSecondaryIndex ... Represents a dynamo global secondary index*/
type GlobalSecondaryIndex struct {
Name string
PartitionKey DynamoFieldIFace
RangeKey DynamoFieldIFace //Optional param. If no range key set to EmptyField
ProjectionType string
NonKeyAttributes []DynamoFieldIFace
ReadUnits int64
WriteUnits int64
}
/*KeyValue ... A Key Value struct for use in GetItem and BatchWriteItem queries*/
type KeyValue struct {
PartitionKey interface{}
RangeKey interface{}
}
type TableName string
type Keys *dynamodb.KeysAndAttributes
type dynamoResult struct {
err error
}
func (r *dynamoResult) Error() error {
return r.err
}
func (r *dynamoResult) ConditionalCheckFailed() (b bool) {
if err := r.Error(); err != nil {
if awsErr, ok := err.(awserr.Error); ok {
switch awsErr.Code() {
case dynamodb.ErrCodeConditionalCheckFailedException:
b = true
default:
b = false
}
}
}
return
}
/***************************************************************************************/
/************************************** GetItem ****************************************/
/***************************************************************************************/
type getInput dynamodb.GetItemInput
type getOutput struct {
*dynamoResult
*dynamodb.GetItemOutput
}
/*GetItem Primary constructor for creating a get item query*/
func (table DynamoTable) GetItem(key KeyValue) *getInput {
q := getInput(dynamodb.GetItemInput{})
q.TableName = &table.Name
appendAttribute(&q.Key, table.PartitionKey.Name(), key.PartitionKey)
if table.RangeKey != nil && !table.RangeKey.IsEmpty() {
appendAttribute(&q.Key, table.RangeKey.Name(), key.RangeKey)
}
return &q
}
/*SetConsistentRead ... */
func (d *getInput) SetConsistentRead(c bool) *getInput {
d.ConsistentRead = &c
return d
}
func (d *getInput) SetProjectionExpression(exp string) *getInput {
d.ProjectionExpression = &exp
return d
}
func (d *getInput) Build() *dynamodb.GetItemInput {
r := dynamodb.GetItemInput(*d)
r.ReturnConsumedCapacity = aws.String("INDEXES")
return &r
}
/**
** ExecuteWith ... Execute a dynamo getitem call with a passed in dynamodb instance
** dynamo - The underlying dynamodb api
** item - The item pointer to be hyderated. I.e. if the table holds User object, item should be a pointer to a uninitialized
** User{} struct
**
** Returns a tuple of the hydrated item struct, or an error
*/
func (d *getInput) ExecuteWith(ctx context.Context, dynamo DynamoDBIFace, opts ...request.Option) (out *getOutput) {
o, err := dynamo.GetItemWithContext(ctx, d.Build(), opts...)
dr := &dynamoResult{
err,
}
out = &getOutput{
dr,
o,
}
return
}
func (o *getOutput) Result(item interface{}) (err error) {
err = o.Error()
if o.GetItemOutput == nil || err != nil || item == nil {
return
}
return deserializeTo(o.Item, item)
}
/***************************************************************************************/
/************************************** BatchGetItem ***********************************/
/***************************************************************************************/
type batchGetInput struct {
input *[]*dynamodb.BatchGetItemInput
consistentRead bool
/*A set of mutational operations that might error out, i.e. not pure, and therefore not conducive to a fluent dsl*/
delayedFunctions []func() error
}
type batchGetOutput struct {
*dynamoResult
results []*dynamodb.BatchGetItemOutput
}
/*BatchGetItem represents dynamo batch get item call*/
func (table DynamoTable) BatchGetItem(items ...KeyValue) *batchGetInput {
/*Delay the attribute value construction, until Build time*/
input := &[]*dynamodb.BatchGetItemInput{}
delayed := func() error {
k := make(map[string]*dynamodb.KeysAndAttributes)
keysAndAttribs := &dynamodb.KeysAndAttributes{}
k[table.Name] = keysAndAttribs
ss := []map[string]*dynamodb.KeysAndAttributes{k}
for i, kv := range items {
if (i-1)%100 == 99 {
k = make(map[string]*dynamodb.KeysAndAttributes)
ss = append(ss, k)
keysAndAttribs = &dynamodb.KeysAndAttributes{}
k[table.Name] = keysAndAttribs
}
m := map[string]interface{}{
table.PartitionKey.Name(): kv.PartitionKey,
}
if table.RangeKey != nil && !table.RangeKey.IsEmpty() {
m[table.RangeKey.Name()] = kv.RangeKey
}
attributes, err := dynamodbattribute.MarshalMap(m)
if err != nil {
return err
}
(*keysAndAttribs).Keys = append((*keysAndAttribs).Keys, attributes)
}
for _, m := range ss {
(*input) = append(*input, &dynamodb.BatchGetItemInput{RequestItems: m})
}
return nil
}
q := &batchGetInput{
input: input,
delayedFunctions: []func() error{delayed},
}
return q
}
func (d *batchGetInput) Build() (input []*dynamodb.BatchGetItemInput, err error) {
for _, function := range d.delayedFunctions {
err = function()
if err != nil {
return
}
}
input = *(d.input)
for _, i := range input {
i.ReturnConsumedCapacity = aws.String("INDEXES")
// set read consistency on individual items.
// this cannot be done in a delayedFunction because it depends on the context
// of the batchGetInput items.
for _, a := range i.RequestItems {
a.ConsistentRead = &d.consistentRead
}
}
return
}
/*SetConsistentRead ... */
func (d *batchGetInput) SetConsistentRead(c bool) *batchGetInput {
d.consistentRead = c
return d
}
const minRetryBackoff = time.Millisecond * 100
const maxRetryBackoff = time.Second * 2
/**
** ExecuteWith ... Execute a dynamo BatchGetItem call with a passed in dynamodb instance and next item pointer
** dynamo - The underlying dynamodb api
**
*/
func (d *batchGetInput) ExecuteWith(ctx context.Context, dynamo DynamoDBIFace, opts ...request.Option) *batchGetOutput {
out := &batchGetOutput{
dynamoResult: &dynamoResult{},
}
var input []*dynamodb.BatchGetItemInput
if input, out.err = d.Build(); out.err != nil {
return out
}
for _, bg := range input {
for retry := 0; ; retry++ {
var result *dynamodb.BatchGetItemOutput
if result, out.err = dynamo.BatchGetItemWithContext(ctx, bg, opts...); out.err != nil {
return out
}
out.results = append(out.results, result)
if result.UnprocessedKeys == nil || len(result.UnprocessedKeys) == 0 {
// we have everything
break
}
bg.RequestItems = result.UnprocessedKeys
// Exponential backoff before re-submitting UnprocessedKeys. Immediate retries re-trigger DynamoDB
// throttling.
delay := time.Duration(math.Min(float64(maxRetryBackoff), float64(minRetryBackoff)*math.Pow(2, float64(retry))))
select {
case <-time.After(delay):
case <-ctx.Done():
out.err = ctx.Err()
return out
}
}
}
return out
}
/** Results ... Deserialize the results using a user provided target object generator function
** nextItem - The item pointer function, which is called on each new object returned from dynamodb. The function should
** store each item in an array before returning.
**/
func (o *batchGetOutput) Results(nextItem func() interface{}) (err error) {
err = o.Error()
if o.Error() != nil || nextItem == nil {
return
}
for _, result := range o.results {
for _, items := range result.Responses {
for _, av := range items {
if o.err = deserializeTo(av, nextItem()); o.err != nil {
return
}
}
}
}
return
}
/***************************************************************************************/
/************************************** TransactGetItems ***********************************/
/***************************************************************************************/
type transactGetInput struct {
input []*dynamodb.TransactGetItemsInput
}
type transactGetOutput struct {
*dynamoResult
results []*dynamodb.TransactGetItemsOutput
}
/*TransactGetItems represents dynamo transact get items call*/
/*Maximum of 10 items are allowed to be fetched, per call. If more are requested,
they will be segmented and fetched in batches of 10*/
func (table DynamoTable) TransactGetItems(items ...KeyValue) *transactGetInput {
r := &transactGetInput{}
l := math.Ceil(float64(len(items)) / 10.0)
if l <= 0 {
return r
}
input := make([]*dynamodb.TransactGetItemsInput, int(l))
var tgi *dynamodb.TransactGetItemsInput
var j int
for i, kv := range items {
// Segment into groups of 10
if i%DynamoBatchSize == 0 {
tgi = &dynamodb.TransactGetItemsInput{}
input[j] = tgi
j = j + 1
}
tr := &dynamodb.TransactGetItem{
Get: &dynamodb.Get{
TableName: &table.Name,
},
}
appendKeyAttribute(&tr.Get.Key, table, kv)
tgi.TransactItems = append(tgi.TransactItems, tr)
}
r.input = input
return r
}
func (d *transactGetInput) Build() (input []*dynamodb.TransactGetItemsInput, err error) {
input = d.input
for _, i := range d.input {
i.ReturnConsumedCapacity = aws.String("INDEXES")
}
return
}
/**
** ExecuteWith ... Execute a dynamo TransactGetItems call with a passed in dynamodb instance and next item pointer
** dynamo - The underlying dynamodb api
**
*/
func (d *transactGetInput) ExecuteWith(ctx context.Context, dynamo DynamoDBIFace, opts ...request.Option) (out *transactGetOutput) {
out = &transactGetOutput{
dynamoResult: &dynamoResult{},
}
var input []*dynamodb.TransactGetItemsInput
if input, out.err = d.Build(); out.err != nil {
return
}
for _, bg := range input {
var result *dynamodb.TransactGetItemsOutput
if result, out.err = dynamo.TransactGetItemsWithContext(ctx, bg, opts...); out.err != nil {
return
}
out.results = append(out.results, result)
}
return
}
/** Results ... Deserialize the results using a user provided target object generator function
** nextItem - The item pointer function, which is called on each new object returned from dynamodb. The function should
** store each item in an array before returning.
**/
func (o *transactGetOutput) Results(nextItem func() interface{}) (err error) {
err = o.Error()
if o.Error() != nil || nextItem == nil {
return
}
for _, result := range o.results {
for _, av := range result.Responses {
if o.err = deserializeTo(av.Item, nextItem()); o.err != nil {
return
}
}
}
return
}
/***************************************************************************************/
/************************************** PutItem ****************************************/
/***************************************************************************************/
type putInput dynamodb.PutItemInput
type putOutput struct {
*dynamodb.PutItemOutput
*dynamoResult
}
/*PutItem represents dynamo put item call*/
func (table DynamoTable) PutItem(i interface{}) *putInput {
q := putInput(dynamodb.PutItemInput{})
q.TableName = &table.Name
q.Item, _ = dynamodbattribute.MarshalMap(i)
return &q
}
func (d *putInput) ReturnAllOld() *putInput {
(*dynamodb.PutItemInput)(d).SetReturnValues("ALL_OLD")
return d
}
func (d *putInput) ReturnNone() *putInput {
(*dynamodb.PutItemInput)(d).SetReturnValues("NONE")
return d
}
func (d *putInput) SetConditionExpression(c Expression) *putInput {
s, n, m, _ := c.construct("cond", 1, true)
d.ConditionExpression = &s
d.ExpressionAttributeNames = n
d.ExpressionAttributeValues = marshal(m)
return d
}
func (d *putInput) Build() *dynamodb.PutItemInput {
r := dynamodb.PutItemInput(*d)
return &r
}
/**
** ExecuteWith ... Execute a dynamo PutItem call with a passed in dynamodb instance
** ctx - An instance of context
** dynamo - The underlying dynamodb api
**
*/
func (d *putInput) ExecuteWith(ctx context.Context, dynamo DynamoDBIFace, opts ...request.Option) (out *putOutput) {
out = &putOutput{
dynamoResult: &dynamoResult{},
}
if result, err := dynamo.PutItemWithContext(ctx, d.Build(), opts...); err != nil {
out.err = err
} else {
out.PutItemOutput = result
}
return
}
func (o *putOutput) Result(item interface{}) (err error) {
err = o.Error()
if err != nil || o.PutItemOutput == nil || item == nil {
return
}
deserializeTo(o.PutItemOutput.Attributes, item)
return
}
/***************************************************************************************/
/************************************** TransactWriteItems *********************************/
/***************************************************************************************/
type transactWriteItemsInput struct {
*dynamodb.TransactWriteItemsInput
table DynamoTable
delayedFunctions []func() error
}
type transactWriteItemsOutput struct {
*dynamoResult
results *dynamodb.TransactWriteItemsOutput
}
/*TransactWriteItems represents dynamo batch write item call*/
func (table DynamoTable) TransactWriteItems() *transactWriteItemsInput {
r := transactWriteItemsInput{
TransactWriteItemsInput: &dynamodb.TransactWriteItemsInput{},
table: table,
}
return &r
}
func (d *transactWriteItemsInput) WithClientRequestToken(token string) *transactWriteItemsInput {
d.ClientRequestToken = &token
return d
}
func (d *transactWriteItemsInput) writeItem(item interface{}, f func(DynamoDBValue) *dynamodb.TransactWriteItem) *transactWriteItemsInput {
delayed := func() error {
// Error if batch size exceeds DynamoBatchSize
if len(d.TransactItems) > DynamoBatchSize {
return BatchSizeExceededError
}
var write *dynamodb.TransactWriteItem
switch t := item.(type) {
case KeyValue:
m := make(map[string]*dynamodb.AttributeValue)
appendKeyAttribute(&m, d.table, t)
write = f(m)
default:
dynamoItem, err := dynamodbattribute.MarshalMap(item)
if err != nil {
return err
}
write = f(dynamoItem)
}
d.TransactItems = append(d.TransactItems, write)
return nil
}
d.delayedFunctions = append(d.delayedFunctions, delayed)
return d
}
func (d *transactWriteItemsInput) PutItem(item interface{}, c ...Expression) *transactWriteItemsInput {
i := d.table.PutItem(item)
if len(c) > 0 {
i.SetConditionExpression(c[0])
}
return d.writeItem(item, func(v DynamoDBValue) *dynamodb.TransactWriteItem {
r := &dynamodb.TransactWriteItem{
Put: &dynamodb.Put{
Item: v,
TableName: &d.table.Name,
},
}
b := i.Build()
r.Put.ConditionExpression = b.ConditionExpression
r.Put.ExpressionAttributeNames = b.ExpressionAttributeNames
r.Put.ExpressionAttributeValues = b.ExpressionAttributeValues
return r
})
}
func (d *transactWriteItemsInput) UpdateItem(key KeyValue, update *UpdateExpression, c ...Expression) *transactWriteItemsInput {
i := d.table.UpdateItem(key).SetUpdateExpression(update)
if len(c) > 0 {
i.SetConditionExpression(c[0])
}
return d.writeItem(key, func(v DynamoDBValue) *dynamodb.TransactWriteItem {
r := &dynamodb.TransactWriteItem{
Update: &dynamodb.Update{
Key: v,
TableName: &d.table.Name,
},
}
b, _ := i.Build()
r.Update.ConditionExpression = b.ConditionExpression
r.Update.UpdateExpression = b.UpdateExpression
r.Update.ExpressionAttributeNames = b.ExpressionAttributeNames
r.Update.ExpressionAttributeValues = b.ExpressionAttributeValues
return r
})
}
func (d *transactWriteItemsInput) DeleteItem(key KeyValue, c ...Expression) *transactWriteItemsInput {
i := d.table.DeleteItem(key)
if len(c) > 0 {
i.SetConditionExpression(c[0])
}
return d.writeItem(key, func(v DynamoDBValue) *dynamodb.TransactWriteItem {
r := &dynamodb.TransactWriteItem{
Delete: &dynamodb.Delete{
Key: v,
TableName: &d.table.Name,
},
}
b := i.Build()
r.Delete.ConditionExpression = b.ConditionExpression
r.Delete.ExpressionAttributeNames = b.ExpressionAttributeNames
r.Delete.ExpressionAttributeValues = b.ExpressionAttributeValues
return r
})
}
func (d *transactWriteItemsInput) ConditionCheck(key KeyValue, c Expression) *transactWriteItemsInput {
return d.writeItem(key, func(v DynamoDBValue) *dynamodb.TransactWriteItem {
r := &dynamodb.TransactWriteItem{
ConditionCheck: &dynamodb.ConditionCheck{
Key: v,
TableName: &d.table.Name,
},
}
s, n, m, _ := c.construct("cond", 1, true)
r.ConditionCheck.ConditionExpression = &s
r.ConditionCheck.ExpressionAttributeNames = n
r.ConditionCheck.ExpressionAttributeValues = marshal(m)
return r
})
}
func (d *transactWriteItemsInput) Build() (input *dynamodb.TransactWriteItemsInput, err error) {
for _, function := range d.delayedFunctions {
if err = function(); err != nil {
return
}
}
input = d.TransactWriteItemsInput
return
}
func (d *transactWriteItemsInput) ExecuteWith(ctx context.Context, dynamo DynamoDBIFace, opts ...request.Option) (out *transactWriteItemsOutput) {
out = &transactWriteItemsOutput{
dynamoResult: &dynamoResult{},
}
input, err := d.Build()
if err != nil {
out.err = err
return
}
out.results, out.err = dynamo.TransactWriteItemsWithContext(ctx, input, opts...)
return
}
func (d *transactWriteItemsOutput) Results() (*dynamodb.TransactWriteItemsOutput, error) {
return d.results, d.Error()
}
/***************************************************************************************/
/************************************** BatchWriteItem *********************************/
/***************************************************************************************/
type batchWriteInput struct {
batches []*dynamodb.BatchWriteItemInput
table DynamoTable
delayedFunctions []func() error
}
type batchPutOutput struct {
*dynamoResult
results []*dynamodb.BatchWriteItemOutput
}
/*BatchWriteItem represents dynamo batch write item call*/
func (table DynamoTable) BatchWriteItem() *batchWriteInput {
r := batchWriteInput{
batches: []*dynamodb.BatchWriteItemInput{},
table: table,
}
return &r
}
func (d *batchWriteInput) writeItems(putOnly bool, items ...interface{}) *batchWriteInput {