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
+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(