Coverage for slidge/core/mixins/db.py: 94%

72 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-12-01 19:36 +0000

1import logging 

2import typing 

3from contextlib import AbstractContextManager as ContextManager 

4from contextlib import contextmanager, nullcontext 

5 

6import sqlalchemy as sa 

7import sqlalchemy.orm 

8 

9from ...db.models import Contact, Participant, Room, Space 

10from ...db.track import TrackedDict 

11from ...util.types import ExtraAttrMapping 

12from .base import SessionBound 

13 

14if typing.TYPE_CHECKING: 

15 from slidge.util.types import AnyGateway 

16 

17 

18class UpdateInfoMixin[ 

19 T: ExtraAttrMapping = typing.Any, 

20 PropsT = typing.Mapping[str, typing.Any], 

21](SessionBound): 

22 _stored: Contact | Room | Participant | Space 

23 xmpp: "AnyGateway" 

24 log: logging.Logger 

25 _batch_set_attributes_enabled = False 

26 _batch_depth = 0 

27 

28 def __init__(self, *args: object, **kwargs: object) -> None: 

29 super().__init__(*args, **kwargs) 

30 self._pending_updates: dict[str, object] = {} 

31 self._extra_attributes = typing.cast( 

32 T, 

33 TrackedDict( 

34 typing.cast(ExtraAttrMapping, self._stored.extra_attributes or {}), 

35 self._on_extra_attr_change, 

36 ), 

37 ) 

38 

39 @classmethod 

40 @contextmanager 

41 def _batch_set_attributes(cls) -> typing.Generator[None]: 

42 cls._batch_set_attributes_enabled = True 

43 cls._batch_depth += 1 

44 try: 

45 yield 

46 finally: 

47 cls._batch_depth -= 1 

48 if cls._batch_depth == 0: 

49 cls._batch_set_attributes_enabled = False 

50 

51 def batch_set_attributes( 

52 self, 

53 **kwargs: typing.Unpack[PropsT], # type:ignore[misc] 

54 ) -> ContextManager[None]: 

55 if not kwargs: 

56 return self.__batch_set_attributes_context() 

57 

58 with self.__batch_set_attributes_context(): 

59 for name, value in kwargs.items(): 

60 setattr(self, name, value) 

61 return nullcontext() 

62 

63 @contextmanager 

64 def __batch_set_attributes_context(self) -> typing.Generator[None]: 

65 self._batch_depth += 1 

66 self._batch_set_attributes_enabled = True 

67 try: 

68 yield 

69 finally: 

70 self._batch_depth -= 1 

71 if self._batch_depth == 0: 

72 self._batch_set_attributes_enabled = False 

73 if self._pending_updates: 

74 with self.xmpp.store.session() as orm: 

75 orm.execute( 

76 sa.update(self._stored.__class__) 

77 .where(self._stored.__class__.id == self._stored.id) 

78 .values(**self._pending_updates) 

79 ) 

80 orm.commit() 

81 self._pending_updates.clear() 

82 

83 def _update_stored_attribute(self, **kwargs: object) -> bool: 

84 kwargs = self._stored._normalize_stored_updates(kwargs) 

85 for key, value in list(kwargs.items()): 

86 try: 

87 change = getattr(self._stored, key) != value 

88 except sa.orm.exc.DetachedInstanceError: 

89 change = True 

90 if change: 

91 self._stored._set_committed_value(key, value) 

92 else: 

93 kwargs.pop(key) 

94 if self._batch_set_attributes_enabled: 

95 self._pending_updates.update(kwargs) 

96 return False 

97 if kwargs: 

98 with self.xmpp.store.session() as orm: 

99 orm.execute( 

100 sa.update(self._stored.__class__) 

101 .where(self._stored.__class__.id == self._stored.id) 

102 .values(**kwargs) 

103 ) 

104 orm.commit() 

105 return True 

106 else: 

107 return False 

108 

109 @property 

110 def extra_attributes(self) -> T: 

111 return self._extra_attributes 

112 

113 def _on_extra_attr_change(self, new_data: T) -> None: 

114 self._update_stored_attribute(extra_attributes=new_data)