Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,10 @@ default CompletableFuture<T> deleteItem(T keyItem) {
throw new UnsupportedOperationException();
}

default CompletableFuture<T> deleteItem(T keyItem, boolean useOptimisticLocking) {
throw new UnsupportedOperationException();
}

/**
* Deletes a single item from the mapped table using a supplied primary {@link Key}.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ default T deleteItem(T keyItem) {
throw new UnsupportedOperationException();
}

default T deleteItem(T keyItem, boolean useOptimisticLocking) {
throw new UnsupportedOperationException();
}

/**
* Deletes a single item from the mapped table using a supplied primary {@link Key}.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package software.amazon.awssdk.enhanced.dynamodb.internal.client;

import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import static software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper.conditionallyApplyOptimisticLocking;

import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
Expand Down Expand Up @@ -124,28 +125,55 @@ public CompletableFuture<Void> createTable() {
.build());
}

/**
* Supports optimistic locking via {@link software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper}.
*/
@Override
public CompletableFuture<T> deleteItem(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndexAsync(tableSchema, tableName, extension, dynamoDbClient)
.thenApply(DeleteItemEnhancedResponse::attributes);
}

/**
* Supports optimistic locking via {@link software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper}.
*/
@Override
public CompletableFuture<T> deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItem(builder.build());
}

/**
* Does not support optimistic locking. Use {@link #deleteItem(Object, boolean)} for optimistic locking support.
*/
@Override
public CompletableFuture<T> deleteItem(Key key) {
return deleteItem(r -> r.key(key));
}

/**
* @deprecated Use {@link #deleteItem(Object, boolean)} instead to explicitly control optimistic locking behavior.
*/
@Override
@Deprecated
public CompletableFuture<T> deleteItem(T keyItem) {
return deleteItem(keyFrom(keyItem));
return deleteItem(keyItem, false);
}

/**
* Deletes an item from the table with optional optimistic locking.
*
* @param keyItem the item containing the key to delete
* @param useOptimisticLocking if true, applies optimistic locking if the item has version information
* @return a CompletableFuture containing the deleted item, or null if the item was not found
*/
@Override
public CompletableFuture<T> deleteItem(T keyItem, boolean useOptimisticLocking) {
DeleteItemEnhancedRequest request = DeleteItemEnhancedRequest.builder().key(keyFrom(keyItem)).build();
request = conditionallyApplyOptimisticLocking(request, keyItem, tableSchema, useOptimisticLocking);
return deleteItem(request);
}

@Override
Expand Down Expand Up @@ -311,7 +339,7 @@ public CompletableFuture<T> updateItem(T item) {
public Key keyFrom(T item) {
return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName());
}


@Override
public CompletableFuture<Void> deleteTable() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package software.amazon.awssdk.enhanced.dynamodb.internal.client;

import static software.amazon.awssdk.enhanced.dynamodb.internal.EnhancedClientUtils.createKeyFromItem;
import static software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper.conditionallyApplyOptimisticLocking;

import java.util.ArrayList;
import java.util.function.Consumer;
Expand Down Expand Up @@ -126,27 +127,54 @@ public void createTable() {
.build());
}

/**
* Supports optimistic locking via {@link software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper}.
*/
@Override
public T deleteItem(DeleteItemEnhancedRequest request) {
TableOperation<T, ?, ?, DeleteItemEnhancedResponse<T>> operation = DeleteItemOperation.create(request);
return operation.executeOnPrimaryIndex(tableSchema, tableName, extension, dynamoDbClient).attributes();
}

/**
* Supports optimistic locking via {@link software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper}.
*/
@Override
public T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer) {
DeleteItemEnhancedRequest.Builder builder = DeleteItemEnhancedRequest.builder();
requestConsumer.accept(builder);
return deleteItem(builder.build());
}

/**
* Does not support optimistic locking. Use {@link #deleteItem(Object, boolean)} for optimistic locking support.
*/
@Override
public T deleteItem(Key key) {
return deleteItem(r -> r.key(key));
}

/**
* @deprecated Use {@link #deleteItem(Object, boolean)} instead to explicitly control optimistic locking behavior.
*/
@Override
@Deprecated
public T deleteItem(T keyItem) {
return deleteItem(keyFrom(keyItem));
return deleteItem(keyItem, false);
}

/**
* Deletes an item from the table with optional optimistic locking.
*
* @param keyItem the item containing the key to delete
* @param useOptimisticLocking if true, applies optimistic locking if the item has version information
* @return the deleted item, or null if the item was not found
*/
@Override
public T deleteItem(T keyItem, boolean useOptimisticLocking) {
DeleteItemEnhancedRequest request = DeleteItemEnhancedRequest.builder().key(keyFrom(keyItem)).build();
request = conditionallyApplyOptimisticLocking(request, keyItem, tableSchema, useOptimisticLocking);
return deleteItem(request);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

package software.amazon.awssdk.enhanced.dynamodb.model;

import static software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper.createVersionCondition;

import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
Expand All @@ -24,6 +26,7 @@
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.ReturnConsumedCapacity;
Expand Down Expand Up @@ -289,6 +292,22 @@ public Builder returnValuesOnConditionCheckFailure(String returnValuesOnConditio
return this;
}

/**
* Adds optimistic locking to this delete request.
* <p>
* This method applies a condition expression that ensures the delete operation only succeeds
* if the version attribute of the item matches the provided expected value.
*
* @param versionValue the expected version value that must match for the deletion to succeed
* @param versionAttributeName the name of the version attribute in the DynamoDB table
* @return a builder of this type with optimistic locking condition applied
* @throws IllegalArgumentException if any parameter is null
*/
public Builder withOptimisticLocking(AttributeValue versionValue, String versionAttributeName) {
Expression optimisticLockingCondition = createVersionCondition(versionValue, versionAttributeName);
return conditionExpression(optimisticLockingCondition);
}

public DeleteItemEnhancedRequest build() {
return new DeleteItemEnhancedRequest(this);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/

package software.amazon.awssdk.enhanced.dynamodb.model;

import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;

/**
* Utility class for adding optimistic locking to DynamoDB delete operations.
* <p>
* Optimistic locking prevents concurrent modifications by checking that an item's version hasn't changed since it was last read.
* If the version has changed, the delete operation fails with a {@code ConditionalCheckFailedException}.
*/
@SdkPublicApi
public final class OptimisticLockingHelper {

private OptimisticLockingHelper() {
}

/**
* Adds optimistic locking to a delete request.
*
* @param request the original delete request
* @param versionValue the expected version value
* @param versionAttributeName the version attribute name
* @return delete request with optimistic locking condition
*/
public static DeleteItemEnhancedRequest withOptimisticLocking(
DeleteItemEnhancedRequest request, AttributeValue versionValue, String versionAttributeName) {

Expression conditionExpression = createVersionCondition(versionValue, versionAttributeName);
return request.toBuilder()
.conditionExpression(conditionExpression)
.build();
}

/**
* Adds optimistic locking to a transactional delete request.
*
* @param request the original transactional delete request
* @param versionValue the expected version value
* @param versionAttributeName the version attribute name
* @return transactional delete request with optimistic locking condition
*/
public static TransactDeleteItemEnhancedRequest withOptimisticLocking(
TransactDeleteItemEnhancedRequest request, AttributeValue versionValue, String versionAttributeName) {

Expression conditionExpression = createVersionCondition(versionValue, versionAttributeName);
return request.toBuilder()
.conditionExpression(conditionExpression)
.build();
}

/**
* Conditionally applies optimistic locking if enabled and version information exists.
*
* @param <T> the type of the item
* @param request the original delete request
* @param keyItem the item containing version information
* @param tableSchema the table schema
* @param useOptimisticLocking if true, applies optimistic locking
* @return delete request with optimistic locking if enabled and version exists, otherwise original request
*/
public static <T> DeleteItemEnhancedRequest conditionallyApplyOptimisticLocking(
DeleteItemEnhancedRequest request, T keyItem, TableSchema<T> tableSchema, boolean useOptimisticLocking) {

if (!useOptimisticLocking) {
return request;
}

return getVersionAttributeName(tableSchema)
.map(versionAttributeName -> {
AttributeValue version = tableSchema.attributeValue(keyItem, versionAttributeName);
return version != null ? withOptimisticLocking(request, version, versionAttributeName) : request;
})
.orElse(request);
}

/**
* Conditionally applies optimistic locking if enabled and version information exists.
*
* @param <T> the type of the item
* @param request the original transactional delete request
* @param keyItem the item containing version information
* @param tableSchema the table schema
* @param useOptimisticLocking if true, applies optimistic locking
* @return delete request with optimistic locking if enabled and version exists, otherwise original request
*/
public static <T> TransactDeleteItemEnhancedRequest conditionallyApplyOptimisticLocking(
TransactDeleteItemEnhancedRequest request, T keyItem, TableSchema<T> tableSchema, boolean useOptimisticLocking) {

if (!useOptimisticLocking) {
return request;
}

return getVersionAttributeName(tableSchema)
.map(versionAttributeName -> {
AttributeValue version = tableSchema.attributeValue(keyItem, versionAttributeName);
return version != null ? withOptimisticLocking(request, version, versionAttributeName) : request;
})
.orElse(request);
}


/**
* Creates a version condition expression.
*
* @param versionValue the expected version value
* @param versionAttributeName the version attribute name
* @return version check condition expression
*/
public static Expression createVersionCondition(AttributeValue versionValue, String versionAttributeName) {
return Expression.builder()
.expression(versionAttributeName + " = :version_value")
.putExpressionValue(":version_value", versionValue)
.build();
}

/**
* Gets the version attribute name from table schema.
*
* @param <T> the type of the item
* @param tableSchema the table schema
* @return version attribute name if present, empty otherwise
*/
public static <T> Optional<String> getVersionAttributeName(TableSchema<T> tableSchema) {
return tableSchema.tableMetadata().customMetadataObject("VersionedRecordExtension:VersionAttribute", String.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

package software.amazon.awssdk.enhanced.dynamodb.model;

import static software.amazon.awssdk.enhanced.dynamodb.model.OptimisticLockingHelper.createVersionCondition;

import java.util.Objects;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.NotThreadSafe;
Expand All @@ -24,6 +26,7 @@
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.Expression;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ReturnValuesOnConditionCheckFailure;

/**
Expand Down Expand Up @@ -215,6 +218,21 @@ public Builder returnValuesOnConditionCheckFailure(String returnValuesOnConditio
return this;
}

/**
* Adds optimistic locking to this transactional delete request.
* <p>
* This method applies a condition expression that ensures the delete operation only succeeds if the version attribute of
* the item matches the provided expected value. If the condition fails, the entire transaction will be cancelled.
*
* @param versionValue the expected version value that must match for the deletion to succeed
* @param versionAttributeName the name of the version attribute in the DynamoDB table
* @return a builder of this type with optimistic locking condition applied
* @throws IllegalArgumentException if any parameter is null
*/
public Builder withOptimisticLocking(AttributeValue versionValue, String versionAttributeName) {
Expression optimisticLockingCondition = createVersionCondition(versionValue, versionAttributeName);
return conditionExpression(optimisticLockingCondition);
}

public TransactDeleteItemEnhancedRequest build() {
return new TransactDeleteItemEnhancedRequest(this);
Expand Down
Loading