Files
paper-doc/backend/app/models/template_field.py
T
govin a5f884f440 refactor: prefix every table with its module
Two tables were named after the concept they came from rather than the module
they belong to, so the schema read as if the template tables were part of the
paper module. Renamed (data preserved, `RENAME TABLE` moves rows in place):

    paper_template  -> template                 the 模板 module
    section_field   -> template_field_library   the 字段库 the 模板 module owns

The paper tables and `template_field` already followed the rule. The rename
carries through everything that named a module:

  models   Template, TemplateField, TemplateFieldLibrary
  schemas  Template*, TemplateFieldLibrary*
  crud     app/crud/template.py, app/crud/template_field_library.py
  API      /template-field-library (was /section-fields); handlers are now
           named after library entries, which removes the ambiguity with
           TemplateField — a placement, a different thing entirely
  client   src/api/templateFieldLibrary.ts

`paper_template_filed_sort` is deliberately untouched: it is a column of the
paper module, spelled as the feature was specified.

TiDB v8.5 with tidb_enable_foreign_key on — as this cluster runs — enforces
foreign keys rather than ignoring them, so the docs' "TiDB does not enforce
foreign keys" was wrong. Corrected, with what actually follows from it: the
rename was rehearsed (RENAME TABLE carries a referencing constraint along), the
API keeps checking first so a violation names the row instead of surfacing a
driver error, and the ORM cascades stay so behaviour does not depend on a
cluster setting.

Revision f27a1c6d9e04 verified both ways; 40 smoke checks, type-check and build
all pass.
2026-09-18 17:48:11 +08:00

74 lines
2.8 KiB
Python

"""The template <-> field join table (关联表), which owns the display order.
This table is the heart of the design. It carries exactly one piece of
information that belongs to neither side alone: ``sort`` — where this field
sits in *this* template.
Consequences worth stating explicitly, because they are the requirements:
* A field can appear in many templates, at a different position in each.
* A field can legitimately appear **more than once** in the same template
(e.g. a level-2 "Background" under both "1. Introduction" and
"2. Related Work"), so there is deliberately **no** unique constraint on
``(template_id, field_id)``. The UI warns about repeats; it does not forbid
them.
* The user picks fields in any order they like. Nothing about the selection
order is stored — readers order strictly by ``sort``, then by ``id`` as a
stable tie-breaker.
"""
from typing import TYPE_CHECKING
from sqlalchemy import ForeignKey, Index, Integer
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.template import Template
from app.models.template_field_library import TemplateFieldLibrary
class TemplateField(Base):
"""One placement of one library field inside one template."""
__tablename__ = "template_field"
__table_args__ = (
# Every read is "the fields of template X, in order", so the index
# covers both the filter and the sort.
Index("ix_template_field_template_sort", "template_id", "sort"),
Index("ix_template_field_field_id", "field_id"),
)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
template_id: Mapped[int] = mapped_column(
ForeignKey("template.id", ondelete="CASCADE"),
nullable=False,
)
#: ``RESTRICT``: a field still placed in a template must not vanish from
#: under it. The API enforces this in Python as well, since TiDB does not
#: enforce foreign keys itself.
field_id: Mapped[int] = mapped_column(
ForeignKey("template_field_library.id", ondelete="RESTRICT"),
nullable=False,
)
#: Display position within the template. Plain ascending integer — lower
#: sorts render first regardless of the field's ``level``.
sort: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
template: Mapped["Template"] = relationship(back_populates="items")
#: Eager-loaded because every template read needs the field's name and
#: typography; lazy loading would emit one query per row.
field: Mapped["TemplateFieldLibrary"] = relationship(lazy="joined")
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"<TemplateField template_id={self.template_id} "
f"field_id={self.field_id} sort={self.sort}>"
)