This commit is contained in:
2025-07-01 16:38:22 -03:00
parent 978b968226
commit d50d828029
6 changed files with 42 additions and 12 deletions

View File

@@ -228,6 +228,7 @@ class KeyPair(Key):
*,
rename_key: str | None = None,
retain_key: bool = False,
table_name: str | None = None,
) -> None:
"""
Initializes a composite key using partition and sort key.
@@ -242,11 +243,13 @@ class KeyPair(Key):
If provided, renames the sort key in the output.
retain_key : bool, optional
Use the key itself as value if True; otherwise, use the extracted value.
table_name : str, optional
"""
super().__init__(**{PK: pk, SK: sk})
self._rename_key = rename_key
self._retain_key = retain_key
self._table_name = table_name
@property
def rename_key(self) -> str | None:
@@ -256,6 +259,10 @@ class KeyPair(Key):
def retain_key(self) -> bool:
return self._retain_key
@property
def table_name(self) -> str | None:
return self._table_name
def __repr__(self) -> str:
pk, sk, *_ = self.values()
return f'KeyPair({pk!r}, {sk!r})'
@@ -297,7 +304,12 @@ class KeyChain:
if not isinstance(other, KeyPair):
raise TypeError('Can only add a KeyPair to a KeyChain')
return KeyChain(pairs=self.pairs + (other,))
if other not in self.pairs:
pairs = self.pairs + (other,)
else:
pairs = self.pairs
return KeyChain(pairs=pairs)
@dataclass(frozen=True)
@@ -311,6 +323,7 @@ class TransactKey:
"""
pk: str
table_name: str | None = None
pairs: tuple[KeyPair, ...] = ()
def __add__(self, other: SortKey | KeyPair) -> 'TransactKey':
@@ -318,9 +331,18 @@ class TransactKey:
raise TypeError('Can only add a SortKey and KeyPair to a TransactKey')
if isinstance(other, SortKey):
other = KeyPair(self.pk, other)
other = KeyPair(self.pk, other, table_name=self.table_name)
return TransactKey(pk=self.pk, pairs=self.pairs + (other,))
if other not in self.pairs:
pairs = self.pairs + (other,)
else:
pairs = self.pairs
return TransactKey(
pk=self.pk,
table_name=self.table_name,
pairs=pairs,
)
class TransactionCanceledReason(TypedDict):
@@ -884,6 +906,7 @@ class DynamoDBCollection:
key: Key,
*,
ttl: int | datetime | None = None,
cond_expr: str | None = None,
**kwargs: Any,
) -> bool:
"""Creates a new item, or replaces an old item with a new item.
@@ -895,6 +918,8 @@ class DynamoDBCollection:
ttl: int or datetime, optional
Time-to-live for the item, specified as a timestamp integer
or datetime object.
cond_expr: str, optional
Conditional expression for deletion.
**kwargs
Additional data to be stored with the item.
@@ -909,7 +934,10 @@ class DynamoDBCollection:
if isinstance(ttl, datetime):
kwargs.update({'ttl': timestamp(ttl)})
return self.persistence_layer.put_item(item=key | kwargs)
return self.persistence_layer.put_item(
item=key | kwargs,
cond_expr=cond_expr,
)
def delete_item(
self,
@@ -1013,7 +1041,7 @@ class DynamoDBCollection:
transact_items = [
{
'Get': {
'TableName': getattr(pair, 'table_name', table_name),
'TableName': pair.table_name or table_name,
'Key': serialize(pair),
}
}