Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Adding support for AttributeUpdates (#579)

Nahuel Nucera2e819da85411
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.py
index 9c3d65db..552271c3 100644
--- a/ministack/services/dynamodb.py
+++ b/ministack/services/dynamodb.py
@@ -659,11 +659,17 @@ def _update_item(data):
return _conditional_check_failed(data, existing)
update_expr = data.get("UpdateExpression", "")
+ attribute_updates = data.get("AttributeUpdates")
eav = data.get("ExpressionAttributeValues", {})
ean = data.get("ExpressionAttributeNames", {})
+ if update_expr and attribute_updates:
+ return error_response_json("ValidationException", "Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}", 400)
+
if update_expr:
item = _apply_update_expression(item, update_expr, eav, ean)
+ elif attribute_updates:
+ item = _apply_attribute_updates(item, attribute_updates)
table["items"][pk_val][sk_val] = item
_update_counts(table)
@@ -2697,6 +2703,57 @@ def _evaluate_expected(item, expected, conditional_operator="AND"):
return all(results)
+def _apply_attribute_updates(item, attribute_updates):
+ """Apply legacy ``AttributeUpdates`` to an item.
+
+ Each key is an attribute name. The value has ``Action`` (``PUT``,
+ ``DELETE``, or ``ADD``; default ``PUT``) and optionally ``Value``
+ (a DynamoDB-typed attribute value).
+ """
+ item = copy.deepcopy(item)
+ for attr_name, update in attribute_updates.items():
+ action = update.get("Action", "PUT")
+ value = update.get("Value")
+
+ if action == "PUT":
+ if value is not None:
+ item[attr_name] = value
+ elif action == "DELETE":
+ if value is None:
+ # No value → remove the attribute entirely
+ item.pop(attr_name, None)
+ else:
+ # Value provided → subtract from a set
+ existing = item.get(attr_name)
+ if existing:
+ for set_type in ("SS", "NS", "BS"):
+ if set_type in value and set_type in existing:
+ remaining = [v for v in existing[set_type] if v not in set(value[set_type])]
+ if remaining:
+ item[attr_name] = {set_type: remaining}
+ else:
+ item.pop(attr_name, None)
+ break
+ elif action == "ADD":
+ if value is None:
+ continue
+ existing = item.get(attr_name)
+ if "N" in value:
+ inc = Decimal(value["N"])
+ cur = Decimal(existing["N"]) if existing and "N" in existing else Decimal(0)
+ item[attr_name] = {"N": str(cur + inc)}
+ elif "SS" in value:
+ cur = set(existing["SS"]) if existing and "SS" in existing else set()
+ item[attr_name] = {"SS": sorted(cur | set(value["SS"]))}
+ elif "NS" in value:
+ cur = set(existing["NS"]) if existing and "NS" in existing else set()
+ item[attr_name] = {"NS": sorted(cur | set(value["NS"]))}
+ elif "BS" in value:
+ cur = set(existing["BS"]) if existing and "BS" in existing else set()
+ item[attr_name] = {"BS": sorted(cur | set(value["BS"]))}
+ return item
+
+
def _extract_pk_from_key_conditions(key_conditions, pk_name):
"""Extract the partition key value from a legacy ``KeyConditions`` map.
diff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.py
index 25c575b4..f962ae2e 100644
--- a/tests/test_dynamodb.py
+++ b/tests/test_dynamodb.py
@@ -2343,3 +2343,153 @@ def test_dynamodb_query_key_conditions_with_query_filter(ddb):
assert item["status"]["S"] == "active"
+# ---------------------------------------------------------------------------
+# Legacy AttributeUpdates (UpdateItem)
+# ---------------------------------------------------------------------------
+
+def test_dynamodb_attribute_updates_put(ddb):
+ """PUT action sets attributes on a new and existing item."""
+ table = f"t_attr_upd_put_{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+
+ # Create item via AttributeUpdates (upsert)
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={
+ "name": {"Action": "PUT", "Value": {"S": "alice"}},
+ "age": {"Action": "PUT", "Value": {"N": "30"}},
+ },
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert item["name"] == {"S": "alice"}
+ assert item["age"] == {"N": "30"}
+
+ # Update existing item
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={
+ "name": {"Action": "PUT", "Value": {"S": "bob"}},
+ },
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert item["name"] == {"S": "bob"}
+ assert item["age"] == {"N": "30"} # unchanged
+
+
+def test_dynamodb_attribute_updates_delete(ddb):
+ """DELETE action removes an attribute or subtracts from a set."""
+ table = f"t_attr_upd_del_{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=table, Item={
+ "pk": {"S": "k1"},
+ "color": {"S": "red"},
+ "tags": {"SS": ["a", "b", "c"]},
+ })
+
+ # DELETE without Value → remove attribute
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={"color": {"Action": "DELETE"}},
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert "color" not in item
+
+ # DELETE with Value → subtract from set
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={"tags": {"Action": "DELETE", "Value": {"SS": ["b"]}}},
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert sorted(item["tags"]["SS"]) == ["a", "c"]
+
+
+def test_dynamodb_attribute_updates_add(ddb):
+ """ADD action increments a number or adds to a set."""
+ table = f"t_attr_upd_add_{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.put_item(TableName=table, Item={
+ "pk": {"S": "k1"},
+ "counter": {"N": "10"},
+ "tags": {"SS": ["a"]},
+ })
+
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={
+ "counter": {"Action": "ADD", "Value": {"N": "5"}},
+ "tags": {"Action": "ADD", "Value": {"SS": ["b", "c"]}},
+ },
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert item["counter"] == {"N": "15"}
+ assert sorted(item["tags"]["SS"]) == ["a", "b", "c"]
+
+ # ADD on non-existent numeric attribute → starts from 0
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={"new_num": {"Action": "ADD", "Value": {"N": "7"}}},
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert item["new_num"] == {"N": "7"}
+
+
+def test_dynamodb_attribute_updates_mutually_exclusive_with_update_expression(ddb):
+ """AttributeUpdates and UpdateExpression cannot be used together."""
+ table = f"t_attr_upd_excl_{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ with pytest.raises(ClientError) as exc_info:
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ UpdateExpression="SET #n = :v",
+ ExpressionAttributeNames={"#n": "name"},
+ ExpressionAttributeValues={":v": {"S": "x"}},
+ AttributeUpdates={"name": {"Action": "PUT", "Value": {"S": "y"}}},
+ )
+ assert exc_info.value.response["Error"]["Code"] == "ValidationException"
+
+
+def test_dynamodb_attribute_updates_default_action_is_put(ddb):
+ """When Action is omitted it defaults to PUT."""
+ table = f"t_attr_upd_dflt_{_uuid_mod.uuid4().hex[:8]}"
+ ddb.create_table(
+ TableName=table,
+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
+ BillingMode="PAY_PER_REQUEST",
+ )
+ ddb.update_item(
+ TableName=table,
+ Key={"pk": {"S": "k1"}},
+ AttributeUpdates={"name": {"Value": {"S": "alice"}}},
+ )
+ item = ddb.get_item(TableName=table, Key={"pk": {"S": "k1"}})["Item"]
+ assert item["name"] == {"S": "alice"}
+
+