Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 49 additions & 18 deletions dynamo_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,18 @@ func (repository *Repository) prepareUpdateWithUpdateExpressions(
return update, nil
}

// ConditionalUpdateWithUpdateExpressions updates an item with update expressions and optional conditions defined at field level, enabling you to set
// different update expressions for each field. The first key of the updateMap specifies the Update expression to use
// for the expressions in the map
func (repository *Repository) ConditionalUpdateWithUpdateExpressions(
ctx context.Context,
key KeyInterface,
updateExpressions UpdateExpressions,
updateOptions ...UpdateOption,
) (bool, error) {
return repository.updateWithUpdateExpressions(ctx, key, updateExpressions, updateOptions...)
}

// UpdateWithUpdateExpressions updates an item with update expressions defined at field level, enabling you to set
// different update expressions for each field. The first key of the updateMap specifies the Update expression to use
// for the expressions in the map
Expand All @@ -199,24 +211,8 @@ func (repository *Repository) UpdateWithUpdateExpressions(
key KeyInterface,
updateExpressions UpdateExpressions,
) error {
update, err := repository.prepareUpdateWithUpdateExpressions(ctx, key, updateExpressions)
if err != nil {
repository.log.error(ctx, key.TableName(), err.Error())
return err
}

err = update.RunWithContext(ctx)
if err != nil {
repository.log.error(ctx, key.TableName(), err.Error())
return err
}

err = repository.metrics.Publish(ctx, key.TableName(), MetricNameUpdatedItemsCount, float64(1))
if err != nil {
repository.log.error(ctx, key.TableName(), err.Error())
}

return nil
_, err := repository.updateWithUpdateExpressions(ctx, key, updateExpressions)
return err
}

// UpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions defined at field level and returns
Expand Down Expand Up @@ -593,3 +589,38 @@ func (repository Repository) ScanIteratorWithContext(ctx context.Context, key Ke

return itr, nil
}

func (repository *Repository) updateWithUpdateExpressions(
ctx context.Context,
key KeyInterface,
updateExpressions UpdateExpressions,
updateOptions ...UpdateOption,
) (bool, error) {
update, err := repository.prepareUpdateWithUpdateExpressions(ctx, key, updateExpressions)
if err != nil {
repository.log.error(ctx, key.TableName(), err.Error())
return false, err
}

for i := range updateOptions {
updateOptions[i](update)
}

err = update.RunWithContext(ctx)
if err != nil {
if awserr, ok := err.(awserr.Error); ok && awserr.Code() == dynamodb.ErrCodeConditionalCheckFailedException && len(updateOptions) > 0 {
repository.log.info(ctx, key.TableName(), dynamodb.ErrCodeConditionalCheckFailedException)
return false, nil
}

repository.log.error(ctx, key.TableName(), err.Error())
return false, err
}

err = repository.metrics.Publish(ctx, key.TableName(), MetricNameUpdatedItemsCount, float64(1))
if err != nil {
repository.log.error(ctx, key.TableName(), err.Error())
}

return true, nil
}
4 changes: 4 additions & 0 deletions dynamo_repository_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ type RepositoryInterface interface {
// for the expressions in the map
UpdateWithUpdateExpressions(ctx context.Context, key KeyInterface, updateExpressions UpdateExpressions) error

// ConditionalUpdateWithUpdateExpressions updates an item with update expressions and optional conditions defined at field level
// if no conditions were provided within UpdateOption, a normal update will be performed
ConditionalUpdateWithUpdateExpressions(ctx context.Context, key KeyInterface, updateExpressions UpdateExpressions, updateOptions ...UpdateOption) (bool, error)

// UpdateWithUpdateExpressionsAndReturnValue updates an item with update expressions defined at field level and returns
// the item, as it appears after the update, enabling you to set different update expressions for each field. The first
// key of the updateMap specifies the Update expression to use for the expressions in the map
Expand Down
93 changes: 87 additions & 6 deletions mock/dynamo_api_mock_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type DynamoMock struct {
QueryOutput *dynamodb.QueryOutput
ScanAllOutput *dynamodb.ScanOutput
Input *dynamodb.PutItemInput
UpdateItemInput *dynamodb.UpdateItemInput
DeleteItemInput *dynamodb.DeleteItemInput
Inputs *dynamodb.BatchWriteItemInput
DeleteInputs *dynamodb.BatchWriteItemInput
Expand Down Expand Up @@ -213,6 +214,37 @@ func (d *DynamoMock) WithInput(value map[string]interface{}) DynamoDBOption {
}
}

// WithUpdateItemInput register option dynamodb UpdateItemInput
func (d *DynamoMock) WithUpdateItemInput(updateExpr string, value interface{}, opts ...UpdateOption) DynamoDBOption {
return func(args *DynamoMock) {
if d.ExpressionAttributeValues == nil {
d.ExpressionAttributeValues = make(map[string]*dynamodb.AttributeValue)
}

expr := d.prepareExpression(updateExpr, value)
for i := range expr.avFields {
d.ExpressionAttributeValues[expr.avFields[i]] = expr.marshaledAVs[i]
}

args.UpdateItemInput = &dynamodb.UpdateItemInput{
Key: d.Hash,
UpdateExpression: &expr.preparedExpr,
TableName: aws.String(d.TableName),
ReturnValues: aws.String("NONE"),
}
for i := range opts {
opts[i](d)
}

args.UpdateItemInput.ExpressionAttributeValues = d.ExpressionAttributeValues
if d.ConditionExpression != nil {
args.UpdateItemInput.ConditionExpression = d.ConditionExpression
}

args.InputMatcher = gomock.Eq(args.UpdateItemInput)
}
}

// WithInput register option dynamodb PutItemInput
func (d *DynamoMock) WithDeleteInput(value map[string]interface{}) DynamoDBOption {
return func(args *DynamoMock) {
Expand Down Expand Up @@ -313,12 +345,16 @@ func (d *DynamoMock) WithCondition(field string, value interface{}, operator str
// WithConditionExpression register option dynamodb GetItemOutput
func (d *DynamoMock) WithConditionExpression(expression string, value interface{}) DynamoDBOption {
return func(args *DynamoMock) {
d.ExpressionAttributeValues = make(map[string]*dynamodb.AttributeValue)
expressionAttributeValueField := ":v0"
expression = strings.Replace(expression, "?", expressionAttributeValueField, 1)
av, _ := dynamodbattribute.Marshal(value)
d.ExpressionAttributeValues[expressionAttributeValueField] = av
d.ConditionExpression = &expression
if d.ExpressionAttributeValues == nil {
d.ExpressionAttributeValues = make(map[string]*dynamodb.AttributeValue)
}

expr := d.prepareExpression(expression, value)
for i := range expr.avFields {
d.ExpressionAttributeValues[expr.avFields[i]] = expr.marshaledAVs[i]
}

d.ConditionExpression = &expr.preparedExpr
}
}

Expand Down Expand Up @@ -521,6 +557,28 @@ func (d *DynamoMock) addCall(method string, input interface{}, output interface{
return d
}

func (d *DynamoMock) prepareExpression(expr string, values ...interface{}) preparedExpression {
currentAttributeStartIndex := len(d.ExpressionAttributeValues)

avFields := make([]string, 0, len(values))
marshaledAVs := make([]*dynamodb.AttributeValue, 0, len(values))

for i, val := range values {
expressionAttributeValueField := ":v" + strconv.Itoa(currentAttributeStartIndex+i)
expr = strings.Replace(expr, "?", expressionAttributeValueField, 1)

avFields = append(avFields, expressionAttributeValueField)
av, _ := dynamodbattribute.Marshal(val)
marshaledAVs = append(marshaledAVs, av)
}

return preparedExpression{
avFields: avFields,
preparedExpr: expr,
marshaledAVs: marshaledAVs,
}
}

// getAttributeValue return dynamodb.AttributeValue from interface type
func getAttributeValue(value interface{}) *dynamodb.AttributeValue {
attributeValue := dynamodb.AttributeValue{}
Expand Down Expand Up @@ -549,3 +607,26 @@ type call struct {
output interface{}
err interface{}
}

type preparedExpression struct {
avFields []string
preparedExpr string
marshaledAVs []*dynamodb.AttributeValue
}

type UpdateOption func(m *DynamoMock)

func WithCondition(conditionExpression string, conditionArgs ...interface{}) func(m *DynamoMock) {
return func(m *DynamoMock) {
if m.ExpressionAttributeValues == nil {
m.ExpressionAttributeValues = make(map[string]*dynamodb.AttributeValue)
}

expr := m.prepareExpression(conditionExpression, conditionArgs...)
for i := range expr.avFields {
m.ExpressionAttributeValues[expr.avFields[i]] = expr.marshaledAVs[i]
}

m.ConditionExpression = &expr.preparedExpr
}
}
4 changes: 2 additions & 2 deletions repository_save_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import (
"context"
"time"

"github.com/adjoeio/djoemo/mock"
"github.com/bouk/monkey"
"github.com/pkg/errors"
"go.uber.org/mock/gomock"

"github.com/adjoeio/djoemo/mock"

. "github.com/adjoeio/djoemo"
)

Expand Down Expand Up @@ -341,7 +342,6 @@ var _ = Describe("Repository", func() {

metricsMock.EXPECT().WithContext(context.TODO()).Return(metricsMock)
metricsMock.EXPECT().Publish(key.TableName(), MetricNameSavedItemsCount, float64(1)).Return(nil)
logMock.EXPECT().WithContext(context.TODO()).Return(logMock)
err := repository.SaveItem(key, user)
Expect(err).To(BeNil())
})
Expand Down
Loading