Dynamojo 1.7.2__tar.gz → 2.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: Dynamojo
3
- Version: 1.7.2
3
+ Version: 2.0.0
4
4
  Summary: ORM For Dynamodb
5
5
  Author: Mathew Moon
6
6
  Author-email: me@mathewmoon.net
@@ -17,6 +17,26 @@ Description-Content-Type: text/markdown
17
17
  # Dynamojo
18
18
 
19
19
  ---
20
+ ### :exclamation: Important Notice :exclamation:
21
+ Version 2.0.0 is an important update that introduces breaking changes:
22
+ * `update()` and `update_by_key()` now default to `fail_on_missing=True`, so an
23
+ update against a key that names no item raises
24
+ `ConditionalCheckFailedException` instead of creating one.
25
+ * DynamoDB's `UpdateItem` upserts. Absent a condition that a missing item
26
+ cannot satisfy, it succeeds and creates an item holding only the key and
27
+ the `SET` targets. That fragment then fails model validation on the next
28
+ read, far from the write that caused it.
29
+ * A caller-supplied `ConditionExpression` is not protection on its own — one
30
+ built from `attribute_not_exists` arms is *satisfied* by a missing item, so
31
+ a guard written to prevent a lost update instead authorises a create.
32
+ * This makes the write pair coherent: `save()` creates (via
33
+ `fail_on_exists=True`), `update()` updates. Neither is an upsert.
34
+ * **If you rely on upsert semantics, pass `fail_on_missing=False`.**
35
+ * `fail_on_exists` on `save()` now composes its guard as a `ConditionBase`
36
+ rather than inlining the key names as raw text. Behaviour is unchanged for
37
+ ordinary keys; the rendered `ConditionExpression` string differs, and a table
38
+ keyed by a DynamoDB reserved word now works where it previously failed.
39
+
20
40
  ### :exclamation: Important Notice :exclamation:
21
41
  Version 1.0.0 is an important update that introduces breaking changes:
22
42
  * Pydantic dependency is now at 2.x
@@ -1,6 +1,26 @@
1
1
  # Dynamojo
2
2
 
3
3
  ---
4
+ ### :exclamation: Important Notice :exclamation:
5
+ Version 2.0.0 is an important update that introduces breaking changes:
6
+ * `update()` and `update_by_key()` now default to `fail_on_missing=True`, so an
7
+ update against a key that names no item raises
8
+ `ConditionalCheckFailedException` instead of creating one.
9
+ * DynamoDB's `UpdateItem` upserts. Absent a condition that a missing item
10
+ cannot satisfy, it succeeds and creates an item holding only the key and
11
+ the `SET` targets. That fragment then fails model validation on the next
12
+ read, far from the write that caused it.
13
+ * A caller-supplied `ConditionExpression` is not protection on its own — one
14
+ built from `attribute_not_exists` arms is *satisfied* by a missing item, so
15
+ a guard written to prevent a lost update instead authorises a create.
16
+ * This makes the write pair coherent: `save()` creates (via
17
+ `fail_on_exists=True`), `update()` updates. Neither is an upsert.
18
+ * **If you rely on upsert semantics, pass `fail_on_missing=False`.**
19
+ * `fail_on_exists` on `save()` now composes its guard as a `ConditionBase`
20
+ rather than inlining the key names as raw text. Behaviour is unchanged for
21
+ ordinary keys; the rendered `ConditionExpression` string differs, and a table
22
+ keyed by a DynamoDB reserved word now works where it previously failed.
23
+
4
24
  ### :exclamation: Important Notice :exclamation:
5
25
  Version 1.0.0 is an important update that introduces breaking changes:
6
26
  * Pydantic dependency is now at 2.x
@@ -9,6 +9,7 @@ from logging import getLogger
9
9
  from typing import Any
10
10
 
11
11
  from boto3.dynamodb.conditions import (
12
+ Attr,
12
13
  AttributeBase,
13
14
  ConditionBase,
14
15
  ConditionExpressionBuilder,
@@ -618,27 +619,27 @@ class DynamojoBase(BaseModel, ABC):
618
619
 
619
620
  opts = {"TableName": self._config().table, "Item": item, **kwargs}
620
621
 
622
+ # Composed as a ConditionBase and ANDed with the caller's expression
623
+ # before rendering, so the guard shares one placeholder namespace with
624
+ # it and passes through the same alias resolver. Building the guard as
625
+ # raw text would inline the key names unplaceholdered, which DynamoDB
626
+ # rejects outright when a key is named after a reserved word.
627
+ if fail_on_exists:
628
+ guard = Attr(table_pk).not_exists()
629
+ if table_sk is not None:
630
+ guard = guard & Attr(table_sk).not_exists()
631
+ ConditionExpression = (
632
+ guard & ConditionExpression
633
+ if ConditionExpression is not None
634
+ else guard
635
+ )
636
+
621
637
  if ConditionExpression:
622
638
  exp = self._get_raw_condition_expression(
623
639
  ConditionExpression, expression_type="ConditionExpression"
624
640
  )
625
641
  opts.update(exp)
626
642
 
627
- if fail_on_exists:
628
- sk_expression = f"attribute_not_exists({table_sk})"
629
- pk_expression = f"attribute_not_exists({table_pk})"
630
- fail_expression = (
631
- f"({pk_expression} AND {sk_expression}) "
632
- if table_sk is not None
633
- else pk_expression
634
- )
635
- if ConditionExpression:
636
- opts["ConditionExpression"] = (
637
- f"{fail_expression} AND {opts['ConditionExpression']}"
638
- )
639
- else:
640
- opts["ConditionExpression"] = fail_expression
641
-
642
643
  # DynamoDB's PutItem rejects empty ``ExpressionAttributeNames``
643
644
  # / ``ExpressionAttributeValues`` maps with ``ValidationException:
644
645
  # ExpressionAttributeValues must not be empty``. The merge above
@@ -855,6 +856,7 @@ class DynamojoBase(BaseModel, ABC):
855
856
  dict_set: dict[str, Any] | None = None,
856
857
  dict_remove: list[str] | None = None,
857
858
  set_if_not_exists: dict[str, Any] | None = None,
859
+ fail_on_missing: bool = True,
858
860
  **opts,
859
861
  ):
860
862
  # NOTE: `set` shadows the built-in inside this function — use the
@@ -945,6 +947,36 @@ class DynamojoBase(BaseModel, ABC):
945
947
  if serialized_values:
946
948
  opts["ExpressionAttributeValues"] = serialized_values
947
949
 
950
+ # UpdateItem upserts by default: absent a condition that a missing item
951
+ # cannot satisfy, DynamoDB creates a new item carrying only the key and
952
+ # the SET targets. That silently produces a partial row which fails
953
+ # model validation on the next read. A caller-supplied condition is no
954
+ # protection either — one built entirely from ``attribute_not_exists``
955
+ # arms is *satisfied* by a missing item, so the guard intended to
956
+ # prevent a lost update instead authorises a create.
957
+ #
958
+ # This is the counterpart to ``fail_on_exists`` on
959
+ # ``make_put_item_opts``: the two together mean a write states whether
960
+ # it expects the item to exist, rather than leaving it to whatever the
961
+ # caller's condition happens to imply.
962
+ #
963
+ # The guard is composed as a ``ConditionBase`` and ANDed with the
964
+ # caller's expression BEFORE rendering, so the whole thing goes through
965
+ # ``_get_raw_condition_expression`` once. Rendering the two separately
966
+ # would restart boto3's placeholder counter at ``#n0`` for each, and
967
+ # merging those name maps would silently clobber the caller's
968
+ # placeholders. Composing first also lets boto3 placeholder the key
969
+ # names, which a hand-built ``attribute_exists(PK)`` does not — that
970
+ # form breaks outright on a table keyed by a reserved word.
971
+ if fail_on_missing:
972
+ guard = Attr(pk_name).exists()
973
+ if sk_name is not None:
974
+ guard = guard & Attr(sk_name).exists()
975
+ supplied = opts.get("ConditionExpression")
976
+ opts["ConditionExpression"] = (
977
+ guard & supplied if supplied is not None else guard
978
+ )
979
+
948
980
  if condition_expression := opts.get("ConditionExpression"):
949
981
  exp = self._get_raw_condition_expression(
950
982
  exp=condition_expression,
@@ -977,6 +1009,7 @@ class DynamojoBase(BaseModel, ABC):
977
1009
  dict_remove: list[str] | None = None,
978
1010
  set_if_not_exists: dict[str, Any] | None = None,
979
1011
  ConditionExpression: ConditionBase | None = None,
1012
+ fail_on_missing: bool = True,
980
1013
  **opts,
981
1014
  ) -> dict:
982
1015
  """Issue a true DynamoDB UpdateItem identified by primary key.
@@ -985,6 +1018,13 @@ class DynamojoBase(BaseModel, ABC):
985
1018
  and conditionally-guarded mutations where only the key is in hand.
986
1019
  At least one update-producing kwarg must be supplied (`set` or any of
987
1020
  the atomic ops); a ConditionExpression alone is not a valid UpdateItem.
1021
+
1022
+ Args:
1023
+ fail_on_missing: When True (the default) the write is conditioned on
1024
+ the item already existing, so a key that names no row raises
1025
+ ``ConditionalCheckFailedException`` instead of creating a
1026
+ key-plus-SET-targets fragment. Matches ``update()``. Pass False
1027
+ where upsert semantics are actually wanted.
988
1028
  """
989
1029
  if not any(
990
1030
  [
@@ -1042,6 +1082,21 @@ class DynamojoBase(BaseModel, ABC):
1042
1082
  k: TYPE_SERIALIZER.serialize(v) for k, v in attribute_values.items()
1043
1083
  }
1044
1084
 
1085
+ # Same upsert hazard as ``update()`` — see the note on
1086
+ # ``make_update_opts``. Composed before rendering so the guard and the
1087
+ # caller's condition share one placeholder namespace and both pass
1088
+ # through the alias resolver.
1089
+ if fail_on_missing:
1090
+ table_index = cls._config().indexes.table
1091
+ guard = Attr(table_index.partitionkey).exists()
1092
+ if table_index.sortkey is not None:
1093
+ guard = guard & Attr(table_index.sortkey).exists()
1094
+ ConditionExpression = (
1095
+ guard & ConditionExpression
1096
+ if ConditionExpression is not None
1097
+ else guard
1098
+ )
1099
+
1045
1100
  if ConditionExpression is not None:
1046
1101
  exp = cls._get_raw_condition_expression(
1047
1102
  exp=ConditionExpression,
@@ -1094,8 +1149,18 @@ class DynamojoBase(BaseModel, ABC):
1094
1149
  dict_set: dict[str, Any] | None = None,
1095
1150
  dict_remove: list[str] | None = None,
1096
1151
  set_if_not_exists: dict[str, Any] | None = None,
1152
+ fail_on_missing: bool = True,
1097
1153
  **opts,
1098
1154
  ):
1155
+ """Write changed attributes back to the table with an UpdateItem.
1156
+
1157
+ Args:
1158
+ fail_on_missing: When True (the default) the update is conditioned
1159
+ on the item already existing, so a row deleted between load and
1160
+ write raises ``ConditionalCheckFailedException`` instead of
1161
+ being silently recreated as a key-plus-SET-targets fragment.
1162
+ Pass False only when upsert semantics are actually wanted.
1163
+ """
1099
1164
  has_atomic = any(
1100
1165
  [
1101
1166
  set,
@@ -1132,6 +1197,7 @@ class DynamojoBase(BaseModel, ABC):
1132
1197
  dict_set=dict_set,
1133
1198
  dict_remove=dict_remove,
1134
1199
  set_if_not_exists=set_if_not_exists,
1200
+ fail_on_missing=fail_on_missing,
1135
1201
  **opts,
1136
1202
  )
1137
1203
  self._config().dynamo_client.update_item(**opts)
@@ -20,7 +20,7 @@ class DynamojoConfig(BaseModel):
20
20
  # attributes.
21
21
  convert_dynamodb_types: bool = Field(default=True)
22
22
  joined_attributes: List[JoinedAttribute]
23
- __joined_attributes__: Dict = {}
23
+ __joined_attributes__: Dict
24
24
 
25
25
  # A list of database `Index` objects from `dynamojo.indexes.get_indexes()``
26
26
  indexes: IndexList
@@ -59,11 +59,14 @@ class DynamojoConfig(BaseModel):
59
59
  def __init__(self, **kwargs):
60
60
  super().__init__(**kwargs)
61
61
 
62
- for attr in self.joined_attributes:
63
- self.__joined_attributes__[attr.attribute] = attr
64
-
62
+ self.__joined_attributes__ = {
63
+ attr.attribute: attr for attr in self.joined_attributes
64
+ }
65
65
  for index_map in self.index_maps:
66
- if sk_att := index_map.sortkey:
66
+ # ``IndexMap`` only assigns ``sortkey`` / ``partitionkey`` when one
67
+ # was supplied, so a partition-key-only table leaves the attribute
68
+ # absent rather than None. Both reads have to tolerate that.
69
+ if sk_att := getattr(index_map, "sortkey", None):
67
70
  self._index_aliases[index_map.index.sortkey] = sk_att
68
71
  if getattr(index_map, "partitionkey", None):
69
72
  self._index_aliases[index_map.index.partitionkey] = (
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "Dynamojo"
3
- version = "1.7.2"
3
+ version = "2.0.0"
4
4
  description = "ORM For Dynamodb"
5
5
  authors = ["Mathew Moon <me@mathewmoon.net>"]
6
6
  homepage = "https://github.com/mathewmoon/dynamojo"
File without changes
File without changes
File without changes