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:
@@ -0,0 +1,157 @@
|
||||
"""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
|
||||
table is the only thing keeping a template's outline intact, and silently
|
||||
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 template_field_library as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import TemplateFieldLibrary
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryRead,
|
||||
TemplateFieldLibraryUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/template-field-library", tags=["template-field-library"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, field_id: int) -> TemplateFieldLibrary:
|
||||
field = crud.get(db, field_id)
|
||||
if field is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"字段 {field_id} 不存在",
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
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
|
||||
delete does not turn into trial and error.
|
||||
"""
|
||||
counts = crud.usage_counts(db, [field.id for field in fields])
|
||||
if not counts:
|
||||
return
|
||||
|
||||
by_id = {field.id: field.name for field in fields}
|
||||
blockers = "、".join(
|
||||
f"“{by_id.get(field_id, field_id)}”({count} 个模板)"
|
||||
for field_id, count in sorted(counts.items())
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"以下字段正被模板使用,请先在模板中移除:{blockers}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PageResult[TemplateFieldLibraryRead],
|
||||
summary="List the field library",
|
||||
)
|
||||
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[TemplateFieldLibraryRead]:
|
||||
"""Browse the field library, grouped by level then creation order."""
|
||||
rows, total = crud.list_fields(
|
||||
db,
|
||||
keyword=keyword,
|
||||
level=level,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return PageResult.build(
|
||||
items=[TemplateFieldLibraryRead.model_validate(row) for row in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a library entry",
|
||||
)
|
||||
def create_library_entry(
|
||||
payload: TemplateFieldLibraryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Add a heading to the library, with its typography."""
|
||||
return TemplateFieldLibraryRead.model_validate(crud.create(db, payload))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several library entries",
|
||||
)
|
||||
def batch_delete_library_entries(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given fields, refusing wholesale if any is still in use."""
|
||||
fields = crud.get_many(db, payload.ids)
|
||||
_assert_unused(db, fields)
|
||||
|
||||
for field in fields:
|
||||
crud.delete(db, field)
|
||||
return BatchDeleteResult(deleted=len(fields))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{field_id}",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
summary="Fetch one library entry",
|
||||
)
|
||||
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=TemplateFieldLibraryRead,
|
||||
summary="Update one library entry",
|
||||
)
|
||||
def update_library_entry(
|
||||
field_id: int,
|
||||
payload: TemplateFieldLibraryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> 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 TemplateFieldLibraryRead.model_validate(crud.update(db, field, payload))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{field_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete one library entry",
|
||||
)
|
||||
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)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
Reference in New Issue
Block a user