refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.
template_field_library -> template_title
template_field -> template_title_placement
field_id (the column) -> title_id
TemplateFieldLibrary -> TemplateTitle
TemplateField -> TemplateTitlePlacement
The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.
Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.
Two deliberate exceptions:
* `paper_template_filed_sort` is untouched — it is a column of the paper module
and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
the `fields`/`field_id` keys in their responses). Agents already call them by
those names; the storage names they read underneath have changed.
The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.
Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
"""Data access for templates and their ordered field selections."""
|
||||
"""Data access for templates and their ordered title 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 Template, TemplateFieldLibrary, TemplateField
|
||||
from app.schemas.template import TemplateListItem, TemplateFieldInput
|
||||
from app.models import Template, TemplateTitle, TemplateTitlePlacement
|
||||
from app.schemas.template import TemplateListItem, TemplateTitlePlacementInput
|
||||
|
||||
|
||||
def _conditions(keyword: str | None) -> list:
|
||||
@@ -23,11 +23,11 @@ def _conditions(keyword: str | None) -> list:
|
||||
]
|
||||
|
||||
|
||||
def _field_count_column():
|
||||
def _placement_count_column():
|
||||
"""A correlated ``COUNT`` of the template's placement rows."""
|
||||
return (
|
||||
select(func.count(TemplateField.id))
|
||||
.where(TemplateField.template_id == Template.id)
|
||||
select(func.count(TemplateTitlePlacement.id))
|
||||
.where(TemplateTitlePlacement.template_id == Template.id)
|
||||
.correlate(Template)
|
||||
.scalar_subquery()
|
||||
)
|
||||
@@ -40,7 +40,7 @@ def list_templates(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[TemplateListItem], int]:
|
||||
"""Return one page of templates with their field counts, plus the total.
|
||||
"""Return one page of templates with their placement counts, plus the total.
|
||||
|
||||
The outline itself is left out: a table row needs the count, not the rows.
|
||||
Recently edited templates come first, since that is what a user returns to.
|
||||
@@ -52,7 +52,7 @@ def list_templates(
|
||||
) or 0
|
||||
|
||||
stmt = (
|
||||
select(Template, _field_count_column().label("field_count"))
|
||||
select(Template, _placement_count_column().label("placement_count"))
|
||||
.where(*conditions)
|
||||
.order_by(Template.updated_at.desc(), Template.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
@@ -64,11 +64,11 @@ def list_templates(
|
||||
id=template.id,
|
||||
name=template.name,
|
||||
abstract=template.abstract,
|
||||
field_count=field_count,
|
||||
placement_count=placement_count,
|
||||
created_at=template.created_at,
|
||||
updated_at=template.updated_at,
|
||||
)
|
||||
for template, field_count in db.execute(stmt).all()
|
||||
for template, placement_count in db.execute(stmt).all()
|
||||
]
|
||||
return items, total
|
||||
|
||||
@@ -76,9 +76,9 @@ def list_templates(
|
||||
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.
|
||||
``placements`` (ordered by ``sort``) and each placement's ``title`` are
|
||||
both configured for eager loading on the relationships, so this is a fixed
|
||||
number of queries rather than one per title.
|
||||
"""
|
||||
return db.get(Template, template_id)
|
||||
|
||||
@@ -91,24 +91,29 @@ def name_taken(db: Session, name: str, *, exclude_id: int | None = None) -> bool
|
||||
return bool(db.scalar(stmt))
|
||||
|
||||
|
||||
def missing_field_ids(db: Session, field_ids: Sequence[int]) -> list[int]:
|
||||
"""Which of ``field_ids`` do not exist in the field library.
|
||||
def missing_title_ids(db: Session, title_ids: Sequence[int]) -> list[int]:
|
||||
"""Which of ``title_ids`` do not exist in the title library.
|
||||
|
||||
Returning the offenders rather than a boolean lets the API name them, which
|
||||
is the difference between a usable error and "invalid request".
|
||||
"""
|
||||
wanted = set(field_ids)
|
||||
wanted = set(title_ids)
|
||||
if not wanted:
|
||||
return []
|
||||
found = set(
|
||||
db.scalars(select(TemplateFieldLibrary.id).where(TemplateFieldLibrary.id.in_(wanted))).all()
|
||||
db.scalars(select(TemplateTitle.id).where(TemplateTitle.id.in_(wanted))).all()
|
||||
)
|
||||
return sorted(wanted - found)
|
||||
|
||||
|
||||
def _build_items(fields: Sequence[TemplateFieldInput]) -> list[TemplateField]:
|
||||
def _build_placements(
|
||||
placements: Sequence[TemplateTitlePlacementInput],
|
||||
) -> list[TemplateTitlePlacement]:
|
||||
"""Materialise the client's selection into placement rows."""
|
||||
return [TemplateField(field_id=item.field_id, sort=item.sort) for item in fields]
|
||||
return [
|
||||
TemplateTitlePlacement(title_id=item.title_id, sort=item.sort)
|
||||
for item in placements
|
||||
]
|
||||
|
||||
|
||||
def create(
|
||||
@@ -116,11 +121,11 @@ def create(
|
||||
*,
|
||||
name: str,
|
||||
abstract: str | None,
|
||||
fields: Sequence[TemplateFieldInput],
|
||||
placements: Sequence[TemplateTitlePlacementInput],
|
||||
) -> Template:
|
||||
"""Insert a template together with its ordered selection."""
|
||||
template = Template(name=name, abstract=abstract)
|
||||
template.items = _build_items(fields)
|
||||
template.placements = _build_placements(placements)
|
||||
db.add(template)
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
@@ -134,9 +139,9 @@ def update(
|
||||
name: str | None = None,
|
||||
abstract: str | None = None,
|
||||
abstract_provided: bool = False,
|
||||
fields: Sequence[TemplateFieldInput] | None = None,
|
||||
placements: Sequence[TemplateTitlePlacementInput] | None = None,
|
||||
) -> Template:
|
||||
"""Apply a partial update. ``fields=None`` leaves the selection untouched.
|
||||
"""Apply a partial update. ``placements=None`` leaves the selection untouched.
|
||||
|
||||
``abstract_provided`` distinguishes "clear the abstract" from "leave it" —
|
||||
both arrive as ``None`` in the payload, and only the caller knows which the
|
||||
@@ -146,13 +151,12 @@ def update(
|
||||
template.name = name
|
||||
if abstract_provided:
|
||||
template.abstract = abstract
|
||||
if fields is not None:
|
||||
# delete-orphan removes the dropped rows on flush. TiDB does not
|
||||
# enforce ON DELETE CASCADE, so this ORM-level cascade is the only
|
||||
# thing cleaning up the join table.
|
||||
template.items.clear()
|
||||
if placements is not None:
|
||||
# delete-orphan removes the dropped rows on flush. The ORM cascade is
|
||||
# what cleans up the join table, whether or not the database would.
|
||||
template.placements.clear()
|
||||
db.flush()
|
||||
template.items.extend(_build_items(fields))
|
||||
template.placements.extend(_build_placements(placements))
|
||||
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
|
||||
Reference in New Issue
Block a user