From a5f884f44026a2b795b335abf1df5d8dee1a1cca Mon Sep 17 00:00:00 2001 From: govin Date: Fri, 18 Sep 2026 17:48:11 +0800 Subject: [PATCH] refactor: prefix every table with its module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- ...6d9e04_rename_tables_to_module_prefixes.py | 50 ++++++++++++ backend/app/api/router.py | 4 +- backend/app/api/routes/papers.py | 4 +- ...on_fields.py => template_field_library.py} | 76 ++++++++++--------- backend/app/api/routes/templates.py | 44 +++++------ backend/app/crud/__init__.py | 4 +- backend/app/crud/paper.py | 2 +- .../crud/{paper_template.py => template.py} | 46 +++++------ ...ion_field.py => template_field_library.py} | 41 +++++----- backend/app/models/__init__.py | 24 +++++- backend/app/models/paper.py | 8 +- backend/app/models/paper_sentence.py | 6 +- .../models/{paper_template.py => template.py} | 11 +-- backend/app/models/template_field.py | 12 +-- ...ion_field.py => template_field_library.py} | 17 +++-- backend/app/schemas/__init__.py | 36 ++++----- .../{paper_template.py => template.py} | 16 ++-- ...ion_field.py => template_field_library.py} | 20 ++--- backend/scripts/seed.py | 27 ++++--- docs/OVERVIEW.md | 74 ++++++++++++------ ...ctionFields.ts => templateFieldLibrary.ts} | 49 ++++++------ .../src/components/fields/FieldFormDialog.vue | 20 ++--- .../templates/TemplateFormDialog.vue | 8 +- frontend/src/views/HomeView.vue | 4 +- .../src/views/templates/FieldManageView.vue | 28 +++---- 25 files changed, 371 insertions(+), 260 deletions(-) create mode 100644 backend/alembic/versions/f27a1c6d9e04_rename_tables_to_module_prefixes.py rename backend/app/api/routes/{section_fields.py => template_field_library.py} (63%) rename backend/app/crud/{paper_template.py => template.py} (76%) rename backend/app/crud/{section_field.py => template_field_library.py} (68%) rename backend/app/models/{paper_template.py => template.py} (82%) rename backend/app/models/{section_field.py => template_field_library.py} (79%) rename backend/app/schemas/{paper_template.py => template.py} (89%) rename backend/app/schemas/{section_field.py => template_field_library.py} (70%) rename frontend/src/api/{sectionFields.ts => templateFieldLibrary.ts} (54%) diff --git a/backend/alembic/versions/f27a1c6d9e04_rename_tables_to_module_prefixes.py b/backend/alembic/versions/f27a1c6d9e04_rename_tables_to_module_prefixes.py new file mode 100644 index 0000000..0956b9d --- /dev/null +++ b/backend/alembic/versions/f27a1c6d9e04_rename_tables_to_module_prefixes.py @@ -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") diff --git a/backend/app/api/router.py b/backend/app/api/router.py index 8031352..2586551 100644 --- a/backend/app/api/router.py +++ b/backend/app/api/router.py @@ -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) diff --git a/backend/app/api/routes/papers.py b/backend/app/api/routes/papers.py index d11e94b..9ffa5f2 100644 --- a/backend/app/api/routes/papers.py +++ b/backend/app/api/routes/papers.py @@ -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} 不存在", diff --git a/backend/app/api/routes/section_fields.py b/backend/app/api/routes/template_field_library.py similarity index 63% rename from backend/app/api/routes/section_fields.py rename to backend/app/api/routes/template_field_library.py index 3eef7f9..2e4bb07 100644 --- a/backend/app/api/routes/section_fields.py +++ b/backend/app/api/routes/template_field_library.py @@ -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) diff --git a/backend/app/api/routes/templates.py b/backend/app/api/routes/templates.py index 88a75ab..cf217b9 100644 --- a/backend/app/api/routes/templates.py +++ b/backend/app/api/routes/templates.py @@ -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( diff --git a/backend/app/crud/__init__.py b/backend/app/crud/__init__.py index 77d0e7d..5e76cc9 100644 --- a/backend/app/crud/__init__.py +++ b/backend/app/crud/__init__.py @@ -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"] diff --git a/backend/app/crud/paper.py b/backend/app/crud/paper.py index 1690764..ce06228 100644 --- a/backend/app/crud/paper.py +++ b/backend/app/crud/paper.py @@ -36,7 +36,7 @@ from app.models import ( Paper, PaperSentence, PaperSentenceReference, - PaperTemplate, + Template, TemplateField, ) from app.schemas.paper import ( diff --git a/backend/app/crud/paper_template.py b/backend/app/crud/template.py similarity index 76% rename from backend/app/crud/paper_template.py rename to backend/app/crud/template.py index 2ed8f5d..d90cfae 100644 --- a/backend/app/crud/paper_template.py +++ b/backend/app/crud/template.py @@ -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: diff --git a/backend/app/crud/section_field.py b/backend/app/crud/template_field_library.py similarity index 68% rename from backend/app/crud/section_field.py rename to backend/app/crud/template_field_library.py index 35c2571..a7e6921 100644 --- a/backend/app/crud/section_field.py +++ b/backend/app/crud/template_field_library.py @@ -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() diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index b6f1573..fd047ec 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -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", ] diff --git a/backend/app/models/paper.py b/backend/app/models/paper.py index c846543..b4d23f7 100644 --- a/backend/app/models/paper.py +++ b/backend/app/models/paper.py @@ -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. #: diff --git a/backend/app/models/paper_sentence.py b/backend/app/models/paper_sentence.py index d1dc1ef..ee84129 100644 --- a/backend/app/models/paper_sentence.py +++ b/backend/app/models/paper_sentence.py @@ -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, ) diff --git a/backend/app/models/paper_template.py b/backend/app/models/template.py similarity index 82% rename from backend/app/models/paper_template.py rename to backend/app/models/template.py index 35c191e..1bf3015 100644 --- a/backend/app/models/paper_template.py +++ b/backend/app/models/template.py @@ -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"" + return f"