Skip to content

Commit

Permalink
refactor: RelationalBone.refresh() (#1392)
Browse files Browse the repository at this point in the history
... and some more on `updateRelations`. This finally kicks this piece
of junk to hell and replaces it by something working, beautiful and
clear.

---------

Co-authored-by: Sven Eberth <[email protected]>
  • Loading branch information
phorward and sveneberth authored Jan 29, 2025
1 parent 4726d59 commit 47d6314
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 36 deletions.
50 changes: 17 additions & 33 deletions src/viur/core/bones/relational.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,7 +1013,7 @@ def orderHook(self, name: str, query: db.Query, orderings): # FIXME
res.append(f"src.{orderKey}")
return res

def refresh(self, skel: "SkeletonInstance", boneName: str):
def refresh(self, skel: "SkeletonInstance", name: str) -> None:
"""
Refreshes all values that might be cached from other entities in the provided skeleton.
Expand All @@ -1024,40 +1024,24 @@ def refresh(self, skel: "SkeletonInstance", boneName: str):
:param SkeletonInstance skel: The skeleton containing the bone to be refreshed.
:param str boneName: The name of the bone to be refreshed.
"""

def updateInplace(relDict):
"""
Fetches the entity referenced by valDict["dest.key"] and updates all dest.* keys
accordingly
"""
if not (isinstance(relDict, dict) and "dest" in relDict):
logging.error(f"Invalid dictionary in updateInplace: {relDict}")
return
newValues = db.Get(db.keyHelper(relDict["dest"]["key"], self.kind))
if newValues is None:
logging.info(f"""The key {relDict["dest"]["key"]} does not exist""")
return
for boneName in self._ref_keys:
if boneName != "key" and boneName in newValues:
relDict["dest"].dbEntity[boneName] = newValues[boneName]

if not skel[boneName] or self.updateLevel == RelationalUpdateLevel.OnValueAssignment:
if not skel[name] or self.updateLevel == RelationalUpdateLevel.OnValueAssignment:
return

# logging.debug("Refreshing RelationalBone %s of %s" % (boneName, skel.kindName))
if isinstance(skel[boneName], dict) and "dest" not in skel[boneName]: # multi lang
for l in skel[boneName]:
if isinstance(skel[boneName][l], dict):
updateInplace(skel[boneName][l])
elif isinstance(skel[boneName][l], list):
for k in skel[boneName][l]:
updateInplace(k)
else:
if isinstance(skel[boneName], dict):
updateInplace(skel[boneName])
elif isinstance(skel[boneName], list):
for k in skel[boneName]:
updateInplace(k)
for idx, lang, value in self.iter_bone_value(skel, name):
if value is None:
continue

if value["dest"]:
try:
target_skel = value["dest"].read()
except ValueError:
logging.error(
f"{name}: The key {value['dest']['key']!r} ({value['dest'].get('name')!r}) seems to be gone"
)
continue

for key in self.refKeys:
value["dest"][key] = target_skel[key]

def getSearchTags(self, skel: "SkeletonInstance", name: str) -> set[str]:
"""
Expand Down
8 changes: 5 additions & 3 deletions src/viur/core/skeleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ def refresh(cls, skel: SkeletonInstance):
This function causes a refresh of all relational bones and their associated
information.
"""
logging.debug(f"""Refreshing {skel["key"]=}""")
logging.debug(f"""Refreshing {skel["key"]!r} ({skel.get("name")!r})""")

for key, bone in skel.items():
if not isinstance(bone, BaseBone):
Expand Down Expand Up @@ -1746,7 +1746,9 @@ def unserialize(self, values: db.Entity | dict):
"""
if not isinstance(values, db.Entity):
self.dbEntity = db.Entity()
self.dbEntity.update(values)

if values:
self.dbEntity.update(values)
else:
self.dbEntity = values

Expand Down Expand Up @@ -1914,7 +1916,7 @@ def updateRelations(destKey: db.Key, minChangeTime: int, changedBone: t.Optional
:param cursor: The database cursor for the current request as we only process five entities at once and then
defer again.
"""
logging.debug(f"Starting updateRelations for {destKey} ; {minChangeTime=},{changedBone=}, {cursor=}")
logging.debug(f"Starting updateRelations for {destKey=}; {minChangeTime=}, {changedBone=}, {cursor=}")
updateListQuery = (
db.Query("viur-relations")
.filter("dest.__key__ =", destKey)
Expand Down

0 comments on commit 47d6314

Please sign in to comment.