This commit is contained in:
2025-04-11 21:28:02 -03:00
parent 5b5e381191
commit 1b2ebcfb99
6 changed files with 107 additions and 62 deletions

View File

@@ -12,6 +12,7 @@ from uuid import UUID
from aws_lambda_powertools import Logger
from boto3.dynamodb.types import TypeDeserializer, TypeSerializer
from botocore.exceptions import ClientError
from glom import glom
from .dateutils import now, timestamp
from .funcs import omit
@@ -58,21 +59,20 @@ if TYPE_CHECKING:
@dataclass
class ComposeKey(str):
"""Creates a composite key by joining string parts with a specified delimiter.
If a prefix is provided, it is added at the beginning of the key parts.
Example
-------
>>> ComposeKey(('abc', 'xyz'), prefix='examples', delimiter='#')
'examples#abc#xyz'
"""
keyparts: str | tuple[str, ...]
prefix: str | None = None
delimiter: str = '#'
else:
class ComposeKey(str):
"""Creates a composite key by joining string parts with a specified delimiter.
If a prefix is provided, it is added at the beginning of the key parts.
Example
-------
ComposeKey(('abc', 'xyz'), prefix='examples', delimiter='#')
"""
def __new__(
cls,
keyparts: str | tuple[str, ...],
@@ -131,17 +131,31 @@ if TYPE_CHECKING:
class SortKey(str):
sk: str
table_name: str | None = None
path_spec: str | None = None
else:
class SortKey(str):
def __new__(cls, sk: str, *, table_name: str | None = None) -> str:
def __new__(
cls,
sk: str,
*,
table_name: str | None = None,
path_spec: str | None = None,
) -> str:
return super().__new__(cls, sk)
def __init__(self, sk: str, *, table_name: str | None = None) -> None:
def __init__(
self,
sk: str,
*,
table_name: str | None = None,
path_spec: str | None = None,
) -> None:
# __init__ is used to store the parameters for later reference.
# For immutable types like str, __init__ cannot change the instance's value.
self.sk = sk
self.table_name = table_name
self.path_spec = path_spec
@dataclass
@@ -149,9 +163,9 @@ class TransactKey:
"""
Example
-------
>>> TransactKey('e9bb7dc6-c7b2-4d34-8931-d298353758ec')
... + SortKey('0')
... + SortKey('tenant')
TransactKey('e9bb7dc6-c7b2-4d34-8931-d298353758ec')
+ SortKey('0')
+ SortKey('tenant')
"""
pk: str
@@ -597,18 +611,18 @@ class DynamoDBCollection:
Parameters
----------
key : Key
key: Key
Key of the item to be retrieved.
path_spec : str, optional
A path specification for nested data extraction, default is None.
raise_on_error : bool, optional
If True, raises an exception when the item is not found, default is True.
exception_cls : Type[Exception], optional
Exception class to be used if the item is not found, default is MissingError.
default : Any, optional
Default value returned if the item is not found, default is None.
delimiter : str, optional
Delimiter used in key composition, default is '#'.
path_spec: str, optional
A path specification for nested data extraction.
raise_on_error: bool, optional
If True, raises an exception when the item is not found.
exception_cls: Type[Exception], optional
Exception class to be used if the item is not found.
default: Any, optional
Default value returned if the item is not found.
delimiter: str, optional
Delimiter used in key composition.
Returns
-------
@@ -644,10 +658,10 @@ class DynamoDBCollection:
Parameters
----------
key : Key
key: Key
Key for the item to be inserted or updated.
ttl : int or datetime, optional
Time-to-live for the item, specified as a timestamp integer or datetime object, default is None.
ttl: int or datetime, optional
Time-to-live for the item, specified as a timestamp integer or datetime object.
**kwargs
Additional data to be stored with the item.
@@ -688,14 +702,14 @@ class DynamoDBCollection:
Parameters
----------
key : Key
key: Key
Key of the item to be deleted.
cond_expr : str, optional
Conditional expression for deletion, default is None.
expr_attr_names : dict, optional
Mapping of attribute names for the expression, default is None.
expr_attr_values : dict, optional
Mapping of attribute values for the expression, default is None.
cond_expr: str, optional
Conditional expression for deletion.
expr_attr_names: dict, optional
Mapping of attribute names for the expression.
expr_attr_values: dict, optional
Mapping of attribute values for the expression.
Returns
-------
@@ -720,21 +734,23 @@ class DynamoDBCollection:
-------
**Get items using chained sort keys**
key = TransactKey('b3511b5a-cb32-4833-a373-f8223f2088d4') + SortKey('sk-1') + SortKey('sk-2')
key = (
TransactKey('b3511b5a-cb32-4833-a373-f8223f2088d4')
+ SortKey('sk-1') + SortKey('sk-2')
)
collect = DynamoDBCollection(...)
items = collect.get_items(key)
Parameters
----------
key : TransactKey
key: TransactKey
A TransactKey instance that contains a partition key and one or more sort keys.
If no sort key is provided, the transaction is skipped.
flatten_top : bool, optional
flatten_top: bool, optional
Determines whether the first nested item in the transaction result should be flattened,
i.e., extracted to serve as the primary item at the top level of the returned dict.
If True, the nested item is promoted to the top level.
The default is True.
Returns
-------
@@ -764,9 +780,11 @@ class DynamoDBCollection:
else:
head, tail = {}, items
return head | {
k: omit((PK, SK), item) for k, item in zip(sortkeys, tail) if item
}
def _getin(sk: SortKey, v: dict) -> dict:
v = omit((PK, SK), v)
return glom(v, sk.path_spec) if sk.path_spec else v
return head | {k: _getin(k, item) for k, item in zip(sortkeys, tail) if item}
def query(
self,
@@ -801,20 +819,20 @@ class DynamoDBCollection:
Parameters
----------
key : PartitionKey or KeyPair
key: PartitionKey or KeyPair
Partition key or Key pair used for the query.
expr_attr_name : dict, optional
Additional mapping for attribute names, default is {}.
expr_attr_values : dict, optional
Additional mapping for attribute values, default is {}.
start_key : str, optional
Starting key for pagination, default is None.
filter_expr : str, optional
Filter expression for the query, default is None.
index_forward : bool, optional
Order of the results; True for ascending order, default is False.
limit : int, optional
Maximum number of items to return, default is LIMIT.
expr_attr_name: dict, optional
Additional mapping for attribute names.
expr_attr_values: dict, optional
Additional mapping for attribute values.
start_key: str, optional
Starting key for pagination.
filter_expr: str, optional
Filter expression for the query.
index_forward: bool, optional
Order of the results; True for ascending order.
limit: int, optional
Maximum number of items to return.
Returns
-------
@@ -823,7 +841,7 @@ class DynamoDBCollection:
See Also
--------
DynamoDB.Client.query : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/query.html
DynamoDB.Client.query: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/query.html
"""
key_cond_expr = (
'#pk = :pk AND begins_with(#sk, :sk)'