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.
This commit is contained in:
2026-09-18 17:48:11 +08:00
parent 2d113f9f6b
commit a5f884f440
25 changed files with 371 additions and 260 deletions
@@ -0,0 +1,50 @@
"""rename tables so every module prefixes its own
Two tables were named after the concept they came from rather than the module
they belong to, which made the schema read as if the template tables were part
of the paper module:
paper_template -> template the 模板 module
section_field -> template_field_library the 字段库, which the 模板 module
owns and every template draws on
The paper module (``paper``, ``paper_sentence``, ``paper_sentence_reference``)
and the join table (``template_field``) already followed the rule and are not
touched. After this revision the naming is:
template template_field template_field_library
paper paper_sentence paper_sentence_reference
A rename, not a copy: ``RENAME TABLE`` moves the rows and leaves the data in
place, and TiDB carries a referencing foreign key along with the renamed table
(verified against the running cluster before this migration was written), so
the constraints in ``template_field``, ``paper`` and ``paper_sentence`` now
point at ``template`` and ``template_field_library`` with no drop/recreate
step. Index names are left alone: they are per-table in MySQL and TiDB, and
``template_field`` — whose indexes embed its own name — is not renamed.
Revision ID: f27a1c6d9e04
Revises: c41d7b09e5af
Create Date: 2026-09-18
"""
from collections.abc import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f27a1c6d9e04"
down_revision: str | None = "c41d7b09e5af"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
op.rename_table("paper_template", "template")
op.rename_table("section_field", "template_field_library")
def downgrade() -> None:
op.rename_table("template_field_library", "section_field")
op.rename_table("template", "paper_template")
+2 -2
View File
@@ -2,10 +2,10 @@
from fastapi import APIRouter
from app.api.routes import health, papers, section_fields, templates
from app.api.routes import health, papers, template_field_library, templates
api_router = APIRouter()
api_router.include_router(health.router)
api_router.include_router(papers.router)
api_router.include_router(section_fields.router)
api_router.include_router(template_field_library.router)
api_router.include_router(templates.router)
+2 -2
View File
@@ -20,7 +20,7 @@ from sqlalchemy.orm import Session
from app.crud import paper as crud
from app.db.session import get_db
from app.models import Paper, PaperSentence, PaperTemplate
from app.models import Paper, PaperSentence, Template
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.paper import (
PaperCreate,
@@ -72,7 +72,7 @@ def _assert_template_exists(db: Session, template_id: int | None) -> None:
"""
if template_id is None:
return
if db.get(PaperTemplate, template_id) is None:
if db.get(Template, template_id) is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"模板 {template_id} 不存在",
@@ -1,4 +1,4 @@
"""Section-field library endpoints (字段管理).
"""Template-field library endpoints (字段管理).
The library is global and reusable: a field exists once and is then placed into
any number of templates. That is why deleting a field is guarded the join
@@ -9,20 +9,20 @@ dropping a live heading from every template would be data loss, not cleanup.
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import section_field as crud
from app.crud import template_field_library as crud
from app.db.session import get_db
from app.models import SectionField
from app.models import TemplateFieldLibrary
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.section_field import (
SectionFieldCreate,
SectionFieldRead,
SectionFieldUpdate,
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryRead,
TemplateFieldLibraryUpdate,
)
router = APIRouter(prefix="/section-fields", tags=["section-fields"])
router = APIRouter(prefix="/template-field-library", tags=["template-field-library"])
def _get_or_404(db: Session, field_id: int) -> SectionField:
def _get_or_404(db: Session, field_id: int) -> TemplateFieldLibrary:
field = crud.get(db, field_id)
if field is None:
raise HTTPException(
@@ -32,7 +32,7 @@ def _get_or_404(db: Session, field_id: int) -> SectionField:
return field
def _assert_unused(db: Session, fields: list[SectionField]) -> None:
def _assert_unused(db: Session, fields: list[TemplateFieldLibrary]) -> None:
"""Refuse the delete if any field is still placed in a template.
All offenders are reported at once rather than one per attempt, so a batch
@@ -55,16 +55,16 @@ def _assert_unused(db: Session, fields: list[SectionField]) -> None:
@router.get(
"",
response_model=PageResult[SectionFieldRead],
response_model=PageResult[TemplateFieldLibraryRead],
summary="List the field library",
)
def list_fields(
def list_library_entries(
db: Session = Depends(get_db),
keyword: str | None = Query(default=None, description="按字段名称模糊搜索"),
level: int | None = Query(default=None, ge=1, le=9, description="按字段等级过滤"),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=500),
) -> PageResult[SectionFieldRead]:
) -> PageResult[TemplateFieldLibraryRead]:
"""Browse the field library, grouped by level then creation order."""
rows, total = crud.list_fields(
db,
@@ -74,7 +74,7 @@ def list_fields(
page_size=page_size,
)
return PageResult.build(
items=[SectionFieldRead.model_validate(row) for row in rows],
items=[TemplateFieldLibraryRead.model_validate(row) for row in rows],
total=total,
page=page,
page_size=page_size,
@@ -83,24 +83,24 @@ def list_fields(
@router.post(
"",
response_model=SectionFieldRead,
response_model=TemplateFieldLibraryRead,
status_code=status.HTTP_201_CREATED,
summary="Create a section field",
summary="Create a library entry",
)
def create_field(
payload: SectionFieldCreate,
def create_library_entry(
payload: TemplateFieldLibraryCreate,
db: Session = Depends(get_db),
) -> SectionFieldRead:
) -> TemplateFieldLibraryRead:
"""Add a heading to the library, with its typography."""
return SectionFieldRead.model_validate(crud.create(db, payload))
return TemplateFieldLibraryRead.model_validate(crud.create(db, payload))
@router.post(
"/batch-delete",
response_model=BatchDeleteResult,
summary="Delete several section fields",
summary="Delete several library entries",
)
def batch_delete_fields(
def batch_delete_library_entries(
payload: BatchDeleteRequest,
db: Session = Depends(get_db),
) -> BatchDeleteResult:
@@ -115,40 +115,42 @@ def batch_delete_fields(
@router.get(
"/{field_id}",
response_model=SectionFieldRead,
summary="Fetch one section field",
response_model=TemplateFieldLibraryRead,
summary="Fetch one library entry",
)
def get_field(field_id: int, db: Session = Depends(get_db)) -> SectionFieldRead:
"""Return a single field."""
return SectionFieldRead.model_validate(_get_or_404(db, field_id))
def get_library_entry(
field_id: int, db: Session = Depends(get_db)
) -> TemplateFieldLibraryRead:
"""Return a single library entry."""
return TemplateFieldLibraryRead.model_validate(_get_or_404(db, field_id))
@router.patch(
"/{field_id}",
response_model=SectionFieldRead,
summary="Update a section field",
response_model=TemplateFieldLibraryRead,
summary="Update one library entry",
)
def update_field(
def update_library_entry(
field_id: int,
payload: SectionFieldUpdate,
payload: TemplateFieldLibraryUpdate,
db: Session = Depends(get_db),
) -> SectionFieldRead:
"""Rename or restyle a field.
) -> TemplateFieldLibraryRead:
"""Rename or restyle a library entry.
The change is visible in every template that places the field, because
templates store a reference rather than a copy.
"""
field = _get_or_404(db, field_id)
return SectionFieldRead.model_validate(crud.update(db, field, payload))
return TemplateFieldLibraryRead.model_validate(crud.update(db, field, payload))
@router.delete(
"/{field_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete a section field",
summary="Delete one library entry",
)
def delete_field(field_id: int, db: Session = Depends(get_db)) -> Response:
"""Delete an unused field."""
def delete_library_entry(field_id: int, db: Session = Depends(get_db)) -> Response:
"""Delete a library entry no template places."""
field = _get_or_404(db, field_id)
_assert_unused(db, [field])
crud.delete(db, field)
+22 -22
View File
@@ -15,21 +15,21 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import paper as paper_crud
from app.crud import paper_template as crud
from app.crud import template as crud
from app.db.session import get_db
from app.models import PaperTemplate
from app.models import Template
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.paper_template import (
PaperTemplateCreate,
PaperTemplateListItem,
PaperTemplateRead,
PaperTemplateUpdate,
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
TemplateRead,
TemplateUpdate,
)
router = APIRouter(prefix="/templates", tags=["templates"])
def _get_or_404(db: Session, template_id: int) -> PaperTemplate:
def _get_or_404(db: Session, template_id: int) -> Template:
template = crud.get(db, template_id)
if template is None:
raise HTTPException(
@@ -60,7 +60,7 @@ def _assert_not_used_by_papers(db: Session, template_ids: list[int]) -> None:
blockers = []
for template_id, count in sorted(counts.items()):
template = db.get(PaperTemplate, template_id)
template = db.get(Template, template_id)
name = template.name if template is not None else template_id
blockers.append(f"{name}”({count} 篇论文)")
@@ -91,7 +91,7 @@ def _assert_fields_exist(db: Session, field_ids: list[int]) -> None:
@router.get(
"",
response_model=PageResult[PaperTemplateListItem],
response_model=PageResult[TemplateListItem],
summary="List paper templates",
)
def list_templates(
@@ -99,7 +99,7 @@ def list_templates(
keyword: str | None = Query(default=None, description="按模板名称或摘要模糊搜索"),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=200),
) -> PageResult[PaperTemplateListItem]:
) -> PageResult[TemplateListItem]:
"""Browse templates, most recently edited first."""
items, total = crud.list_templates(
db, keyword=keyword, page=page, page_size=page_size
@@ -109,14 +109,14 @@ def list_templates(
@router.post(
"",
response_model=PaperTemplateRead,
response_model=TemplateRead,
status_code=status.HTTP_201_CREATED,
summary="Create a paper template",
)
def create_template(
payload: PaperTemplateCreate,
payload: TemplateCreate,
db: Session = Depends(get_db),
) -> PaperTemplateRead:
) -> TemplateRead:
"""Create a template from a name, an abstract, and a field selection."""
_assert_name_free(db, payload.name)
_assert_fields_exist(db, [item.field_id for item in payload.fields])
@@ -127,7 +127,7 @@ def create_template(
abstract=payload.abstract,
fields=payload.fields,
)
return PaperTemplateRead.from_model(template)
return TemplateRead.from_model(template)
@router.post(
@@ -146,24 +146,24 @@ def batch_delete_templates(
@router.get(
"/{template_id}",
response_model=PaperTemplateRead,
response_model=TemplateRead,
summary="Fetch one paper template with its outline",
)
def get_template(template_id: int, db: Session = Depends(get_db)) -> PaperTemplateRead:
def get_template(template_id: int, db: Session = Depends(get_db)) -> TemplateRead:
"""Return a template; ``fields`` arrives already ordered by ``sort``."""
return PaperTemplateRead.from_model(_get_or_404(db, template_id))
return TemplateRead.from_model(_get_or_404(db, template_id))
@router.patch(
"/{template_id}",
response_model=PaperTemplateRead,
response_model=TemplateRead,
summary="Update a paper template",
)
def update_template(
template_id: int,
payload: PaperTemplateUpdate,
payload: TemplateUpdate,
db: Session = Depends(get_db),
) -> PaperTemplateRead:
) -> TemplateRead:
"""Update the name, the abstract, the field selection, or any combination.
``fields`` is a full replacement when present. Omitting it leaves the
@@ -186,7 +186,7 @@ def update_template(
abstract_provided="abstract" in payload.model_fields_set,
fields=payload.fields,
)
return PaperTemplateRead.from_model(updated)
return TemplateRead.from_model(updated)
@router.delete(
+2 -2
View File
@@ -5,6 +5,6 @@ models. They own the commit: a route calls one function and gets back either a
persisted object or ``None``.
"""
from app.crud import paper, paper_template, section_field
from app.crud import paper, template, template_field_library
__all__ = ["paper", "paper_template", "section_field"]
__all__ = ["paper", "template", "template_field_library"]
+1 -1
View File
@@ -36,7 +36,7 @@ from app.models import (
Paper,
PaperSentence,
PaperSentenceReference,
PaperTemplate,
Template,
TemplateField,
)
from app.schemas.paper import (
@@ -1,4 +1,4 @@
"""Data access for paper templates and their ordered field selections."""
"""Data access for templates and their ordered field selections."""
from collections.abc import Sequence
@@ -6,8 +6,8 @@ from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import PaperTemplate, SectionField, TemplateField
from app.schemas.paper_template import PaperTemplateListItem, TemplateFieldInput
from app.models import Template, TemplateFieldLibrary, TemplateField
from app.schemas.template import TemplateListItem, TemplateFieldInput
def _conditions(keyword: str | None) -> list:
@@ -17,8 +17,8 @@ def _conditions(keyword: str | None) -> list:
pattern = like_pattern(keyword)
return [
or_(
PaperTemplate.name.like(pattern, escape=LIKE_ESCAPE),
PaperTemplate.abstract.like(pattern, escape=LIKE_ESCAPE),
Template.name.like(pattern, escape=LIKE_ESCAPE),
Template.abstract.like(pattern, escape=LIKE_ESCAPE),
)
]
@@ -27,8 +27,8 @@ def _field_count_column():
"""A correlated ``COUNT`` of the template's placement rows."""
return (
select(func.count(TemplateField.id))
.where(TemplateField.template_id == PaperTemplate.id)
.correlate(PaperTemplate)
.where(TemplateField.template_id == Template.id)
.correlate(Template)
.scalar_subquery()
)
@@ -39,7 +39,7 @@ def list_templates(
keyword: str | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[PaperTemplateListItem], int]:
) -> tuple[list[TemplateListItem], int]:
"""Return one page of templates with their field counts, plus the total.
The outline itself is left out: a table row needs the count, not the rows.
@@ -48,19 +48,19 @@ def list_templates(
conditions = _conditions(keyword)
total = db.scalar(
select(func.count(PaperTemplate.id)).where(*conditions)
select(func.count(Template.id)).where(*conditions)
) or 0
stmt = (
select(PaperTemplate, _field_count_column().label("field_count"))
select(Template, _field_count_column().label("field_count"))
.where(*conditions)
.order_by(PaperTemplate.updated_at.desc(), PaperTemplate.id.desc())
.order_by(Template.updated_at.desc(), Template.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
items = [
PaperTemplateListItem(
TemplateListItem(
id=template.id,
name=template.name,
abstract=template.abstract,
@@ -73,21 +73,21 @@ def list_templates(
return items, total
def get(db: Session, template_id: int) -> PaperTemplate | None:
def get(db: Session, template_id: int) -> Template | None:
"""Return one template with its outline already loaded, or ``None``.
``items`` (ordered by ``sort``) and each item's ``field`` are both
configured for eager loading on the relationships, so this is a fixed
number of queries rather than one per field.
"""
return db.get(PaperTemplate, template_id)
return db.get(Template, template_id)
def name_taken(db: Session, name: str, *, exclude_id: int | None = None) -> bool:
"""Whether another template already uses ``name``."""
stmt = select(func.count(PaperTemplate.id)).where(PaperTemplate.name == name)
stmt = select(func.count(Template.id)).where(Template.name == name)
if exclude_id is not None:
stmt = stmt.where(PaperTemplate.id != exclude_id)
stmt = stmt.where(Template.id != exclude_id)
return bool(db.scalar(stmt))
@@ -101,7 +101,7 @@ def missing_field_ids(db: Session, field_ids: Sequence[int]) -> list[int]:
if not wanted:
return []
found = set(
db.scalars(select(SectionField.id).where(SectionField.id.in_(wanted))).all()
db.scalars(select(TemplateFieldLibrary.id).where(TemplateFieldLibrary.id.in_(wanted))).all()
)
return sorted(wanted - found)
@@ -117,9 +117,9 @@ def create(
name: str,
abstract: str | None,
fields: Sequence[TemplateFieldInput],
) -> PaperTemplate:
) -> Template:
"""Insert a template together with its ordered selection."""
template = PaperTemplate(name=name, abstract=abstract)
template = Template(name=name, abstract=abstract)
template.items = _build_items(fields)
db.add(template)
db.commit()
@@ -129,13 +129,13 @@ def create(
def update(
db: Session,
template: PaperTemplate,
template: Template,
*,
name: str | None = None,
abstract: str | None = None,
abstract_provided: bool = False,
fields: Sequence[TemplateFieldInput] | None = None,
) -> PaperTemplate:
) -> Template:
"""Apply a partial update. ``fields=None`` leaves the selection untouched.
``abstract_provided`` distinguishes "clear the abstract" from "leave it"
@@ -159,7 +159,7 @@ def update(
return template
def delete(db: Session, template: PaperTemplate) -> None:
def delete(db: Session, template: Template) -> None:
"""Delete a template and its placement rows."""
db.delete(template)
db.commit()
@@ -171,7 +171,7 @@ def delete_many(db: Session, template_ids: Sequence[int]) -> int:
return 0
templates = list(
db.scalars(
select(PaperTemplate).where(PaperTemplate.id.in_(list(template_ids)))
select(Template).where(Template.id.in_(list(template_ids)))
).all()
)
for template in templates:
@@ -1,4 +1,4 @@
"""Data access for the reusable section-field library (字段管理)."""
"""Data access for the reusable template-field library (字段管理)."""
from collections.abc import Sequence
@@ -6,8 +6,11 @@ from sqlalchemy import Select, func, select
from sqlalchemy.orm import Session
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import SectionField, TemplateField
from app.schemas.section_field import SectionFieldCreate, SectionFieldUpdate
from app.models import TemplateField, TemplateFieldLibrary
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryUpdate,
)
def _conditions(keyword: str | None, level: int | None) -> list:
@@ -15,10 +18,10 @@ def _conditions(keyword: str | None, level: int | None) -> list:
conditions = []
if keyword:
conditions.append(
SectionField.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
TemplateFieldLibrary.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
)
if level is not None:
conditions.append(SectionField.level == level)
conditions.append(TemplateFieldLibrary.level == level)
return conditions
@@ -30,7 +33,7 @@ def _ordered(stmt: Select) -> Select:
ordered by ``name``: names carry hand-written numbering ("1.", "10.",
"2."), and string ordering would scramble it.
"""
return stmt.order_by(SectionField.level.asc(), SectionField.id.asc())
return stmt.order_by(TemplateFieldLibrary.level.asc(), TemplateFieldLibrary.id.asc())
def list_fields(
@@ -40,16 +43,16 @@ def list_fields(
level: int | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[SectionField], int]:
) -> tuple[list[TemplateFieldLibrary], int]:
"""Return one page of the field library, plus the unpaged total."""
conditions = _conditions(keyword, level)
total = db.scalar(
select(func.count(SectionField.id)).where(*conditions)
select(func.count(TemplateFieldLibrary.id)).where(*conditions)
) or 0
stmt = _ordered(
select(SectionField)
select(TemplateFieldLibrary)
.where(*conditions)
.offset((page - 1) * page_size)
.limit(page_size)
@@ -57,16 +60,16 @@ def list_fields(
return list(db.scalars(stmt).all()), total
def get(db: Session, field_id: int) -> SectionField | None:
def get(db: Session, field_id: int) -> TemplateFieldLibrary | None:
"""Return one field, or ``None``."""
return db.get(SectionField, field_id)
return db.get(TemplateFieldLibrary, field_id)
def get_many(db: Session, field_ids: Sequence[int]) -> list[SectionField]:
def get_many(db: Session, field_ids: Sequence[int]) -> list[TemplateFieldLibrary]:
"""Return every field whose id is in ``field_ids`` (missing ids ignored)."""
if not field_ids:
return []
stmt = select(SectionField).where(SectionField.id.in_(list(field_ids)))
stmt = select(TemplateFieldLibrary).where(TemplateFieldLibrary.id.in_(list(field_ids)))
return list(db.scalars(stmt).all())
@@ -89,16 +92,20 @@ def usage_counts(db: Session, field_ids: Sequence[int]) -> dict[int, int]:
return {field_id: count for field_id, count in db.execute(stmt).all()}
def create(db: Session, data: SectionFieldCreate) -> SectionField:
def create(db: Session, data: TemplateFieldLibraryCreate) -> TemplateFieldLibrary:
"""Insert a field."""
field = SectionField(**data.model_dump())
field = TemplateFieldLibrary(**data.model_dump())
db.add(field)
db.commit()
db.refresh(field)
return field
def update(db: Session, field: SectionField, data: SectionFieldUpdate) -> SectionField:
def update(
db: Session,
field: TemplateFieldLibrary,
data: TemplateFieldLibraryUpdate,
) -> TemplateFieldLibrary:
"""Apply a partial update to a field.
``exclude_unset`` is what makes PATCH semantics work: a key the client did
@@ -112,7 +119,7 @@ def update(db: Session, field: SectionField, data: SectionFieldUpdate) -> Sectio
return field
def delete(db: Session, field: SectionField) -> None:
def delete(db: Session, field: TemplateFieldLibrary) -> None:
"""Delete a field. Callers must check :func:`usage_counts` first."""
db.delete(field)
db.commit()
+20 -4
View File
@@ -7,6 +7,22 @@ be added to the imports below, not only to its own module.
The import order here is for readability only: relationships are declared by
name and resolved through the SQLAlchemy registry after every module has been
imported, so a cycle between two model modules is not a problem.
Table naming
------------
Every table is prefixed with the module it belongs to, and a class is named
after its table (``Template`` -> ``template``):
template the 模板 module
template_field a field placed in a template, with its position
template_field_library the 字段库 the template module draws on
paper the 论文 module
paper_sentence one sentence of one paper
paper_sentence_reference a citation of one sentence
``template_field`` and ``template_field_library`` are one word apart and mean
opposite things: the first is a *placement* (this template puts this field
here, ``sort`` included), the second is the *catalogue* it was picked from.
"""
from app.models.mixins import TimestampMixin
@@ -19,9 +35,9 @@ from app.models.paper import (
)
from app.models.paper_sentence import PaperSentence
from app.models.paper_sentence_reference import PaperSentenceReference
from app.models.paper_template import PaperTemplate
from app.models.section_field import SectionField
from app.models.template import Template
from app.models.template_field import TemplateField
from app.models.template_field_library import TemplateFieldLibrary
__all__ = [
"PAPER_STATUSES",
@@ -31,8 +47,8 @@ __all__ = [
"Paper",
"PaperSentence",
"PaperSentenceReference",
"PaperTemplate",
"SectionField",
"Template",
"TemplateField",
"TemplateFieldLibrary",
"TimestampMixin",
]
+4 -4
View File
@@ -3,7 +3,7 @@
A paper is a bag of metadata plus two things that are deliberately kept apart:
* its **structure**, which is not stored here at all. Every render reads the
:class:`~app.models.paper_template.PaperTemplate` the paper points at, live.
:class:`~app.models.template.Template` the paper points at, live.
Nothing is copied, so switching ``template_id`` re-shapes the whole document
in one write.
* its **content**, which lives in
@@ -33,7 +33,7 @@ from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.paper_sentence import PaperSentence
from app.models.paper_template import PaperTemplate
from app.models.template import Template
#: Writing state of a paper: 草稿 / 撰写中 / 已完成.
#:
@@ -65,7 +65,7 @@ class Paper(TimestampMixin, Base):
#: ``RESTRICT`` documents the intent (a template in use must not vanish);
#: TiDB does not enforce it, so the API refuses the template delete too.
template_id: Mapped[int | None] = mapped_column(
ForeignKey("paper_template.id", ondelete="RESTRICT"),
ForeignKey("template.id", ondelete="RESTRICT"),
nullable=True,
)
@@ -93,7 +93,7 @@ class Paper(TimestampMixin, Base):
#: Eager-loaded with the paper: every read of a paper shows its template
#: name, and a lazy load there would be one query per row in the table.
template: Mapped["PaperTemplate | None"] = relationship(lazy="joined")
template: Mapped["Template | None"] = relationship(lazy="joined")
#: The paper's sentences, in document order.
#:
+3 -3
View File
@@ -10,7 +10,7 @@ whole design:
meaningfully have in common. Swap the paper's template and this sentence
lands on whatever the new template puts at that position, with no per
sentence editing. (The name keeps the spelling the feature was specified
with; it reads ``paper_template_field_sort``.)
with; it reads ``template_field_sort``.)
``sort``
Where this sentence sits *inside* that paragraph. A paragraph is reassembled
@@ -40,7 +40,7 @@ from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.paper import Paper
from app.models.paper_sentence_reference import PaperSentenceReference
from app.models.paper_template import PaperTemplate
from app.models.template import Template
class PaperSentence(TimestampMixin, Base):
@@ -70,7 +70,7 @@ class PaperSentence(TimestampMixin, Base):
#: The template this sentence was written against — provenance only. Reads
#: never filter on it; see the module docstring.
template_id: Mapped[int | None] = mapped_column(
ForeignKey("paper_template.id", ondelete="SET NULL"),
ForeignKey("template.id", ondelete="SET NULL"),
nullable=True,
)
@@ -1,8 +1,9 @@
"""Paper templates (模板表).
"""Templates (模板表) — the outlines a paper can be written against.
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`,
colour are read from the referenced
:class:`~app.models.template_field_library.TemplateFieldLibrary`,
so correcting a field's styling updates every template that uses it.
"""
@@ -18,10 +19,10 @@ if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.template_field import TemplateField
class PaperTemplate(TimestampMixin, Base):
class Template(TimestampMixin, Base):
"""A named outline: a template name, a summary, and its ordered fields."""
__tablename__ = "paper_template"
__tablename__ = "template"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
@@ -43,4 +44,4 @@ class PaperTemplate(TimestampMixin, Base):
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"<PaperTemplate id={self.id} name={self.name!r}>"
return f"<Template id={self.id} name={self.name!r}>"
+6 -6
View File
@@ -25,8 +25,8 @@ 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
from app.models.template import Template
from app.models.template_field_library import TemplateFieldLibrary
class TemplateField(Base):
@@ -44,7 +44,7 @@ class TemplateField(Base):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
template_id: Mapped[int] = mapped_column(
ForeignKey("paper_template.id", ondelete="CASCADE"),
ForeignKey("template.id", ondelete="CASCADE"),
nullable=False,
)
@@ -52,7 +52,7 @@ class TemplateField(Base):
#: 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"),
ForeignKey("template_field_library.id", ondelete="RESTRICT"),
nullable=False,
)
@@ -60,11 +60,11 @@ class TemplateField(Base):
#: 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")
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["SectionField"] = relationship(lazy="joined")
field: Mapped["TemplateFieldLibrary"] = relationship(lazy="joined")
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
@@ -1,6 +1,6 @@
"""The reusable section-field library (字段).
"""The reusable template-field library (字段).
A *section field* is one heading a paper can contain "1. Introduction",
A *library entry* 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.
@@ -9,7 +9,7 @@ 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
:attr:`TemplateFieldLibrary.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.
@@ -20,6 +20,11 @@ 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.
Naming: the table is ``template_field_library`` and one row is one entry of it
the class is named after the table, as everywhere else in this package. The
library is global, but it belongs to the 模板 module: it is the raw material a
template is built from, and it is managed from the same menu.
"""
from decimal import Decimal
@@ -31,10 +36,10 @@ from app.db.base import Base
from app.models.mixins import TimestampMixin
class SectionField(TimestampMixin, Base):
class TemplateFieldLibrary(TimestampMixin, Base):
"""A single reusable heading, with the typography it should render in."""
__tablename__ = "section_field"
__tablename__ = "template_field_library"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
@@ -72,6 +77,6 @@ class SectionField(TimestampMixin, Base):
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"<SectionField id={self.id} name={self.name!r} "
f"<TemplateFieldLibrary id={self.id} name={self.name!r} "
f"level={self.level} color={self.font_color}>"
)
+18 -18
View File
@@ -23,19 +23,19 @@ from app.schemas.paper import (
SentenceRead,
SentenceUpdate,
)
from app.schemas.paper_template import (
PaperTemplateCreate,
PaperTemplateListItem,
PaperTemplateRead,
PaperTemplateUpdate,
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
TemplateRead,
TemplateUpdate,
TemplateFieldInput,
TemplateFieldRead,
)
from app.schemas.section_field import (
SectionFieldCreate,
SectionFieldRead,
SectionFieldRef,
SectionFieldUpdate,
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryRead,
TemplateFieldLibraryRef,
TemplateFieldLibraryUpdate,
)
__all__ = [
@@ -57,14 +57,14 @@ __all__ = [
"SentenceUpdate",
"BatchDeleteResult",
"PageResult",
"PaperTemplateCreate",
"PaperTemplateListItem",
"PaperTemplateRead",
"PaperTemplateUpdate",
"SectionFieldCreate",
"SectionFieldRead",
"SectionFieldRef",
"SectionFieldUpdate",
"TemplateCreate",
"TemplateListItem",
"TemplateRead",
"TemplateUpdate",
"TemplateFieldLibraryCreate",
"TemplateFieldLibraryRead",
"TemplateFieldLibraryRef",
"TemplateFieldLibraryUpdate",
"TemplateFieldInput",
"TemplateFieldRead",
"normalize_hex_color",
@@ -1,11 +1,11 @@
"""Request/response schemas for paper templates (模板管理)."""
"""Request/response schemas for templates (模板管理)."""
from datetime import datetime
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field
from app.models.paper_template import PaperTemplate
from app.models.template import Template
from app.models.template_field import TemplateField
from app.schemas.common import TypographyMixin
@@ -54,14 +54,14 @@ class TemplateFieldRead(TypographyMixin, BaseModel):
)
class PaperTemplateBase(BaseModel):
class TemplateBase(BaseModel):
"""Shared body of the create/update payloads."""
name: str = Field(min_length=1, max_length=255)
abstract: str | None = None
class PaperTemplateCreate(PaperTemplateBase):
class TemplateCreate(TemplateBase):
"""Payload for ``POST /templates``.
The field selection is free: any subset, any order, repeats allowed. The
@@ -71,7 +71,7 @@ class PaperTemplateCreate(PaperTemplateBase):
fields: list[TemplateFieldInput] = Field(default_factory=list)
class PaperTemplateUpdate(BaseModel):
class TemplateUpdate(BaseModel):
"""Payload for ``PATCH /templates/{id}``.
``fields`` is a full replacement when present omit it to leave the
@@ -83,7 +83,7 @@ class PaperTemplateUpdate(BaseModel):
fields: list[TemplateFieldInput] | None = None
class PaperTemplateListItem(BaseModel):
class TemplateListItem(BaseModel):
"""A template as it appears in the list table — no field rows."""
model_config = ConfigDict(from_attributes=True)
@@ -96,7 +96,7 @@ class PaperTemplateListItem(BaseModel):
updated_at: datetime
class PaperTemplateRead(BaseModel):
class TemplateRead(BaseModel):
"""A template with its outline, already ordered by ``sort``."""
model_config = ConfigDict(from_attributes=True)
@@ -111,7 +111,7 @@ class PaperTemplateRead(BaseModel):
updated_at: datetime
@classmethod
def from_model(cls, template: PaperTemplate) -> "PaperTemplateRead":
def from_model(cls, template: Template) -> "TemplateRead":
"""Build the response from a template and its placement rows."""
return cls(
id=template.id,
@@ -1,4 +1,4 @@
"""Request/response schemas for the section-field library (字段管理)."""
"""Request/response schemas for the template-field library (字段管理)."""
from datetime import datetime
from decimal import Decimal
@@ -8,8 +8,8 @@ from pydantic import BaseModel, ConfigDict, Field
from app.schemas.common import TypographyMixin
class SectionFieldBase(TypographyMixin, BaseModel):
"""Fields a client may set on a section field."""
class TemplateFieldLibraryBase(TypographyMixin, BaseModel):
"""Fields a client may set on a library entry."""
#: Display name, numbering included — e.g. ``"1. Introduction"``. Stored
#: and rendered verbatim; the API never rewrites it.
@@ -25,12 +25,12 @@ class SectionFieldBase(TypographyMixin, BaseModel):
font_color: str = Field(default="#000000", max_length=32)
class SectionFieldCreate(SectionFieldBase):
"""Payload for ``POST /section-fields``."""
class TemplateFieldLibraryCreate(TemplateFieldLibraryBase):
"""Payload for ``POST /template-field-library``."""
class SectionFieldUpdate(TypographyMixin, BaseModel):
"""Payload for ``PATCH /section-fields/{id}`` — every part optional.
class TemplateFieldLibraryUpdate(TypographyMixin, BaseModel):
"""Payload for ``PATCH /template-field-library/{id}`` — every part optional.
The colour normaliser tolerates ``None`` here; the validator returns
non-strings untouched, so an omitted colour stays omitted.
@@ -42,8 +42,8 @@ class SectionFieldUpdate(TypographyMixin, BaseModel):
font_color: str | None = Field(default=None, max_length=32)
class SectionFieldRead(SectionFieldBase):
"""A stored section field."""
class TemplateFieldLibraryRead(TemplateFieldLibraryBase):
"""A stored library entry."""
model_config = ConfigDict(from_attributes=True)
@@ -52,7 +52,7 @@ class SectionFieldRead(SectionFieldBase):
updated_at: datetime
class SectionFieldRef(BaseModel):
class TemplateFieldLibraryRef(BaseModel):
"""How many templates currently place a field — used to explain a refusal."""
field_id: int
+15 -12
View File
@@ -1,4 +1,4 @@
"""Seed the section-field library and a couple of starter templates.
"""Seed the template-field library and a couple of starter templates.
Idempotent: fields are matched by name and templates by name, so running it
twice adds nothing. ``--reset`` empties the three tables first, which is the
@@ -27,7 +27,7 @@ from sqlalchemy import delete, select # noqa: E402
from sqlalchemy.orm import Session # noqa: E402
from app.db.session import SessionLocal # noqa: E402
from app.models import PaperTemplate, SectionField, TemplateField # noqa: E402
from app.models import Template, TemplateFieldLibrary, TemplateField # noqa: E402
# --- the field library -------------------------------------------------------
#
@@ -118,20 +118,20 @@ TEMPLATES: list[tuple[str, str, list[str]]] = [
def reset(db: Session) -> None:
"""Empty the three tables in dependency order."""
db.execute(delete(TemplateField))
db.execute(delete(PaperTemplate))
db.execute(delete(SectionField))
db.execute(delete(Template))
db.execute(delete(TemplateFieldLibrary))
db.commit()
def seed_fields(db: Session) -> dict[str, SectionField]:
def seed_fields(db: Session) -> dict[str, TemplateFieldLibrary]:
"""Insert any missing library fields and return name -> field."""
existing = {field.name: field for field in db.scalars(select(SectionField)).all()}
existing = {field.name: field for field in db.scalars(select(TemplateFieldLibrary)).all()}
created = 0
for name, level, font_size, font_color in FIELDS:
if name in existing:
continue
field = SectionField(
field = TemplateFieldLibrary(
name=name, level=level, font_size=font_size, font_color=font_color
)
db.add(field)
@@ -142,13 +142,16 @@ def seed_fields(db: Session) -> dict[str, SectionField]:
for field in existing.values():
db.refresh(field)
print(f" section_field : {created} created, {len(existing) - created} already present")
print(
f" template_field_library : {created} created, "
f"{len(existing) - created} already present"
)
return existing
def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
def seed_templates(db: Session, fields: dict[str, TemplateFieldLibrary]) -> None:
"""Insert any missing starter templates."""
existing = {name for name in db.scalars(select(PaperTemplate.name)).all()}
existing = {name for name in db.scalars(select(Template.name)).all()}
created = 0
for name, abstract, field_names in TEMPLATES:
@@ -159,7 +162,7 @@ def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
if missing:
raise SystemExit(f"template {name!r} references unknown fields: {missing}")
template = PaperTemplate(name=name, abstract=abstract)
template = Template(name=name, abstract=abstract)
# sort is the list position: 1-based, ascending, with gaps allowed
# because the UI lets the user type any integer.
template.items = [
@@ -170,7 +173,7 @@ def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
created += 1
db.commit()
print(f" paper_template: {created} created, {len(existing)} already present")
print(f" template: {created} created, {len(existing)} already present")
def main() -> None: