Update Go AWS SDK to the latest version

This commit is contained in:
Andrey Smirnov
2019-07-13 00:03:55 +03:00
committed by Andrey Smirnov
parent d08be990ef
commit 94a72b23ff
2183 changed files with 885887 additions and 228114 deletions
+4878 -867
View File
File diff suppressed because it is too large Load Diff
@@ -31,6 +31,8 @@ func mockCRCResponse(svc *dynamodb.DynamoDB, status int, body, crc string) (req
header.Set("x-amz-crc32", crc)
req, _ = svc.ListTablesRequest(nil)
req.Handlers.Build.RemoveByName("crr.endpointdiscovery")
req.Handlers.Send.PushBack(func(*request.Request) {
req.HTTPResponse = &http.Response{
ContentLength: int64(len(body)),
@@ -119,6 +121,7 @@ func TestValidateCRC32DoesNotMatch(t *testing.T) {
if req.Error == nil {
t.Fatalf("expect error, but got none")
}
req.Handlers.Build.RemoveByName("crr.endpointdiscovery")
aerr := req.Error.(awserr.Error)
if e, a := "CRC32CheckFailed", aerr.Code(); e != a {
+1 -1
View File
@@ -3,7 +3,7 @@ AttributeValue Marshaling and Unmarshaling Helpers
Utility helpers to marshal and unmarshal AttributeValue to and
from Go types can be found in the dynamodbattribute sub package. This package
provides has specialized functions for the common ways of working with
provides specialized functions for the common ways of working with
AttributeValues. Such as map[string]*AttributeValue, []*AttributeValue, and
directly with *AttributeValue. This is helpful for marshaling Go types for API
operations such as PutItem, and unmarshaling Query and Scan APIs' responses.
@@ -1,6 +1,7 @@
package dynamodbattribute
import (
"encoding/base64"
"fmt"
"reflect"
"strconv"
@@ -16,7 +17,7 @@ import (
// Value int
// }
//
// func (u *exampleUnmarshaler) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
// func (u *ExampleUnmarshaler) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
// if av.N == nil {
// return nil
// }
@@ -26,7 +27,7 @@ import (
// return err
// }
//
// u.Value = n
// u.Value = int(n)
// return nil
// }
type Unmarshaler interface {
@@ -538,6 +539,16 @@ func (d *Decoder) decodeString(s *string, v reflect.Value, fieldTag tag) error {
switch v.Kind() {
case reflect.String:
v.SetString(*s)
case reflect.Slice:
// To maintain backwards compatibility with the ConvertFrom family of methods
// which converted []byte into base64-encoded strings if the input was typed
if v.Type() == byteSliceType {
decoded, err := base64.StdEncoding.DecodeString(*s)
if err != nil {
return &UnmarshalError{Err: err, Value: "string", Type: v.Type()}
}
v.SetBytes(decoded)
}
case reflect.Interface:
// Ensure type aliasing is handled properly
v.Set(reflect.ValueOf(*s).Convert(v.Type()))
@@ -727,9 +738,9 @@ func (e *InvalidUnmarshalError) Message() string {
return "cannot unmarshal to nil value, " + e.Type.String()
}
// An UnmarshalError wraps an error that occured while unmarshaling a DynamoDB
// An UnmarshalError wraps an error that occurred while unmarshaling a DynamoDB
// AttributeValue element into a Go type. This is different from UnmarshalTypeError
// in that it wraps the underlying error that occured.
// in that it wraps the underlying error that occurred.
type UnmarshalError struct {
Err error
Value string
@@ -234,6 +234,30 @@ func TestUnmarshalListError(t *testing.T) {
}
}
func TestUnmarshalConvertToData(t *testing.T) {
type T struct {
Int int
Str string
ByteSlice []byte
StrSlice []string
}
exp := T{
Int: 42,
Str: "foo",
ByteSlice: []byte{42, 97, 83},
StrSlice: []string{"cat", "dog"},
}
av, err := ConvertToMap(exp)
if err != nil {
t.Fatalf("expect no error, got %v", err)
}
var act T
err = UnmarshalMap(av, &act)
assertConvertTest(t, 0, act, exp, err, nil)
}
func TestUnmarshalMapShared(t *testing.T) {
for i, c := range sharedMapTestCases {
err := UnmarshalMap(c.in, c.actual)
@@ -81,7 +81,7 @@
// The ConvertTo, ConvertToList, ConvertToMap, ConvertFrom, ConvertFromMap
// and ConvertFromList methods have been deprecated. The Marshal and Unmarshal
// functions should be used instead. The ConvertTo|From marshallers do not
// support BinarySet, NumberSet, nor StringSets, and will incorrect marshal
// support BinarySet, NumberSet, nor StringSets, and will incorrectly marshal
// binary data fields in structs as base64 strings.
//
// The Marshal and Unmarshal functions correct this behavior, and removes
@@ -91,5 +91,11 @@
// replaced with have been replaced with dynamodbattribute.Marshaler and
// dynamodbattribute.Unmarshaler interfaces.
//
// The Unmarshal functions are backwards compatible with data marshalled by
// ConvertTo*, but the reverse is not true: objects marshalled using Marshal
// are not necessarily usable by ConvertFrom*. This backward compatibility is
// intended to assist with incremental upgrading of data following a switch
// away from the Convert* family of functions.
//
// `time.Time` is marshaled as RFC3339 format.
package dynamodbattribute
@@ -189,6 +189,11 @@ type MarshalOptions struct {
//
// Enabled by default.
SupportJSONTags bool
// Support other custom struct tag keys, such as `yaml` or `toml`.
// Note that values provided with a custom TagKey must also be supported
// by the (un)marshalers in this package.
TagKey string
}
// An Encoder provides marshaling Go value types to AttributeValues.
@@ -99,8 +99,12 @@ func enumFields(t reflect.Type, opts MarshalOptions) []field {
fieldTag := tag{}
fieldTag.parseAVTag(sf.Tag)
if opts.SupportJSONTags && fieldTag == (tag{}) {
fieldTag.parseJSONTag(sf.Tag)
// Because MarshalOptions.TagKey must be explicitly set, use it
// over JSON, which is enabled by default.
if opts.TagKey != "" && fieldTag == (tag{}) {
fieldTag.parseStructTag(opts.TagKey, sf.Tag)
} else if opts.SupportJSONTags && fieldTag == (tag{}) {
fieldTag.parseStructTag("json", sf.Tag)
}
if fieldTag.Ignore {
@@ -571,3 +571,65 @@ func BenchmarkMarshal(b *testing.B) {
}
}
}
func Test_Encode_YAML_TagKey(t *testing.T) {
input := struct {
String string `yaml:"string"`
EmptyString string `yaml:"empty"`
OmitString string `yaml:"omitted,omitempty"`
Ignored string `yaml:"-"`
Byte []byte `yaml:"byte"`
Float32 float32 `yaml:"float32"`
Float64 float64 `yaml:"float64"`
Int int `yaml:"int"`
Uint uint `yaml:"uint"`
Slice []string `yaml:"slice"`
Map map[string]int `yaml:"map"`
NoTag string
}{
String: "String",
Ignored: "Ignored",
Slice: []string{"one", "two"},
Map: map[string]int{
"one": 1,
"two": 2,
},
NoTag: "NoTag",
}
expected := &dynamodb.AttributeValue{
M: map[string]*dynamodb.AttributeValue{
"string": {S: aws.String("String")},
"empty": {NULL: &trueValue},
"byte": {NULL: &trueValue},
"float32": {N: aws.String("0")},
"float64": {N: aws.String("0")},
"int": {N: aws.String("0")},
"uint": {N: aws.String("0")},
"slice": {
L: []*dynamodb.AttributeValue{
{S: aws.String("one")},
{S: aws.String("two")},
},
},
"map": {
M: map[string]*dynamodb.AttributeValue{
"one": {N: aws.String("1")},
"two": {N: aws.String("2")},
},
},
"NoTag": {S: aws.String("NoTag")},
},
}
enc := NewEncoder(func(e *Encoder) {
e.TagKey = "yaml"
})
actual, err := enc.Encode(input)
if err != nil {
t.Errorf("Encode with input %#v retured error `%s`, expected nil", input, err)
}
compareObjects(t, expected, actual)
}
@@ -24,8 +24,8 @@ func (t *tag) parseAVTag(structTag reflect.StructTag) {
t.parseTagStr(tagStr)
}
func (t *tag) parseJSONTag(structTag reflect.StructTag) {
tagStr := structTag.Get("json")
func (t *tag) parseStructTag(tag string, structTag reflect.StructTag) {
tagStr := structTag.Get(tag)
if len(tagStr) == 0 {
return
}
@@ -35,7 +35,7 @@ func TestTagParse(t *testing.T) {
for i, c := range cases {
actual := tag{}
if c.json {
actual.parseJSONTag(c.in)
actual.parseStructTag("json", c.in)
}
if c.av {
actual.parseAVTag(c.in)
@@ -103,10 +103,18 @@ type DynamoDBAPI interface {
DescribeContinuousBackupsWithContext(aws.Context, *dynamodb.DescribeContinuousBackupsInput, ...request.Option) (*dynamodb.DescribeContinuousBackupsOutput, error)
DescribeContinuousBackupsRequest(*dynamodb.DescribeContinuousBackupsInput) (*request.Request, *dynamodb.DescribeContinuousBackupsOutput)
DescribeEndpoints(*dynamodb.DescribeEndpointsInput) (*dynamodb.DescribeEndpointsOutput, error)
DescribeEndpointsWithContext(aws.Context, *dynamodb.DescribeEndpointsInput, ...request.Option) (*dynamodb.DescribeEndpointsOutput, error)
DescribeEndpointsRequest(*dynamodb.DescribeEndpointsInput) (*request.Request, *dynamodb.DescribeEndpointsOutput)
DescribeGlobalTable(*dynamodb.DescribeGlobalTableInput) (*dynamodb.DescribeGlobalTableOutput, error)
DescribeGlobalTableWithContext(aws.Context, *dynamodb.DescribeGlobalTableInput, ...request.Option) (*dynamodb.DescribeGlobalTableOutput, error)
DescribeGlobalTableRequest(*dynamodb.DescribeGlobalTableInput) (*request.Request, *dynamodb.DescribeGlobalTableOutput)
DescribeGlobalTableSettings(*dynamodb.DescribeGlobalTableSettingsInput) (*dynamodb.DescribeGlobalTableSettingsOutput, error)
DescribeGlobalTableSettingsWithContext(aws.Context, *dynamodb.DescribeGlobalTableSettingsInput, ...request.Option) (*dynamodb.DescribeGlobalTableSettingsOutput, error)
DescribeGlobalTableSettingsRequest(*dynamodb.DescribeGlobalTableSettingsInput) (*request.Request, *dynamodb.DescribeGlobalTableSettingsOutput)
DescribeLimits(*dynamodb.DescribeLimitsInput) (*dynamodb.DescribeLimitsOutput, error)
DescribeLimitsWithContext(aws.Context, *dynamodb.DescribeLimitsInput, ...request.Option) (*dynamodb.DescribeLimitsOutput, error)
DescribeLimitsRequest(*dynamodb.DescribeLimitsInput) (*request.Request, *dynamodb.DescribeLimitsOutput)
@@ -172,6 +180,14 @@ type DynamoDBAPI interface {
TagResourceWithContext(aws.Context, *dynamodb.TagResourceInput, ...request.Option) (*dynamodb.TagResourceOutput, error)
TagResourceRequest(*dynamodb.TagResourceInput) (*request.Request, *dynamodb.TagResourceOutput)
TransactGetItems(*dynamodb.TransactGetItemsInput) (*dynamodb.TransactGetItemsOutput, error)
TransactGetItemsWithContext(aws.Context, *dynamodb.TransactGetItemsInput, ...request.Option) (*dynamodb.TransactGetItemsOutput, error)
TransactGetItemsRequest(*dynamodb.TransactGetItemsInput) (*request.Request, *dynamodb.TransactGetItemsOutput)
TransactWriteItems(*dynamodb.TransactWriteItemsInput) (*dynamodb.TransactWriteItemsOutput, error)
TransactWriteItemsWithContext(aws.Context, *dynamodb.TransactWriteItemsInput, ...request.Option) (*dynamodb.TransactWriteItemsOutput, error)
TransactWriteItemsRequest(*dynamodb.TransactWriteItemsInput) (*request.Request, *dynamodb.TransactWriteItemsOutput)
UntagResource(*dynamodb.UntagResourceInput) (*dynamodb.UntagResourceOutput, error)
UntagResourceWithContext(aws.Context, *dynamodb.UntagResourceInput, ...request.Option) (*dynamodb.UntagResourceOutput, error)
UntagResourceRequest(*dynamodb.UntagResourceInput) (*request.Request, *dynamodb.UntagResourceOutput)
@@ -184,6 +200,10 @@ type DynamoDBAPI interface {
UpdateGlobalTableWithContext(aws.Context, *dynamodb.UpdateGlobalTableInput, ...request.Option) (*dynamodb.UpdateGlobalTableOutput, error)
UpdateGlobalTableRequest(*dynamodb.UpdateGlobalTableInput) (*request.Request, *dynamodb.UpdateGlobalTableOutput)
UpdateGlobalTableSettings(*dynamodb.UpdateGlobalTableSettingsInput) (*dynamodb.UpdateGlobalTableSettingsOutput, error)
UpdateGlobalTableSettingsWithContext(aws.Context, *dynamodb.UpdateGlobalTableSettingsInput, ...request.Option) (*dynamodb.UpdateGlobalTableSettingsOutput, error)
UpdateGlobalTableSettingsRequest(*dynamodb.UpdateGlobalTableSettingsInput) (*request.Request, *dynamodb.UpdateGlobalTableSettingsOutput)
UpdateItem(*dynamodb.UpdateItemInput) (*dynamodb.UpdateItemOutput, error)
UpdateItemWithContext(aws.Context, *dynamodb.UpdateItemInput, ...request.Option) (*dynamodb.UpdateItemOutput, error)
UpdateItemRequest(*dynamodb.UpdateItemInput) (*request.Request, *dynamodb.UpdateItemOutput)
+136 -9
View File
@@ -8,7 +8,7 @@ const (
// "BackupInUseException".
//
// There is another ongoing conflicting backup control plane operation on the
// table. The backups is either being created, deleted or restored to a table.
// table. The backup is either being created, deleted or restored to a table.
ErrCodeBackupInUseException = "BackupInUseException"
// ErrCodeBackupNotFoundException for service response error code
@@ -41,6 +41,19 @@ const (
// The specified global table does not exist.
ErrCodeGlobalTableNotFoundException = "GlobalTableNotFoundException"
// ErrCodeIdempotentParameterMismatchException for service response error code
// "IdempotentParameterMismatchException".
//
// DynamoDB rejected the request because you retried a request with a different
// payload but with an idempotent token that was already used.
ErrCodeIdempotentParameterMismatchException = "IdempotentParameterMismatchException"
// ErrCodeIndexNotFoundException for service response error code
// "IndexNotFoundException".
//
// The operation tried to access a nonexistent index.
ErrCodeIndexNotFoundException = "IndexNotFoundException"
// ErrCodeInternalServerError for service response error code
// "InternalServerError".
//
@@ -64,18 +77,18 @@ const (
// ErrCodeLimitExceededException for service response error code
// "LimitExceededException".
//
// Up to 50 CreateBackup operations are allowed per second, per account. There
// is no limit to the number of daily on-demand backups that can be taken.
// There is no limit to the number of daily on-demand backups that can be taken.
//
// Up to 10 simultaneous table operations are allowed per account. These operations
// Up to 50 simultaneous table operations are allowed per account. These operations
// include CreateTable, UpdateTable, DeleteTable,UpdateTimeToLive, RestoreTableFromBackup,
// and RestoreTableToPointInTime.
//
// For tables with secondary indexes, only one of those tables can be in the
// CREATING state at any point in time. Do not attempt to create more than one
// such table simultaneously.
// The only exception is when you are creating a table with one or more secondary
// indexes. You can have up to 25 such requests running at a time; however,
// if the table or index specifications are complex, DynamoDB might temporarily
// reduce the number of concurrent operations.
//
// The total limit of tables in the ACTIVE state is 250.
// There is a soft account limit of 256 tables.
ErrCodeLimitExceededException = "LimitExceededException"
// ErrCodePointInTimeRecoveryUnavailableException for service response error code
@@ -91,7 +104,7 @@ const (
// requests that receive this exception. Your request is eventually successful,
// unless your retry queue is too large to finish. Reduce the frequency of requests
// and use exponential backoff. For more information, go to Error Retries and
// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff)
// Exponential Backoff (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff)
// in the Amazon DynamoDB Developer Guide.
ErrCodeProvisionedThroughputExceededException = "ProvisionedThroughputExceededException"
@@ -107,6 +120,14 @@ const (
// The specified replica is no longer part of the global table.
ErrCodeReplicaNotFoundException = "ReplicaNotFoundException"
// ErrCodeRequestLimitExceeded for service response error code
// "RequestLimitExceeded".
//
// Throughput exceeds the current throughput limit for your account. Please
// contact AWS Support at AWS Support (https://aws.amazon.com/support) to request
// a limit increase.
ErrCodeRequestLimitExceeded = "RequestLimitExceeded"
// ErrCodeResourceInUseException for service response error code
// "ResourceInUseException".
//
@@ -140,4 +161,110 @@ const (
// A source table with the name TableName does not currently exist within the
// subscriber's account.
ErrCodeTableNotFoundException = "TableNotFoundException"
// ErrCodeTransactionCanceledException for service response error code
// "TransactionCanceledException".
//
// The entire transaction request was canceled.
//
// DynamoDB cancels a TransactWriteItems request under the following circumstances:
//
// * A condition in one of the condition expressions is not met.
//
// * A table in the TransactWriteItems request is in a different account
// or region.
//
// * More than one action in the TransactWriteItems operation targets the
// same item.
//
// * There is insufficient provisioned capacity for the transaction to be
// completed.
//
// * An item size becomes too large (larger than 400 KB), or a local secondary
// index (LSI) becomes too large, or a similar validation error occurs because
// of changes made by the transaction.
//
// * The aggregate size of the items in the transaction exceeds 4 MBs.
//
// * There is a user error, such as an invalid data format.
//
// DynamoDB cancels a TransactGetItems request under the following circumstances:
//
// * There is an ongoing TransactGetItems operation that conflicts with a
// concurrent PutItem, UpdateItem, DeleteItem or TransactWriteItems request.
// In this case the TransactGetItems operation fails with a TransactionCanceledException.
//
// * A table in the TransactGetItems request is in a different account or
// region.
//
// * There is insufficient provisioned capacity for the transaction to be
// completed.
//
// * The aggregate size of the items in the transaction exceeds 4 MBs.
//
// * There is a user error, such as an invalid data format.
//
// If using Java, DynamoDB lists the cancellation reasons on the CancellationReasons
// property. This property is not set for other languages. Transaction cancellation
// reasons are ordered in the order of requested items, if an item has no error
// it will have NONE code and Null message.
//
// Cancellation reason codes and possible error messages:
//
// * No Errors: Code: NONE Message: null
//
// * Conditional Check Failed: Code: ConditionalCheckFailed Message: The
// conditional request failed.
//
// * Item Collection Size Limit Exceeded: Code: ItemCollectionSizeLimitExceeded
// Message: Collection size exceeded.
//
// * Transaction Conflict: Code: TransactionConflict Message: Transaction
// is ongoing for the item.
//
// * Provisioned Throughput Exceeded: Code: ProvisionedThroughputExceeded
// Messages: The level of configured provisioned throughput for the table
// was exceeded. Consider increasing your provisioning level with the UpdateTable
// API. This Message is received when provisioned throughput is exceeded
// is on a provisioned DynamoDB table. The level of configured provisioned
// throughput for one or more global secondary indexes of the table was exceeded.
// Consider increasing your provisioning level for the under-provisioned
// global secondary indexes with the UpdateTable API. This message is returned
// when provisioned throughput is exceeded is on a provisioned GSI.
//
// * Throttling Error: Code: ThrottlingError Messages: Throughput exceeds
// the current capacity of your table or index. DynamoDB is automatically
// scaling your table or index so please try again shortly. If exceptions
// persist, check if you have a hot key: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html.
// This message is returned when writes get throttled on an On-Demand table
// as DynamoDB is automatically scaling the table. Throughput exceeds the
// current capacity for one or more global secondary indexes. DynamoDB is
// automatically scaling your index so please try again shortly. This message
// is returned when when writes get throttled on an On-Demand GSI as DynamoDB
// is automatically scaling the GSI.
//
// * Validation Error: Code: ValidationError Messages: One or more parameter
// values were invalid. The update expression attempted to update the secondary
// index key beyond allowed size limits. The update expression attempted
// to update the secondary index key to unsupported type. An operand in the
// update expression has an incorrect data type. Item size to update has
// exceeded the maximum allowed size. Number overflow. Attempting to store
// a number with magnitude larger than supported range. Type mismatch for
// attribute to update. Nesting Levels have exceeded supported limits. The
// document path provided in the update expression is invalid for update.
// The provided expression refers to an attribute that does not exist in
// the item.
ErrCodeTransactionCanceledException = "TransactionCanceledException"
// ErrCodeTransactionConflictException for service response error code
// "TransactionConflictException".
//
// Operation was rejected because there is an ongoing transaction for the item.
ErrCodeTransactionConflictException = "TransactionConflictException"
// ErrCodeTransactionInProgressException for service response error code
// "TransactionInProgressException".
//
// The transaction with the given request token is already in progress.
ErrCodeTransactionInProgressException = "TransactionInProgressException"
)
+26 -4
View File
@@ -28,7 +28,7 @@ func parseTime(layout, value string) *time.Time {
// To retrieve multiple items from a table
//
// This example reads multiple items from the Music table using a batch of three GetItem
// requests. Only the AlbumTitle attribute is returned.
// requests. Only the AlbumTitle attribute is returned.
func ExampleDynamoDB_BatchGetItem_shared00() {
svc := dynamodb.New(session.New())
input := &dynamodb.BatchGetItemInput{
@@ -73,6 +73,8 @@ func ExampleDynamoDB_BatchGetItem_shared00() {
fmt.Println(dynamodb.ErrCodeProvisionedThroughputExceededException, aerr.Error())
case dynamodb.ErrCodeResourceNotFoundException:
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -157,6 +159,8 @@ func ExampleDynamoDB_BatchWriteItem_shared00() {
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fmt.Println(dynamodb.ErrCodeItemCollectionSizeLimitExceededException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -259,6 +263,10 @@ func ExampleDynamoDB_DeleteItem_shared00() {
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fmt.Println(dynamodb.ErrCodeItemCollectionSizeLimitExceededException, aerr.Error())
case dynamodb.ErrCodeTransactionConflictException:
fmt.Println(dynamodb.ErrCodeTransactionConflictException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -395,6 +403,8 @@ func ExampleDynamoDB_GetItem_shared00() {
fmt.Println(dynamodb.ErrCodeProvisionedThroughputExceededException, aerr.Error())
case dynamodb.ErrCodeResourceNotFoundException:
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -472,6 +482,10 @@ func ExampleDynamoDB_PutItem_shared00() {
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fmt.Println(dynamodb.ErrCodeItemCollectionSizeLimitExceededException, aerr.Error())
case dynamodb.ErrCodeTransactionConflictException:
fmt.Println(dynamodb.ErrCodeTransactionConflictException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -514,6 +528,8 @@ func ExampleDynamoDB_Query_shared00() {
fmt.Println(dynamodb.ErrCodeProvisionedThroughputExceededException, aerr.Error())
case dynamodb.ErrCodeResourceNotFoundException:
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -539,8 +555,8 @@ func ExampleDynamoDB_Scan_shared00() {
svc := dynamodb.New(session.New())
input := &dynamodb.ScanInput{
ExpressionAttributeNames: map[string]*string{
"AT": aws.String("AlbumTitle"),
"ST": aws.String("SongTitle"),
"#AT": aws.String("AlbumTitle"),
"#ST": aws.String("SongTitle"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":a": {
@@ -560,6 +576,8 @@ func ExampleDynamoDB_Scan_shared00() {
fmt.Println(dynamodb.ErrCodeProvisionedThroughputExceededException, aerr.Error())
case dynamodb.ErrCodeResourceNotFoundException:
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -579,7 +597,7 @@ func ExampleDynamoDB_Scan_shared00() {
// To update an item in a table
//
// This example updates an item in the Music table. It adds a new attribute (Year) and
// modifies the AlbumTitle attribute. All of the attributes in the item, as they appear
// modifies the AlbumTitle attribute. All of the attributes in the item, as they appear
// after the update, are returned in the response.
func ExampleDynamoDB_UpdateItem_shared00() {
svc := dynamodb.New(session.New())
@@ -621,6 +639,10 @@ func ExampleDynamoDB_UpdateItem_shared00() {
fmt.Println(dynamodb.ErrCodeResourceNotFoundException, aerr.Error())
case dynamodb.ErrCodeItemCollectionSizeLimitExceededException:
fmt.Println(dynamodb.ErrCodeItemCollectionSizeLimitExceededException, aerr.Error())
case dynamodb.ErrCodeTransactionConflictException:
fmt.Println(dynamodb.ErrCodeTransactionConflictException, aerr.Error())
case dynamodb.ErrCodeRequestLimitExceeded:
fmt.Println(dynamodb.ErrCodeRequestLimitExceeded, aerr.Error())
case dynamodb.ErrCodeInternalServerError:
fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
default:
@@ -94,6 +94,7 @@ func ExampleBuilder_WithKeyCondition() {
// Use the built expression to populate the DynamoDB Query's API input
// parameters.
input := &dynamodb.QueryInput{
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
KeyConditionExpression: expr.KeyCondition(),
ProjectionExpression: expr.Projection(),
+24 -21
View File
@@ -46,13 +46,13 @@ func (l typeList) Swap(i, j int) {
// proj := expression.NamesList(expression.Name("aName"), expression.Name("anotherName"), expression.Name("oneOtherName"))
//
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
// expr := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// KeyConditionExpression: expr.KeyCondition(),
// ProjectionExpression: expr.Projection(),
// ExpressionAttributeNames: expr.Names(),
// ExpressionAttributeValues: expr.Values(),
// TableName: aws.String("SomeTable"),
// }
type Builder struct {
@@ -89,13 +89,13 @@ func NewBuilder() Builder {
// // Add keyCond and proj to builder as a Key Condition and Projection
// // respectively
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
// expr := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// KeyConditionExpression: expr.KeyCondition(),
// ProjectionExpression: expr.Projection(),
// ExpressionAttributeNames: expr.Names(),
// ExpressionAttributeValues: expr.Values(),
// TableName: aws.String("SomeTable"),
// }
func (b Builder) Build() (Expression, error) {
@@ -177,7 +177,7 @@ func (b Builder) buildChildTrees() (aliasList, map[expressionType]string, error)
// // existing ProjectionBuilder
// builder = builder.WithProjection(proj)
// // create an Expression struct
// expression := builder.Build()
// expr := builder.Build()
func (b Builder) WithCondition(conditionBuilder ConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
@@ -201,7 +201,7 @@ func (b Builder) WithCondition(conditionBuilder ConditionBuilder) Builder {
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
// expr := builder.Build()
func (b Builder) WithProjection(projectionBuilder ProjectionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
@@ -225,7 +225,7 @@ func (b Builder) WithProjection(projectionBuilder ProjectionBuilder) Builder {
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
// expr := builder.Build()
func (b Builder) WithKeyCondition(keyConditionBuilder KeyConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
@@ -249,7 +249,7 @@ func (b Builder) WithKeyCondition(keyConditionBuilder KeyConditionBuilder) Build
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
// expr := builder.Build()
func (b Builder) WithFilter(filterBuilder ConditionBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
@@ -273,7 +273,7 @@ func (b Builder) WithFilter(filterBuilder ConditionBuilder) Builder {
// // existing ConditionBuilder
// builder = builder.WithCondition(cond)
// // create an Expression struct
// expression := builder.Build()
// expr := builder.Build()
func (b Builder) WithUpdate(updateBuilder UpdateBuilder) Builder {
if b.expressionMap == nil {
b.expressionMap = map[expressionType]treeBuilder{}
@@ -296,13 +296,13 @@ func (b Builder) WithUpdate(updateBuilder UpdateBuilder) Builder {
// // Add keyCond and proj to builder as a Key Condition and Projection
// // respectively
// builder := expression.NewBuilder().WithKeyCondition(keyCond).WithProjection(proj)
// expression := builder.Build()
// expr := builder.Build()
//
// queryInput := dynamodb.QueryInput{
// KeyConditionExpression: expression.KeyCondition(),
// ProjectionExpression: expression.Projection(),
// ExpressionAttributeNames: expression.Names(),
// ExpressionAttributeValues: expression.Values(),
// KeyConditionExpression: expr.KeyCondition(),
// ProjectionExpression: expr.Projection(),
// ExpressionAttributeNames: expr.Names(),
// ExpressionAttributeValues: expr.Values(),
// TableName: aws.String("SomeTable"),
// }
type Expression struct {
@@ -488,7 +488,10 @@ func (e Expression) returnExpression(expressionType expressionType) *string {
if e.expressionMap == nil {
return nil
}
return aws.String(e.expressionMap[expressionType])
if s, exists := e.expressionMap[expressionType]; exists {
return &s
}
return nil
}
// exprNode are the generic nodes that represents both Operands and
@@ -978,6 +978,39 @@ func TestBuildExpressionString(t *testing.T) {
}
}
func TestReturnExpression(t *testing.T) {
cases := []struct {
name string
input Expression
expected *string
}{
{
name: "projection exists",
input: Expression{
expressionMap: map[expressionType]string{
projection: "#0, #1, #2",
},
},
expected: aws.String("#0, #1, #2"),
},
{
name: "projection not exists",
input: Expression{
expressionMap: map[expressionType]string{},
},
expected: nil,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
actual := c.input.returnExpression(projection)
if e, a := c.expected, actual; !reflect.DeepEqual(a, e) {
t.Errorf("expect %v, got %v", e, a)
}
})
}
}
func TestAliasValue(t *testing.T) {
cases := []struct {
name string
+60
View File
@@ -0,0 +1,60 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// +build go1.10,integration
package dynamodb_test
import (
"context"
"testing"
"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/awstesting/integration"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
var _ aws.Config
var _ awserr.Error
var _ request.Request
func TestInteg_00_ListTables(t *testing.T) {
ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()
sess := integration.SessionWithDefaultRegion("us-west-2")
svc := dynamodb.New(sess)
params := &dynamodb.ListTablesInput{
Limit: aws.Int64(1),
}
_, err := svc.ListTablesWithContext(ctx, params)
if err != nil {
t.Errorf("expect no error, got %v", err)
}
}
func TestInteg_01_DescribeTable(t *testing.T) {
ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()
sess := integration.SessionWithDefaultRegion("us-west-2")
svc := dynamodb.New(sess)
params := &dynamodb.DescribeTableInput{
TableName: aws.String("fake-table"),
}
_, err := svc.DescribeTableWithContext(ctx, params)
if err == nil {
t.Fatalf("expect request to fail")
}
aerr, ok := err.(awserr.RequestFailure)
if !ok {
t.Fatalf("expect awserr, was %T", err)
}
if len(aerr.Code()) == 0 {
t.Errorf("expect non-empty error code")
}
if v := aerr.Code(); v == request.ErrCodeSerialization {
t.Errorf("expect API error code got serialization failure")
}
}
+7 -2
View File
@@ -6,6 +6,7 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/crr"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/jsonrpc"
@@ -19,6 +20,7 @@ import (
// modify mutate any of the struct's properties though.
type DynamoDB struct {
*client.Client
endpointCache *crr.EndpointCache
}
// Used for custom client initialization logic
@@ -29,8 +31,9 @@ var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "dynamodb" // Service endpoint prefix API calls made to.
EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata.
ServiceName = "dynamodb" // Name of service.
EndpointsID = ServiceName // ID to lookup a service endpoint with.
ServiceID = "DynamoDB" // ServiceID is a unique identifer of a specific service.
)
// New creates a new instance of the DynamoDB client with a session.
@@ -55,6 +58,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
Endpoint: endpoint,
@@ -65,6 +69,7 @@ func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio
handlers,
),
}
svc.endpointCache = crr.NewEndpointCache(10)
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)