Coverage for polar/custom_field/attachment.py: 91%

18 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-12-05 17:15 +0000

1from typing import TYPE_CHECKING, Any 1ab

2from uuid import UUID 1ab

3 

4from sqlalchemy import Boolean, ForeignKey, Integer, Uuid, event 1ab

5from sqlalchemy.orm import ( 1ab

6 Mapped, 

7 Mapper, 

8 declared_attr, 

9 mapped_column, 

10 relationship, 

11) 

12 

13if TYPE_CHECKING: 13 ↛ 14line 13 didn't jump to line 14 because the condition on line 13 was never true1ab

14 from polar.models import CustomField 

15 

16 

17class AttachedCustomFieldMixin: 1ab

18 """Mixin for models that attach custom fields.""" 

19 

20 custom_field_id: Mapped[UUID] = mapped_column( 1ab

21 Uuid, 

22 ForeignKey("custom_fields.id", ondelete="cascade"), 

23 primary_key=True, 

24 ) 

25 order: Mapped[int] = mapped_column(Integer, index=True, nullable=False) 1ab

26 required: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False) 1ab

27 

28 @declared_attr 1ab

29 def custom_field(cls) -> Mapped["CustomField"]: 1ab

30 # This is an association table, so eager loading makes sense 

31 return relationship("CustomField", lazy="joined") 1ab

32 

33 

34attached_custom_fields_models: set[type[AttachedCustomFieldMixin]] = set() 1ab

35 

36 

37# Event listener to track models inheriting from AttachedCustomFieldMixin 

38@event.listens_for(Mapper, "mapper_configured") 1ab

39def track_attached_custom_field_mixin(_mapper: Mapper[Any], class_: type) -> None: 1ab

40 if issubclass(class_, AttachedCustomFieldMixin): 1c

41 attached_custom_fields_models.add(class_) 1c