Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exposing control over return_values in Model.update() #1050

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
30 changes: 21 additions & 9 deletions pynamodb/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
ATTR_DEFINITIONS, ATTR_NAME, ATTR_TYPE, KEY_SCHEMA,
KEY_TYPE, ITEM, READ_CAPACITY_UNITS, WRITE_CAPACITY_UNITS,
RANGE_KEY, ATTRIBUTES, PUT, DELETE, RESPONSES,
INDEX_NAME, PROVISIONED_THROUGHPUT, PROJECTION, ALL_NEW,
INDEX_NAME, PROVISIONED_THROUGHPUT, PROJECTION, ALL_NEW, NONE,
GLOBAL_SECONDARY_INDEXES, LOCAL_SECONDARY_INDEXES, KEYS,
PROJECTION_TYPE, NON_KEY_ATTRIBUTES,
TABLE_STATUS, ACTIVE, RETURN_VALUES, BATCH_GET_PAGE_LIMIT,
Expand Down Expand Up @@ -417,31 +417,43 @@ def delete(self, condition: Optional[Condition] = None, settings: OperationSetti

return self._get_connection().delete_item(hk_value, range_key=rk_value, condition=condition, settings=settings)

def update(self, actions: List[Action], condition: Optional[Condition] = None, settings: OperationSettings = OperationSettings.default) -> Any:
def update(
self,
actions: List[Action],
condition: Optional[Condition] = None,
settings: OperationSettings = OperationSettings.default,
read_back: str = ALL_NEW,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should make it an enum. This library isn't awfully modern, but maybe there's an opportunity to change that (especially as we're establishing a new API here).

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say an enum is a better choice, too. Let's start to use strong typing whenever possible.

) -> Any:
"""
Updates an item using the UpdateItem operation.

:param actions: a list of Action updates to apply
:param condition: an optional Condition on which to update
:param settings: per-operation settings
:param read_back: what to read back from the DB after the update
ALL_NEW: read back entire object after the update (default)
NONE: read back nothing, local version is not updated
:raises ModelInstance.DoesNotExist: if the object to be updated does not exist
:raises pynamodb.exceptions.UpdateError: if the `condition` is not met
"""
if not isinstance(actions, list) or len(actions) == 0:
raise TypeError("the value of `actions` is expected to be a non-empty list")
if read_back not in (ALL_NEW, NONE):
raise ValueError("expected `read_back` to be `ALL_NEW` or `NONE`, but was: {}".format(read_back))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
raise ValueError("expected `read_back` to be `ALL_NEW` or `NONE`, but was: {}".format(read_back))
raise ValueError(f"expected `read_back` to be `ALL_NEW` or `NONE`, but was: '{read_back}'")


hk_value, rk_value = self._get_hash_range_key_serialized_values()
version_condition = self._handle_version_attribute(actions=actions)
if version_condition is not None:
condition &= version_condition

data = self._get_connection().update_item(hk_value, range_key=rk_value, return_values=ALL_NEW, condition=condition, actions=actions, settings=settings)
item_data = data[ATTRIBUTES]
stored_cls = self._get_discriminator_class(item_data)
if stored_cls and stored_cls != type(self):
raise ValueError("Cannot update this item from the returned class: {}".format(stored_cls.__name__))
self.deserialize(item_data)
return data
data = self._get_connection().update_item(hk_value, range_key=rk_value, return_values=read_back, condition=condition, actions=actions, settings=settings)
if read_back == ALL_NEW:
item_data = data[ATTRIBUTES]
stored_cls = self._get_discriminator_class(item_data)
if stored_cls and stored_cls != type(self):
raise ValueError("Cannot update this item from the returned class: {}".format(stored_cls.__name__))
self.deserialize(item_data)
return data

def save(self, condition: Optional[Condition] = None, settings: OperationSettings = OperationSettings.default) -> Dict[str, Any]:
"""
Expand Down
24 changes: 23 additions & 1 deletion tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from pynamodb.constants import (
ITEM, STRING, ALL, KEYS_ONLY, INCLUDE, REQUEST_ITEMS, UNPROCESSED_KEYS, CAMEL_COUNT,
RESPONSES, KEYS, ITEMS, LAST_EVALUATED_KEY, EXCLUSIVE_START_KEY, ATTRIBUTES, BINARY,
UNPROCESSED_ITEMS, DEFAULT_ENCODING, MAP, LIST, NUMBER, SCANNED_COUNT,
UNPROCESSED_ITEMS, DEFAULT_ENCODING, MAP, LIST, NUMBER, SCANNED_COUNT, ALL_NEW, NONE
)
from pynamodb.models import Model
from pynamodb.indexes import (
Expand Down Expand Up @@ -921,6 +921,28 @@ def test_update(self, mock_time):
assert item.views is None
self.assertEqual({'bob'}, item.custom_aliases)

def test_update_readback(self):
self.init_table_meta(SimpleUserModel, SIMPLE_MODEL_TABLE_DATA)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.init_table_meta(SimpleUserModel, SIMPLE_MODEL_TABLE_DATA)

No longer needed 😅

item = SimpleUserModel(user_name='foo', is_active=True, email='[email protected]', signature='foo', views=100)

with patch(PATCH_METHOD) as req:
req.return_value = {}
item.update(
actions=[SimpleUserModel.email.set('[email protected]')],
read_back=NONE)
params = {
'TableName': 'SimpleModel',
'Key': {'user_name': {'S': 'foo'}},
'ReturnValues': 'NONE',
'UpdateExpression': 'SET #0 = :0',
'ExpressionAttributeNames': {'#0': 'email'},
'ExpressionAttributeValues': {':0': {'S': '[email protected]'}},
'ReturnConsumedCapacity': 'TOTAL'
}
args = req.call_args[0][1]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
args = req.call_args[0][1]
args = req.call_args[0].args

deep_eq(args, params, _assert=True)
assert item.email == '[email protected]'

def test_update_doesnt_do_validation_on_null_attributes(self):
self.init_table_meta(CarModel, CAR_MODEL_TABLE_DATA)
item = CarModel(12345)
Expand Down