43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
|
|
from sqlalchemy import String, ForeignKey, event
|
||
|
|
from sqlalchemy.orm import Mapped, mapped_column, declared_attr, relationship, Session
|
||
|
|
|
||
|
|
from .base import Base
|
||
|
|
|
||
|
|
__all__ = ["Status"]
|
||
|
|
|
||
|
|
|
||
|
|
class Status(Base):
|
||
|
|
"""Status of a record. Can be used in any table by using MixIn :class:`StatusForeignKey`."""
|
||
|
|
|
||
|
|
id: Mapped[str] = mapped_column(String(3), primary_key=True)
|
||
|
|
name: Mapped[str] = mapped_column(String(30), unique=True)
|
||
|
|
|
||
|
|
|
||
|
|
class StatusForeignKey:
|
||
|
|
"""Foreign Key Mixin for :py:class:`.Status`
|
||
|
|
|
||
|
|
By adding this mixin every record will get a status assigned.
|
||
|
|
"""
|
||
|
|
|
||
|
|
status_id: Mapped[str] = mapped_column(ForeignKey("status.id"), default="N", sort_order=1000000)
|
||
|
|
|
||
|
|
# noinspection PyMethodParameters
|
||
|
|
@declared_attr
|
||
|
|
def status(cls) -> Mapped[Status]:
|
||
|
|
return relationship()
|
||
|
|
|
||
|
|
|
||
|
|
# noinspection PyUnusedLocal
|
||
|
|
@event.listens_for(Status.__table__, "after_create")
|
||
|
|
def initialize_status(target, connection, **kwargs):
|
||
|
|
with Session(connection) as session:
|
||
|
|
for kwargs in (
|
||
|
|
dict(id="A", name="Active"),
|
||
|
|
dict(id="I", name="Inactive"),
|
||
|
|
dict(id="N", name="New"),
|
||
|
|
dict(id="PRE", name="Prepared"),
|
||
|
|
dict(id="X", name="eXcluded"),
|
||
|
|
):
|
||
|
|
session.add(Status(**kwargs))
|
||
|
|
session.commit()
|