ryoaska
ryoaska

Reputation: 327

DynamoDB Conditional check on existing item with no value for attribute with @DynamoDBVersionAttribute annotation

From looking at the documentation for attribute @DynamoDBVersionAttribute it says that for put or update calls where the item isn't in the table yet, it will automatically set a value of 1 on the attribute with the annotation. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html

What I'm wondering is, what happens if the item exists, but there is no value in that column. Basically, what happens if I want to add a new version attribute to a table that has a bunch of existing items already, and I try to do an update. Here is the specific scenario I'm looking at:

I want to use DynamoDB Transactions for a use case where I Need to update one table, then increment the count of an attribute in another table. From looking around, I couldn't find any way to do an incremental add in a DDB transaction- the only way I know how to do that is using AttributeValueUpdate + 'AttributeAction.ADD', but this requires using an UpdateItemRequest, and DDB Transactions use the 'Update' item instead.

Instead of doing that I thought I would try to read the value I need to increment first, increment it locally, and then save that value in the transaction, using a conditional check to only update if the count hasn't been changed (version hasn't been updated). However, the table with the value to increment doesn't have any attribute tracking version yet, so it would have to be added. After adding the attribute, how would the logic above turn out for a new item that hasn't had a value added for the new version attribute yet? When I read the version value I would get null back right? So idk if I would be able to set the conditional check up correctly, or if the conditional check would successfully compare the null to null (if that even makes sense to do...) Would I be required to backfill the whole table with 0 first or something before enabling optimistic locking to make this work?

Upvotes: 2

Views: 1421

Answers (1)

jhilden
jhilden

Reputation: 12419

what happens if I want to add a new version attribute to a table that has a bunch of existing items already, and I try to do an update.

If you have a dynamo class annotated with @ DynamoDBVersionAttribute and the previous version is null when the record is updated the version number will be set to 1.

Upvotes: 1

Related Questions