/
dynamodb.go
2412 lines (2064 loc) · 81.8 KB
/
dynamodb.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
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 dynamodb
/*
* Copyright 2020 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// =================================================================================================================
// AWS CREDENTIAL:
// use $> aws configure (to set aws access key and secret to target machine)
// Store AWS Access ID and Secret Key into Default Profile Using '$ aws configure' cli
// =================================================================================================================
import (
awshttp2 "github.com/aldelo/common/wrapper/aws"
"github.com/aldelo/common/wrapper/aws/awsregion"
"github.com/aws/aws-dax-go/dax"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
"net/http"
util "github.com/aldelo/common"
"context"
"errors"
"time"
)
// ================================================================================================================
// STRUCTS
// ================================================================================================================
// DynamoDB struct encapsulates the AWS DynamoDB access functionality
//
// Notes:
// 1) to use dax, must be within vpc with dax cluster subnet pointing to private ip subnet of the vpc
// 2) dax is not accessible outside of vpc
// 3) on ec2 or container within vpc, also need aws credential via aws cli too = aws configure
type DynamoDB struct {
// define the AWS region that dynamodb is serviced from
AwsRegion awsregion.AWSRegion
// custom http2 client options
HttpOptions *awshttp2.HttpClientSettings
// define the Dax Endpoint (required if using DAX)
DaxEndpoint string
// dynamodb connection object
cn *dynamodb.DynamoDB
// dax connection object
cnDax *dax.Dax
// if dax is enabled, skip dax will skip dax and route direct to DynamoDB
// if dax is not enabled, skip dax true or not will always route to DynamoDB
SkipDax bool
// operating table
TableName string
PKName string
SKName string
// last execute param string
LastExecuteParamsPayload string
}
// DynamoDBError struct contains special status info including error and retry advise
type DynamoDBError struct {
ErrorMessage string
SuppressError bool
AllowRetry bool
RetryNeedsBackOff bool
}
// Error returns error string of the struct object
func (e *DynamoDBError) Error() string {
return e.ErrorMessage
}
// DynamoDBTableKeys struct defines the PK and SK fields to be used in key search (Always PK and SK)
//
// important
// if dynamodb table is defined as PK and SK together, then to search, MUST use PK and SK together or error will trigger
//
// ResultItemPtr = optional, used with TransactionGetItems() to denote output unmarshal object target
type DynamoDBTableKeys struct {
PK string
SK string
ResultItemPtr interface{} `dynamodbav:"-"`
resultProcessed bool
}
// DynamoDBUnprocessedItemsAndKeys defines struct to slices of items and keys
type DynamoDBUnprocessedItemsAndKeys struct {
PutItems []map[string]*dynamodb.AttributeValue
DeleteKeys []*DynamoDBTableKeys
}
// UnmarshalPutItems will convert struct's PutItems into target slice of struct objects
//
// notes:
// resultItemsPtr interface{} = Input is Slice of Actual Struct Objects
func (u *DynamoDBUnprocessedItemsAndKeys) UnmarshalPutItems(resultItemsPtr interface{}) error {
if u == nil {
return errors.New("UnmarshalPutItems Failed: (Validate) " + "DynamoDBUnprocessedItemsAndKeys Object Nil")
}
if resultItemsPtr == nil {
return errors.New("UnmarshalPutItems Failed: (Validate) " + "ResultItems Object Nil")
}
if err := dynamodbattribute.UnmarshalListOfMaps(u.PutItems, resultItemsPtr); err != nil {
return errors.New("UnmarshalPutItems Failed: (Unmarshal) " + err.Error())
} else {
// success
return nil
}
}
// DynamoDBUpdateItemInput defines a single item update instruction
//
// important
// if dynamodb table is defined as PK and SK together, then to search, MUST use PK and SK together or error will trigger
//
// parameters:
// pkValue = required, value of partition key to seek
// skValue = optional, value of sort key to seek; set to blank if value not provided
//
// updateExpression = required, ATTRIBUTES ARE CASE SENSITIVE; set remove add or delete action expression, see Rules URL for full detail
// Rules:
// 1) https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html
// Usage Syntax:
// 1) Action Keywords are: set, add, remove, delete
// 2) Each Action Keyword May Appear in UpdateExpression Only Once
// 3) Each Action Keyword Grouping May Contain One or More Actions, Such as 'set price=:p, age=:age, etc' (each action separated by comma)
// 4) Each Action Keyword Always Begin with Action Keyword itself, such as 'set ...', 'add ...', etc
// 5) If Attribute is Numeric, Action Can Perform + or - Operation in Expression, such as 'set age=age-:newAge, price=price+:price, etc'
// 6) If Attribute is Slice, Action Can Perform Slice Element Operation in Expression, such as 'set age[2]=:newData, etc'
// 7) When Attribute Name is Reserved Keyword, Use ExpressionAttributeNames to Define #xyz to Alias
// a) Use the #xyz in the KeyConditionExpression such as #yr = :year (:year is Defined ExpressionAttributeValue)
// 8) When Attribute is a List, Use list_append(a, b, ...) in Expression to append elements (list_append() is case sensitive)
// a) set #ri = list_append(#ri, :vals) where :vals represents one or more of elements to add as in L
// 9) if_not_exists(path, value)
// a) Avoids existing attribute if already exists
// b) set price = if_not_exists(price, :p)
// c) if_not_exists is case sensitive; path is the existing attribute to check
// 10) Action Type Purposes
// a) SET = add one or more attributes to an item; overrides existing attributes in item with new values; if attribute is number, able to perform + or - operations
// b) REMOVE = remove one or more attributes from an item, to remove multiple attributes, separate by comma; remove element from list use xyz[1] index notation
// c) ADD = adds a new attribute and its values to an item; if attribute is number and already exists, value will add up or subtract
// d) DELETE = supports only on set data types; deletes one or more elements from a set, such as 'delete color :c'
// 11) Example
// a) set age=:age, name=:name, etc
// b) set age=age-:age, num=num+:num, etc
//
// conditionExpress = optional, ATTRIBUTES ARE CASE SENSITIVE; sets conditions for this condition expression, set to blank if not used
// Usage Syntax:
// 1) "size(info.actors) >= :num"
// a) When Length of Actors Attribute Value is Equal or Greater Than :num, ONLY THEN UpdateExpression is Performed
// 2) ExpressionAttributeName and ExpressionAttributeValue is Still Defined within ExpressionAttributeNames and ExpressionAttributeValues Where Applicable
//
// expressionAttributeNames = optional, ATTRIBUTES ARE CASE SENSITIVE; set nil if not used, must define for attribute names that are reserved keywords such as year, data etc. using #xyz
// Usage Syntax:
// 1) map[string]*string: where string is the #xyz, and *string is the original xyz attribute name
// a) map[string]*string { "#xyz": aws.String("Xyz"), }
// 2) Add to Map
// a) m := make(map[string]*string)
// b) m["#xyz"] = aws.String("Xyz")
//
// expressionAttributeValues = required, ATTRIBUTES ARE CASE SENSITIVE; sets the value token and value actual to be used within the keyConditionExpression; this sets both compare token and compare value
// Usage Syntax:
// 1) map[string]*dynamodb.AttributeValue: where string is the :xyz, and *dynamodb.AttributeValue is { S: aws.String("abc"), },
// a) map[string]*dynamodb.AttributeValue { ":xyz" : { S: aws.String("abc"), }, ":xyy" : { N: aws.String("123"), }, }
// 2) Add to Map
// a) m := make(map[string]*dynamodb.AttributeValue)
// b) m[":xyz"] = &dynamodb.AttributeValue{ S: aws.String("xyz") }
// 3) Slice of Strings -> CONVERT To Slice of *dynamodb.AttributeValue = []string -> []*dynamodb.AttributeValue
// a) av, err := dynamodbattribute.MarshalList(xyzSlice)
// b) ExpressionAttributeValue, Use 'L' To Represent the List for av defined in 3.a above
type DynamoDBUpdateItemInput struct {
PK string
SK string
UpdateExpression string
ConditionExpression string
ExpressionAttributeNames map[string]*string
ExpressionAttributeValues map[string]*dynamodb.AttributeValue
}
// DynamoDBTransactionWrites defines one or more items to put, update or delete
//
// notes
// PutItems interface{} = is Slice of PutItems: []Xyz
// a) We use interface{} because []interface{} will require each element conversion (instead we will handle conversion by internal code)
// b) PutItems ALWAYS Slice of Struct (Value), NOT pointers to Structs
type DynamoDBTransactionWrites struct {
PutItems interface{}
UpdateItems []*DynamoDBUpdateItemInput
DeleteItems []*DynamoDBTableKeys
TableNameOverride string
}
// MarshalPutItems will marshal dynamodb transaction writes' put items into []map[string]*dynamodb.AttributeValue
func (w *DynamoDBTransactionWrites) MarshalPutItems() (result []map[string]*dynamodb.AttributeValue, err error) {
if w == nil {
return nil, errors.New("MarshalPutItems Failed: (Validate) " + "DynamoDBTransactionWrites Object Nil")
}
// validate
if w.PutItems == nil {
// no PutItems
return nil, nil
}
// get []interface{}
itemsIf := util.SliceObjectsToSliceInterface(w.PutItems)
if itemsIf == nil {
// no PutItems
return nil, errors.New("MarshalPutItems Failed: (Slice Convert) " + "Interface Slice Nil")
}
if len(itemsIf) <= 0 {
// no PutItems
return nil, nil
}
// loop thru each put item to marshal
for _, v := range itemsIf {
if m, e := dynamodbattribute.MarshalMap(v); e != nil {
return nil, errors.New("MarshalPutItems Failed: (Marshal) " + e.Error())
} else {
if m != nil {
result = append(result, m)
} else {
return nil, errors.New("MarshalPutItems Failed: (Marshal) " + "Marshaled Result Nil")
}
}
}
// return result
return result, nil
}
// DynamoDBTransactionReads defines one or more items to get by PK / SK
type DynamoDBTransactionReads struct {
Keys []*DynamoDBTableKeys
TableNameOverride string
}
// ================================================================================================================
// STRUCTS FUNCTIONS
// ================================================================================================================
// ----------------------------------------------------------------------------------------------------------------
// utility functions
// ----------------------------------------------------------------------------------------------------------------
// handleError is an internal helper method to evaluate dynamodb error,
// and to advise if retry, immediate retry, suppress error etc error handling advisory
//
// notes:
// RetryNeedsBackOff = true indicates when doing retry, must wait an arbitrary time duration before retry; false indicates immediate is ok
func (d *DynamoDB) handleError(err error, errorPrefix ...string) *DynamoDBError {
if err != nil {
prefix := ""
if len(errorPrefix) > 0 {
prefix = errorPrefix[0] + " "
}
prefixType := ""
if aerr, ok := err.(awserr.Error); ok {
// aws errors
prefixType = "[AWS] "
switch aerr.Code() {
case dynamodb.ErrCodeConditionalCheckFailedException:
fallthrough
case dynamodb.ErrCodeResourceInUseException:
fallthrough
case dynamodb.ErrCodeResourceNotFoundException:
fallthrough
case dynamodb.ErrCodeIdempotentParameterMismatchException:
fallthrough
case dynamodb.ErrCodeBackupInUseException:
fallthrough
case dynamodb.ErrCodeBackupNotFoundException:
fallthrough
case dynamodb.ErrCodeContinuousBackupsUnavailableException:
fallthrough
case dynamodb.ErrCodeGlobalTableAlreadyExistsException:
fallthrough
case dynamodb.ErrCodeGlobalTableNotFoundException:
fallthrough
case dynamodb.ErrCodeIndexNotFoundException:
fallthrough
case dynamodb.ErrCodeInvalidRestoreTimeException:
fallthrough
case dynamodb.ErrCodePointInTimeRecoveryUnavailableException:
fallthrough
case dynamodb.ErrCodeReplicaAlreadyExistsException:
fallthrough
case dynamodb.ErrCodeReplicaNotFoundException:
fallthrough
case dynamodb.ErrCodeTableAlreadyExistsException:
fallthrough
case dynamodb.ErrCodeTableInUseException:
fallthrough
case dynamodb.ErrCodeTableNotFoundException:
fallthrough
case dynamodb.ErrCodeTransactionCanceledException:
fallthrough
case dynamodb.ErrCodeTransactionConflictException:
fallthrough
case dynamodb.ErrCodeTransactionInProgressException:
// show error + no retry
return &DynamoDBError{
ErrorMessage: prefix + prefixType + aerr.Code() + " - " + aerr.Message(),
SuppressError: false,
AllowRetry: false,
RetryNeedsBackOff: false,
}
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fallthrough
case dynamodb.ErrCodeLimitExceededException:
// show error + allow retry with backoff
return &DynamoDBError{
ErrorMessage: prefix + prefixType + aerr.Code() + " - " + aerr.Message(),
SuppressError: false,
AllowRetry: true,
RetryNeedsBackOff: true,
}
case dynamodb.ErrCodeProvisionedThroughputExceededException:
fallthrough
case dynamodb.ErrCodeRequestLimitExceeded:
// no error + allow retry with backoff
return &DynamoDBError{
ErrorMessage: prefix + prefixType + aerr.Code() + " - " + aerr.Message(),
SuppressError: true,
AllowRetry: true,
RetryNeedsBackOff: true,
}
case dynamodb.ErrCodeInternalServerError:
// no error + allow auto retry without backoff
return &DynamoDBError{
ErrorMessage: prefix + prefixType + aerr.Code() + " - " + aerr.Message(),
SuppressError: true,
AllowRetry: true,
RetryNeedsBackOff: false,
}
default:
return &DynamoDBError{
ErrorMessage: prefix + prefixType + aerr.Code() + " - " + aerr.Message(),
SuppressError: false,
AllowRetry: false,
RetryNeedsBackOff: false,
}
}
} else {
// other errors
prefixType = "[General] "
return &DynamoDBError{
ErrorMessage: prefix + prefixType + err.Error(),
SuppressError: false,
AllowRetry: false,
RetryNeedsBackOff: false,
}
}
} else {
// no error
return nil
}
}
// Connect will establish a connection to the dynamodb service
func (d *DynamoDB) Connect() error {
// clean up prior cn reference
d.cn = nil
d.SkipDax = false
if !d.AwsRegion.Valid() || d.AwsRegion == awsregion.UNKNOWN {
return errors.New("Connect To DynamoDB Failed: (AWS Session Error) " + "Region is Required")
}
// create custom http2 client if needed
var httpCli *http.Client
var httpErr error
if d.HttpOptions == nil {
d.HttpOptions = new(awshttp2.HttpClientSettings)
}
// use custom http2 client
h2 := &awshttp2.AwsHttp2Client{
Options: d.HttpOptions,
}
if httpCli, httpErr = h2.NewHttp2Client(); httpErr != nil {
return errors.New("Connect to DynamoDB Failed: (AWS Session Error) " + "Create Custom Http2 Client Errored = " + httpErr.Error())
}
// establish aws session connection and connect to dynamodb service
if sess, err := session.NewSession(
&aws.Config{
Region: aws.String(d.AwsRegion.Key()),
HTTPClient: httpCli,
}); err != nil {
// aws session error
return errors.New("Connect To DynamoDB Failed: (AWS Session Error) " + err.Error())
} else {
// aws session obtained
d.cn = dynamodb.New(sess)
if d.cn == nil {
return errors.New("Connect To DynamoDB Failed: (New DynamoDB Connection) " + "Connection Object Nil")
}
// successfully connected to dynamodb service
return nil
}
}
// EnableDax will enable dax service for this dynamodb session
func (d *DynamoDB) EnableDax() error {
if d.cn == nil {
return errors.New("Enable Dax Failed: " + "DynamoDB Not Yet Connected")
}
cfg := dax.DefaultConfig()
cfg.HostPorts = []string{ d.DaxEndpoint }
cfg.Region = d.AwsRegion.Key()
var err error
d.cnDax, err = dax.New(cfg)
if err != nil {
d.cnDax = nil
return errors.New("Enable Dax Failed: " + err.Error())
}
// default skip dax to false
d.SkipDax = false
// success
return nil
}
// DisableDax will disable dax service for this dynamodb session
func (d *DynamoDB) DisableDax() {
if d.cnDax != nil {
_ = d.cnDax.Close()
d.cnDax = nil
d.SkipDax = false
}
}
// do_PutItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_PutItem(input *dynamodb.PutItemInput, ctx ...aws.Context) (output *dynamodb.PutItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.PutItem(input)
} else {
return d.cnDax.PutItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.PutItem(input)
} else {
return d.cn.PutItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB PutItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_UpdateItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_UpdateItem(input *dynamodb.UpdateItemInput, ctx ...aws.Context) (output *dynamodb.UpdateItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.UpdateItem(input)
} else {
return d.cnDax.UpdateItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.UpdateItem(input)
} else {
return d.cn.UpdateItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB UpdateItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_DeleteItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_DeleteItem(input *dynamodb.DeleteItemInput, ctx ...aws.Context) (output *dynamodb.DeleteItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.DeleteItem(input)
} else {
return d.cnDax.DeleteItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.DeleteItem(input)
} else {
return d.cn.DeleteItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB DeleteItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_GetItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_GetItem(input *dynamodb.GetItemInput, ctx ...aws.Context) (output *dynamodb.GetItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.GetItem(input)
} else {
return d.cnDax.GetItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.GetItem(input)
} else {
return d.cn.GetItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB GetItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_Query is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_Query(input *dynamodb.QueryInput, pagedQuery bool, pagedQueryPageCountLimit *int64, ctx ...aws.Context) (output *dynamodb.QueryOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if !pagedQuery {
//
// not paged query
//
if len(ctx) <= 0 {
return d.cnDax.Query(input)
} else {
return d.cnDax.QueryWithContext(ctx[0], input)
}
} else {
//
// paged query
//
pageCount := int64(0)
fn := func(pageOutput *dynamodb.QueryOutput, lastPage bool) bool {
if pageOutput != nil {
if pageOutput.Items != nil && len(pageOutput.Items) > 0 {
pageCount++
if output == nil {
output = new(dynamodb.QueryOutput)
}
output.SetCount(aws.Int64Value(output.Count) + aws.Int64Value(pageOutput.Count))
output.SetScannedCount(aws.Int64Value(output.ScannedCount) + aws.Int64Value(pageOutput.ScannedCount))
output.SetLastEvaluatedKey(pageOutput.LastEvaluatedKey)
for _, v := range pageOutput.Items {
output.Items = append(output.Items, v)
}
// check if ok to stop
if pagedQueryPageCountLimit != nil && *pagedQueryPageCountLimit > 0 {
if pageCount >= *pagedQueryPageCountLimit {
return false
}
}
}
}
return !lastPage
}
if len(ctx) <= 0 {
err = d.cnDax.QueryPages(input, fn)
} else {
err = d.cnDax.QueryPagesWithContext(ctx[0], input, fn)
}
return output, err
}
} else if d.cn != nil {
// dynamodb
if !pagedQuery {
//
// not paged query
//
if len(ctx) <= 0 {
return d.cn.Query(input)
} else {
return d.cn.QueryWithContext(ctx[0], input)
}
} else {
//
// paged query
//
pageCount := int64(0)
fn := func(pageOutput *dynamodb.QueryOutput, lastPage bool) bool {
if pageOutput != nil {
if pageOutput.Items != nil && len(pageOutput.Items) > 0 {
pageCount++
if output == nil {
output = new(dynamodb.QueryOutput)
}
output.SetCount(aws.Int64Value(output.Count) + aws.Int64Value(pageOutput.Count))
output.SetScannedCount(aws.Int64Value(output.ScannedCount) + aws.Int64Value(pageOutput.ScannedCount))
output.SetLastEvaluatedKey(pageOutput.LastEvaluatedKey)
for _, v := range pageOutput.Items {
output.Items = append(output.Items, v)
}
// check if ok to stop
if pagedQueryPageCountLimit != nil && *pagedQueryPageCountLimit > 0 {
if pageCount >= *pagedQueryPageCountLimit {
return false
}
}
}
}
return !lastPage
}
if len(ctx) <= 0 {
err = d.cn.QueryPages(input, fn)
} else {
err = d.cn.QueryPagesWithContext(ctx[0], input, fn)
}
return output, err
}
} else {
// connection error
return nil, errors.New("DynamoDB QueryItems Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_Scan is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_Scan(input *dynamodb.ScanInput, pagedQuery bool, pagedQueryPageCountLimit *int64, ctx ...aws.Context) (output *dynamodb.ScanOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if !pagedQuery {
//
// not paged query
//
if len(ctx) <= 0 {
return d.cnDax.Scan(input)
} else {
return d.cnDax.ScanWithContext(ctx[0], input)
}
} else {
//
// paged query
//
pageCount := int64(0)
fn := func(pageOutput *dynamodb.ScanOutput, lastPage bool) bool {
if pageOutput != nil {
if pageOutput.Items != nil && len(pageOutput.Items) > 0 {
pageCount++
if output == nil {
output = new(dynamodb.ScanOutput)
}
output.SetCount(aws.Int64Value(output.Count) + aws.Int64Value(pageOutput.Count))
output.SetScannedCount(aws.Int64Value(output.ScannedCount) + aws.Int64Value(pageOutput.ScannedCount))
output.SetLastEvaluatedKey(pageOutput.LastEvaluatedKey)
for _, v := range pageOutput.Items {
output.Items = append(output.Items, v)
}
if pagedQueryPageCountLimit != nil && *pagedQueryPageCountLimit > 0 {
if pageCount >= *pagedQueryPageCountLimit {
return false
}
}
}
}
return !lastPage
}
if len(ctx) <= 0 {
err = d.cnDax.ScanPages(input, fn)
} else {
err = d.cnDax.ScanPagesWithContext(ctx[0], input, fn)
}
return output, err
}
} else if d.cn != nil {
// dynamodb
if !pagedQuery {
//
// not paged query
//
if len(ctx) <= 0 {
return d.cn.Scan(input)
} else {
return d.cn.ScanWithContext(ctx[0], input)
}
} else {
//
// paged query
//
pageCount := int64(0)
fn := func(pageOutput *dynamodb.ScanOutput, lastPage bool) bool {
if pageOutput != nil {
if pageOutput.Items != nil && len(pageOutput.Items) > 0 {
pageCount++
if output == nil {
output = new(dynamodb.ScanOutput)
}
output.SetCount(aws.Int64Value(output.Count) + aws.Int64Value(pageOutput.Count))
output.SetScannedCount(aws.Int64Value(output.ScannedCount) + aws.Int64Value(pageOutput.ScannedCount))
output.SetLastEvaluatedKey(pageOutput.LastEvaluatedKey)
for _, v := range pageOutput.Items {
output.Items = append(output.Items, v)
}
if pagedQueryPageCountLimit != nil && *pagedQueryPageCountLimit > 0 {
if pageCount >= *pagedQueryPageCountLimit {
return false
}
}
}
}
return !lastPage
}
if len(ctx) <= 0 {
err = d.cn.ScanPages(input, fn)
} else {
err = d.cn.ScanPagesWithContext(ctx[0], input, fn)
}
return output, err
}
} else {
// connection error
return nil, errors.New("DynamoDB ScanItems Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_BatchWriteItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_BatchWriteItem(input *dynamodb.BatchWriteItemInput, ctx ...aws.Context) (output *dynamodb.BatchWriteItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.BatchWriteItem(input)
} else {
return d.cnDax.BatchWriteItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.BatchWriteItem(input)
} else {
return d.cn.BatchWriteItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB BatchWriteItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_BatchGetItem is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_BatchGetItem(input *dynamodb.BatchGetItemInput, ctx ...aws.Context) (output *dynamodb.BatchGetItemOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.BatchGetItem(input)
} else {
return d.cnDax.BatchGetItemWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.BatchGetItem(input)
} else {
return d.cn.BatchGetItemWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB BatchGetItem Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_TransactWriteItems is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_TransactWriteItems(input *dynamodb.TransactWriteItemsInput, ctx ...aws.Context) (output *dynamodb.TransactWriteItemsOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.TransactWriteItems(input)
} else {
return d.cnDax.TransactWriteItemsWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.TransactWriteItems(input)
} else {
return d.cn.TransactWriteItemsWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB TransactionWriteItems Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// do_TransactGetItems is a helper that calls either dax or dynamodb based on dax availability
func (d *DynamoDB) do_TransactGetItems(input *dynamodb.TransactGetItemsInput, ctx ...aws.Context) (output *dynamodb.TransactGetItemsOutput, err error) {
if d.cnDax != nil && !d.SkipDax {
// dax
if len(ctx) <= 0 {
return d.cnDax.TransactGetItems(input)
} else {
return d.cnDax.TransactGetItemsWithContext(ctx[0], input)
}
} else if d.cn != nil {
// dynamodb
if len(ctx) <= 0 {
return d.cn.TransactGetItems(input)
} else {
return d.cn.TransactGetItemsWithContext(ctx[0], input)
}
} else {
// connection error
return nil, errors.New("DynamoDB TransactionGetItems Failed: " + "No DynamoDB or Dax Connection Available")
}
}
// PutItem will add a new item into dynamodb table
//
// parameters:
// item = required, must be a struct object; ALWAYS SINGLE STRUCT OBJECT, NEVER SLICE
// must start with fields 'pk string', 'sk string', and 'data string' before any other attributes
// timeOutDuration = optional, timeout duration sent via context to scan method; nil if not using timeout duration
//
// notes:
// item struct tags
// use `json:"" dynamodbav:""`
// json = sets the name used in json
// dynamodbav = sets the name used in dynamodb
// reference child element
// if struct has field with complex type (another struct), to reference it in code, use the parent struct field dot child field notation
// Info in parent struct with struct tag as info; to reach child element: info.xyz
func (d *DynamoDB) PutItem(item interface{}, timeOutDuration *time.Duration) *DynamoDBError {
if d.cn == nil {
return d.handleError(errors.New("DynamoDB Connection is Required"))
}
if util.LenTrim(d.TableName) <= 0 {
return d.handleError(errors.New("DynamoDB Table Name is Required"))
}
if item == nil {
return d.handleError(errors.New("DynamoDB PutItem Failed: " + "Input Item Object is Nil"))
}
if av, err := dynamodbattribute.MarshalMap(item); err != nil {
return d.handleError(err, "DynamoDB PutItem Failed: (MarshalMap)")
} else {
input := &dynamodb.PutItemInput{
Item: av,
TableName: aws.String(d.TableName),
}
// record params payload
d.LastExecuteParamsPayload = "PutItem = " + input.String()
// save into dynamodb table
if timeOutDuration != nil {
ctx, cancel := context.WithTimeout(context.Background(), *timeOutDuration)
defer cancel()
_, err = d.do_PutItem(input, ctx)
} else {
_, err = d.do_PutItem(input)
}
if err != nil {
return d.handleError(err, "DynamoDB PutItem Failed: (PutItem)")
}
}
// put item was successful
return nil
}
// UpdateItem will update dynamodb item in given table using primary key (PK, SK), and set specific attributes with new value and persists
// UpdateItem requires using Primary Key attributes, and limited to TWO key attributes in condition maximum;
//
// important
// if dynamodb table is defined as PK and SK together, then to search, MUST use PK and SK together or error will trigger
//
// parameters:
// pkValue = required, value of partition key to seek
// skValue = optional, value of sort key to seek; set to blank if value not provided
//
// updateExpression = required, ATTRIBUTES ARE CASE SENSITIVE; set remove add or delete action expression, see Rules URL for full detail
// Rules:
// 1) https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html
// Usage Syntax:
// 1) Action Keywords are: set, add, remove, delete
// 2) Each Action Keyword May Appear in UpdateExpression Only Once
// 3) Each Action Keyword Grouping May Contain One or More Actions, Such as 'set price=:p, age=:age, etc' (each action separated by comma)
// 4) Each Action Keyword Always Begin with Action Keyword itself, such as 'set ...', 'add ...', etc
// 5) If Attribute is Numeric, Action Can Perform + or - Operation in Expression, such as 'set age=age-:newAge, price=price+:price, etc'
// 6) If Attribute is Slice, Action Can Perform Slice Element Operation in Expression, such as 'set age[2]=:newData, etc'
// 7) When Attribute Name is Reserved Keyword, Use ExpressionAttributeNames to Define #xyz to Alias
// a) Use the #xyz in the KeyConditionExpression such as #yr = :year (:year is Defined ExpressionAttributeValue)
// 8) When Attribute is a List, Use list_append(a, b, ...) in Expression to append elements (list_append() is case sensitive)
// a) set #ri = list_append(#ri, :vals) where :vals represents one or more of elements to add as in L
// 9) if_not_exists(path, value)
// a) Avoids existing attribute if already exists
// b) set price = if_not_exists(price, :p)
// c) if_not_exists is case sensitive; path is the existing attribute to check
// 10) Action Type Purposes
// a) SET = add one or more attributes to an item; overrides existing attributes in item with new values; if attribute is number, able to perform + or - operations
// b) REMOVE = remove one or more attributes from an item, to remove multiple attributes, separate by comma; remove element from list use xyz[1] index notation
// c) ADD = adds a new attribute and its values to an item; if attribute is number and already exists, value will add up or subtract
// d) DELETE = supports only on set data types; deletes one or more elements from a set, such as 'delete color :c'
// 11) Example
// a) set age=:age, name=:name, etc
// b) set age=age-:age, num=num+:num, etc
//
// conditionExpress = optional, ATTRIBUTES ARE CASE SENSITIVE; sets conditions for this condition expression, set to blank if not used
// Usage Syntax:
// 1) "size(info.actors) >= :num"
// a) When Length of Actors Attribute Value is Equal or Greater Than :num, ONLY THEN UpdateExpression is Performed
// 2) ExpressionAttributeName and ExpressionAttributeValue is Still Defined within ExpressionAttributeNames and ExpressionAttributeValues Where Applicable
//
// expressionAttributeNames = optional, ATTRIBUTES ARE CASE SENSITIVE; set nil if not used, must define for attribute names that are reserved keywords such as year, data etc. using #xyz
// Usage Syntax:
// 1) map[string]*string: where string is the #xyz, and *string is the original xyz attribute name
// a) map[string]*string { "#xyz": aws.String("Xyz"), }
// 2) Add to Map
// a) m := make(map[string]*string)
// b) m["#xyz"] = aws.String("Xyz")
//
// expressionAttributeValues = required, ATTRIBUTES ARE CASE SENSITIVE; sets the value token and value actual to be used within the keyConditionExpression; this sets both compare token and compare value
// Usage Syntax:
// 1) map[string]*dynamodb.AttributeValue: where string is the :xyz, and *dynamodb.AttributeValue is { S: aws.String("abc"), },
// a) map[string]*dynamodb.AttributeValue { ":xyz" : { S: aws.String("abc"), }, ":xyy" : { N: aws.String("123"), }, }
// 2) Add to Map