"""The contributors of one reference (文献责任者). A citation prints its authors in a fixed order, with a mark for anyone who is not the author — 「张三, 编」, "Ed. by Smith" — so the list is a child table rather than a column, and each row knows its position and its role. Why a name is three fields -------------------------- Citation styles rewrite names, and they disagree: =========== ================ ================== style 「张三」 "John Smith" =========== ================ ================== GB/T 7714 张三 Smith J APA Zhang, S. Smith, J. IEEE S. Zhang J. Smith =========== ================ ================== So the printed form and the two halves are kept apart: ``name`` is what the writer typed and what prints when a style does not need to rearrange anything, while ``family_name`` / ``given_name`` are what a style needs to invert or initialise a name. Both are optional enrichment — a row with only ``name`` is complete — and that is deliberate rather than duplication: ``name`` is the authority for display, the halves are the authority for reformatting, and a style uses whichever it needs. Institutional authors ("世界卫生组织") have no halves at all, which is why they are not required. """ from typing import TYPE_CHECKING from sqlalchemy import ForeignKey, Index, Integer, String, text from sqlalchemy.orm import Mapped, mapped_column, relationship from app.db.base import Base if TYPE_CHECKING: # pragma: no cover - typing only from app.models.reference import Reference class ReferenceAuthor(Base): """One contributor of one reference, at one position, with one role.""" __tablename__ = "reference_author" __table_args__ = ( # Reads are always "the contributors of this reference, in order". Index("ix_reference_author_reference_sort", "reference_id", "sort"), ) id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) reference_id: Mapped[int] = mapped_column( ForeignKey("reference.id", ondelete="CASCADE"), nullable=False, ) #: Print order, ascending. Ties are broken by ``id``, as everywhere else. sort: Mapped[int] = mapped_column(Integer, nullable=False, default=0) #: What prints: 「张三」, "John Smith", "世界卫生组织". name: Mapped[str] = mapped_column(String(255), nullable=False) #: Optional halves, for styles that invert or initialise a name. family_name: Mapped[str | None] = mapped_column(String(128), nullable=True) given_name: Mapped[str | None] = mapped_column(String(128), nullable=True) #: One of :data:`app.models.reference.REFERENCE_AUTHOR_ROLES`. The default #: is the one that needs no mark in the citation. role: Mapped[str] = mapped_column( String(16), nullable=False, default="author", server_default=text("'author'"), ) reference: Mapped["Reference"] = relationship(back_populates="authors") def __repr__(self) -> str: # pragma: no cover - debugging aid return ( f"" )