backend: add section-field and paper-template schema, API, and seed data

Three tables behind the template configuration feature:

  section_field   the reusable heading library (name, level, font size,
                  colour)
  paper_template  a named outline (name, abstract)
  template_field  the join, and the only home of display order (sort)

The field library is deliberately flat. A `parent_id` would tie a level-2
heading to exactly one level-1 heading, and the point of the feature is that
a field such as "Background" can sit under both "1. Introduction" and
"2. Related Work" — and in any number of templates, at a different position
in each. Hierarchy is expressed only by `level`, which is a rendering hint.

Display order lives entirely in `template_field.sort`. The order fields were
picked in is never stored, so selecting fields out of order and assigning
sorts renders in sort order. Two consequences are intentional and documented
on the model: repeats are allowed (no unique constraint on template+field)
and ties are legal (broken by insertion order, so the ordering is total).

Templates reference library fields rather than copying them, so renaming or
restyling a field updates every template that places it.

TiDB parses FOREIGN KEY and then ignores it, so the constraints are declared
for documentation and the integrity is enforced in the application layer:
deleting a field still in use is refused with the field names, creating a
template against a missing field is refused, and deleting a template removes
its join rows through the ORM's delete-orphan cascade.

Also normalises font_color to #RRGGBB on write (accepting rgb() and
shorthand) and emits font_size as a JSON number rather than pydantic's
default Decimal string.

scripts/seed.py is idempotent and fills the library with a standard academic
outline plus three starter templates.
This commit is contained in:
2026-09-18 15:56:47 +08:00
parent cad96e585f
commit 13e5fc2cc1
18 changed files with 1540 additions and 15 deletions
+14 -11
View File
@@ -1,15 +1,18 @@
"""SQLAlchemy ORM models.
This package is intentionally empty.
No model classes exist yet, and no tables are created by this project at
import time. The schema will be introduced through Alembic migrations:
alembic revision --autogenerate -m "describe the change"
alembic upgrade head
When the first model is written, add it here (or in a submodule imported from
here) so that ``Base.metadata`` — and therefore autogenerate — can see it.
Importing this package registers every model on ``Base.metadata``, which is
what ``alembic revision --autogenerate`` inspects. A new model therefore has to
be added to the imports below, not only to its own module.
"""
__all__: list[str] = []
from app.models.mixins import TimestampMixin
from app.models.paper_template import PaperTemplate
from app.models.section_field import SectionField
from app.models.template_field import TemplateField
__all__ = [
"PaperTemplate",
"SectionField",
"TemplateField",
"TimestampMixin",
]
+26
View File
@@ -0,0 +1,26 @@
"""Column mixins shared by the ORM models."""
from datetime import datetime
from sqlalchemy import DateTime, func
from sqlalchemy.orm import Mapped, mapped_column
class TimestampMixin:
"""Adds ``created_at`` / ``updated_at`` to a model.
Timestamps are generated by the database on insert and refreshed by the
ORM on update, so a row written by any client carries a server clock value.
"""
created_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
server_default=func.now(),
)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
nullable=False,
server_default=func.now(),
onupdate=func.now(),
)
+46
View File
@@ -0,0 +1,46 @@
"""Paper templates (模板表).
A template is a named, ordered selection of library fields — the outline a
paper is written against. It stores no typography of its own: font size and
colour are read from the referenced :class:`~app.models.section_field.SectionField`,
so correcting a field's styling updates every template that uses it.
"""
from typing import TYPE_CHECKING
from sqlalchemy import String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.template_field import TemplateField
class PaperTemplate(TimestampMixin, Base):
"""A named outline: a template name, a summary, and its ordered fields."""
__tablename__ = "paper_template"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
#: Free-text abstract (摘要) describing when to use this template.
abstract: Mapped[str | None] = mapped_column(Text, nullable=True)
#: The template's fields, always handed to callers in display order.
#:
#: ``delete-orphan`` is doing real work here: TiDB parses but does not
#: enforce ``ON DELETE CASCADE``, so removing a template's rows in the join
#: table is the ORM's job, not the database's.
items: Mapped[list["TemplateField"]] = relationship(
back_populates="template",
cascade="all, delete-orphan",
order_by="TemplateField.sort, TemplateField.id",
lazy="selectin",
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"<PaperTemplate id={self.id} name={self.name!r}>"
+77
View File
@@ -0,0 +1,77 @@
"""The reusable section-field library (字段表).
A *section field* is one heading a paper can contain — "1. Introduction",
"2.1 Dataset", "0 Abstract". Fields live in this one global library and are
never owned by a template.
Why there is no ``parent_id``
-----------------------------
A tree would make a field usable under exactly one parent, so a level-2 heading
such as "Background" could not sit under both "1. Introduction" and
"2. Related Work". Hierarchy is therefore expressed only by
:attr:`SectionField.level` (1, 2, 3 ...), which is a *rendering hint* — it
drives indentation and numbering semantics in the UI — while a field stays
free to be attached to any number of templates and any number of parents
within them.
The number that the reader sees is part of :attr:`name` and is written by the
user ("1. Introduction", "0 Abstract"). Nothing derives or rewrites it.
Ordering inside a template is *not* stored here: it lives in
``template_field.sort``. This table has no ``sort`` column on purpose, so that
one library field can occupy a different position in every template.
"""
from decimal import Decimal
from sqlalchemy import Integer, Numeric, String, text
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base
from app.models.mixins import TimestampMixin
class SectionField(TimestampMixin, Base):
"""A single reusable heading, with the typography it should render in."""
__tablename__ = "section_field"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
#: Display name, numbering included. Stored and rendered verbatim.
name: Mapped[str] = mapped_column(String(255), nullable=False)
#: Heading depth: 1 for "1.", 2 for "1.1", 3 for "1.1.1". Rendering hint
#: only — it does not link fields to each other.
level: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
server_default=text("1"),
)
#: Font size in points. ``Numeric`` rather than ``Integer`` because the
#: conventional Chinese sizes are fractional (五号 = 10.5pt,
#: 小四 = 12pt).
font_size: Mapped[Decimal] = mapped_column(
Numeric(4, 1),
nullable=False,
default=Decimal("12.0"),
server_default=text("12.0"),
)
#: Font colour as ``#RRGGBB`` — the canonical RGB encoding. The API
#: normalises ``rgb(20, 30, 40)``, ``#abc`` and bare ``aabbcc`` to it on
#: write, so the column always holds one comparable format.
font_color: Mapped[str] = mapped_column(
String(7),
nullable=False,
default="#000000",
server_default=text("'#000000'"),
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"<SectionField id={self.id} name={self.name!r} "
f"level={self.level} color={self.font_color}>"
)
+73
View File
@@ -0,0 +1,73 @@
"""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.paper_template import PaperTemplate
from app.models.section_field import SectionField
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("paper_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("section_field.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["PaperTemplate"] = 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["SectionField"] = 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}>"
)