Skip to content
Merged
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
3 changes: 2 additions & 1 deletion put_item.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ type PutOption func(*dynamodb.PutItemInput) error
// Each update increments the version number and if the update fails fetch the record again to get latest version number and try again
func WithOptimisticLock(key string, currentVersion uint) PutOption {
return func(input *dynamodb.PutItemInput) error {
condition := "#version = :oldVersion"
// Ensure the condition expression is set to check if the version attribute does not exist or matches the old version
condition := "attribute_not_exists(#version) or #version = :oldVersion"
input.ConditionExpression = &condition
if input.ExpressionAttributeNames == nil {
input.ExpressionAttributeNames = map[string]string{}
Expand Down
9 changes: 1 addition & 8 deletions tests/putitem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,15 +109,8 @@ type LedgerAccount struct {

func TestPutItemWithOptimisticLock(t *testing.T) {
table := prepareTable(t, dynamoEndpoint, "put_optimistic_test")
// Create new account item in DynamoDB with default values
account := LedgerAccount{ID: "123"}
ctx := context.Background()
pk := dynago.StringValue("123")
err := table.PutItem(ctx, pk, pk, account)
if err != nil {
t.Fatalf("unexpected error %s", err)
return
}

// Update method will add 100 to the current account balance
update := func() error {
Expand Down Expand Up @@ -151,7 +144,7 @@ func TestPutItemWithOptimisticLock(t *testing.T) {
// We expect account balance to be 1000 after 10 update
// If any update method overwrote with an outdated value then total balance will be less than 1000
var acc LedgerAccount
err, _ = table.GetItem(ctx, pk, pk, &acc)
err, _ := table.GetItem(ctx, pk, pk, &acc)
if err != nil {
t.Fatalf("unexpected error %s", err)
return
Expand Down