backend: tag the literature, in a table of its own
A tag is the writer's filing of a row — 「综述」, 「必读」 — and it is a different fact from `reference.keywords`, which are the 关键词 printed on the article. A tag never prints, one document carries several, and the same label is on many documents, so it gets two tables rather than a column: reference_tag name (unique), colour, note reference_tag_link reference_id + tag_id — the pair is the primary key The link is a bare link, which is why it is `_link` and not `_placement`: there is no `sort` to own, so the pair *is* the row and the same label cannot be applied twice. A tag is made first and applied second: `tag_ids`, never tag names, so a typo cannot invent a label — an unknown id is a 400 naming it, and nothing is written. Deleting a tag is deliberately *not* guarded the way deleting a cited reference is: both foreign keys cascade, so the labels go and the literature stays. `GET /references?tag=1&tag=2` narrows rather than widens — the rows carrying both labels — because that is what a second filter reads as. The smoke test now walks the whole flow in the order the feature intends: labels first, then tagged references, then a rename that follows every row.
This commit is contained in:
@@ -8,6 +8,10 @@ table row never has to load the rows behind it.
|
||||
Writes keep the two lists (authors, citations) on their own side: authors belong
|
||||
to the reference and are replaced wholesale, citations belong to the papers that
|
||||
made them and are never touched from here.
|
||||
|
||||
Tags are the third list and follow the same rule as authors — sent as ids, stored
|
||||
as links, replaced wholesale — except that the ids must already exist: a tag is
|
||||
made first and applied second, so a typo cannot invent a label.
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
@@ -15,6 +19,7 @@ from collections.abc import Sequence
|
||||
from sqlalchemy import Select, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import reference_tag as tag_crud
|
||||
from app.crud.filters import LIKE_ESCAPE, like_pattern
|
||||
from app.models import (
|
||||
Paper,
|
||||
@@ -22,8 +27,10 @@ from app.models import (
|
||||
PaperSentenceReference,
|
||||
Reference,
|
||||
ReferenceAuthor,
|
||||
ReferenceTag,
|
||||
TemplateTitle,
|
||||
TemplateTitlePlacement,
|
||||
reference_tag_link,
|
||||
)
|
||||
from app.schemas.reference import (
|
||||
ReferenceCitationRead,
|
||||
@@ -32,6 +39,7 @@ from app.schemas.reference import (
|
||||
ReferenceRead,
|
||||
ReferenceUpdate,
|
||||
)
|
||||
from app.schemas.reference_tag import ReferenceTagRef
|
||||
|
||||
#: How many authors a table row prints before it cuts the line short.
|
||||
_LIST_AUTHOR_LIMIT = 3
|
||||
@@ -42,6 +50,7 @@ def _conditions(
|
||||
type_: str | None,
|
||||
year: int | None,
|
||||
cited_only: bool | None,
|
||||
tag_ids: Sequence[int] | None = None,
|
||||
) -> list:
|
||||
"""Translate the list filters into SQLAlchemy predicates."""
|
||||
conditions = []
|
||||
@@ -73,6 +82,18 @@ def _conditions(
|
||||
conditions.append(_citation_count_column() > 0)
|
||||
if cited_only is False:
|
||||
conditions.append(_citation_count_column() == 0)
|
||||
# One EXISTS per tag rather than an IN over the link table: IN would ask
|
||||
# "carries at least one of these", while repeated filters read as a
|
||||
# narrowing — 「方法」 plus 「必读」 means both labels are on the row.
|
||||
for tag_id in dict.fromkeys(tag_ids or ()):
|
||||
conditions.append(
|
||||
select(reference_tag_link.c.reference_id)
|
||||
.where(
|
||||
reference_tag_link.c.reference_id == Reference.id,
|
||||
reference_tag_link.c.tag_id == tag_id,
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
return conditions
|
||||
|
||||
|
||||
@@ -119,11 +140,12 @@ def list_references(
|
||||
type_: str | None = None,
|
||||
year: int | None = None,
|
||||
cited_only: bool | None = None,
|
||||
tag_ids: Sequence[int] | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[ReferenceListItem], int]:
|
||||
"""Return one page of the library, plus the unpaged total."""
|
||||
conditions = _conditions(keyword, type_, year, cited_only)
|
||||
conditions = _conditions(keyword, type_, year, cited_only, tag_ids)
|
||||
|
||||
total = db.scalar(select(func.count(Reference.id)).where(*conditions)) or 0
|
||||
|
||||
@@ -147,6 +169,7 @@ def list_references(
|
||||
title=row.title,
|
||||
subtitle=row.subtitle,
|
||||
container_title=row.container_title,
|
||||
publisher=row.publisher,
|
||||
publication_year=row.publication_year,
|
||||
volume=row.volume,
|
||||
issue=row.issue,
|
||||
@@ -154,6 +177,7 @@ def list_references(
|
||||
doi=row.doi,
|
||||
authors_line=authors_line(row.authors),
|
||||
author_count=len(row.authors),
|
||||
tags=[ReferenceTagRef.model_validate(tag) for tag in row.tags],
|
||||
citation_count=counts.get(row.id, 0),
|
||||
created_at=row.created_at,
|
||||
updated_at=row.updated_at,
|
||||
@@ -241,6 +265,7 @@ def read(db: Session, reference: Reference) -> ReferenceRead:
|
||||
for column in Reference.__table__.columns
|
||||
},
|
||||
"authors": reference.authors,
|
||||
"tags": reference.tags,
|
||||
"citation_count": counts.get(reference.id, 0),
|
||||
}
|
||||
)
|
||||
@@ -263,16 +288,28 @@ def _build_authors(
|
||||
|
||||
|
||||
def create(db: Session, data: ReferenceCreate) -> Reference:
|
||||
"""Insert a reference together with its contributors."""
|
||||
values = data.model_dump(exclude={"authors"})
|
||||
"""Insert a reference together with its contributors and its tags."""
|
||||
tags = _resolve_tags(db, data.tag_ids)
|
||||
values = data.model_dump(exclude={"authors", "tag_ids"})
|
||||
reference = Reference(**values)
|
||||
reference.authors = _build_authors(data.authors)
|
||||
reference.tags = tags
|
||||
db.add(reference)
|
||||
db.commit()
|
||||
db.refresh(reference)
|
||||
return reference
|
||||
|
||||
|
||||
def _resolve_tags(db: Session, tag_ids: Sequence[int]) -> list[ReferenceTag]:
|
||||
"""Load the tags to apply, refusing ids the library does not have.
|
||||
|
||||
Nothing is written before this returns, so a reference naming a tag that
|
||||
does not exist is rejected whole rather than stored half-labelled.
|
||||
"""
|
||||
tag_crud.assert_exist(db, tag_ids)
|
||||
return tag_crud.get_many(db, tag_ids)
|
||||
|
||||
|
||||
def update(
|
||||
db: Session,
|
||||
reference: Reference,
|
||||
@@ -283,8 +320,14 @@ def update(
|
||||
``exclude_unset`` is what makes PATCH semantics work: a key the client did
|
||||
not send leaves the column alone, so clearing a field is an explicit
|
||||
``null`` and omitting it is not.
|
||||
|
||||
``authors`` and ``tag_ids`` are full replacements when present — the first
|
||||
because a citation prints the list in the order sent, the second because the
|
||||
list *is* the set of labels on the row.
|
||||
"""
|
||||
values = data.model_dump(exclude_unset=True, exclude={"authors"})
|
||||
tags = _resolve_tags(db, data.tag_ids) if data.tag_ids is not None else None
|
||||
|
||||
values = data.model_dump(exclude_unset=True, exclude={"authors", "tag_ids"})
|
||||
for key, value in values.items():
|
||||
setattr(reference, key, value)
|
||||
|
||||
@@ -295,6 +338,12 @@ def update(
|
||||
db.flush()
|
||||
reference.authors.extend(_build_authors(data.authors))
|
||||
|
||||
if tags is not None:
|
||||
# Assigning to a secondary relationship rewrites the link rows: the ones
|
||||
# that stayed are untouched, the new ones are inserted, the dropped ones
|
||||
# deleted. An empty list therefore clears every label.
|
||||
reference.tags = tags
|
||||
|
||||
db.commit()
|
||||
db.refresh(reference)
|
||||
return reference
|
||||
|
||||
Reference in New Issue
Block a user