Demo: simplify resolve_user to a plain previous-state lookup
This commit is contained in:
+5
-17
@@ -7,7 +7,7 @@ from pathlib import Path
|
|||||||
import msgspec
|
import msgspec
|
||||||
|
|
||||||
from kanta import Kanta
|
from kanta import Kanta
|
||||||
from kanta.callbacks import DictPost, DictPre
|
from kanta.callbacks import DictPre
|
||||||
from kanta.logging import configure_logging
|
from kanta.logging import configure_logging
|
||||||
|
|
||||||
|
|
||||||
@@ -47,18 +47,11 @@ kanta_v1 = Kanta(filename, Data(), migrations=sys.modules[__name__])
|
|||||||
|
|
||||||
|
|
||||||
@kanta_v1.logfmt
|
@kanta_v1.logfmt
|
||||||
def resolve_user(
|
def resolve_user(value: str, path: str, previous: DictPre) -> str | None:
|
||||||
value: str, path: str, previous: DictPre, current: DictPost
|
|
||||||
) -> str | None:
|
|
||||||
"""Resolve user ids to names from the database state itself."""
|
"""Resolve user ids to names from the database state itself."""
|
||||||
if path != "$user" and not path.startswith("users."):
|
if path != "$user" and not path.startswith("users."):
|
||||||
return None
|
return None
|
||||||
# Post-change state first, then pre-change (deleted users are only there).
|
return previous.get("users", {}).get(value, {}).get("name")
|
||||||
for state in (current, previous):
|
|
||||||
name = state.get("users", {}).get(value, {}).get("name")
|
|
||||||
if name:
|
|
||||||
return name
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
@@ -92,18 +85,13 @@ async def main() -> None:
|
|||||||
)
|
)
|
||||||
async with kanta_v1 as kanta:
|
async with kanta_v1 as kanta:
|
||||||
with kanta.transaction(
|
with kanta.transaction(
|
||||||
action="import", user="userid001", logdiff=False
|
action="update", user="userid002", extra=filename.name
|
||||||
) as data:
|
) as data:
|
||||||
data.total = 3
|
data.total += 1
|
||||||
|
|
||||||
with kanta.transaction(action="delete", user="userid002") as data:
|
with kanta.transaction(action="delete", user="userid002") as data:
|
||||||
del data.users["userid001"]
|
del data.users["userid001"]
|
||||||
|
|
||||||
with kanta.transaction(
|
|
||||||
action="update", user="userid002", extra=filename.name
|
|
||||||
) as data:
|
|
||||||
data.total = 4
|
|
||||||
|
|
||||||
|
|
||||||
# Fake clock for deterministic timestamps
|
# Fake clock for deterministic timestamps
|
||||||
_now = datetime(2027, 1, 1, tzinfo=UTC)
|
_now = datetime(2027, 1, 1, tzinfo=UTC)
|
||||||
|
|||||||
Reference in New Issue
Block a user