feat(fc3a): ArtistService.find_or_create + autocomplete
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,6 +9,7 @@ Dates come from Post.post_date via ImageProvenance.post_id.
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from sqlalchemy import and_, func, or_, select
|
from sqlalchemy import and_, func, or_, select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from ..models import (
|
from ..models import (
|
||||||
@@ -20,6 +21,7 @@ from ..models import (
|
|||||||
Tag,
|
Tag,
|
||||||
)
|
)
|
||||||
from ..models.tag import image_tag
|
from ..models.tag import image_tag
|
||||||
|
from ..utils.slug import slugify
|
||||||
from .gallery_service import decode_cursor, encode_cursor, thumbnail_url
|
from .gallery_service import decode_cursor, encode_cursor, thumbnail_url
|
||||||
|
|
||||||
|
|
||||||
@@ -191,3 +193,49 @@ class ArtistService:
|
|||||||
],
|
],
|
||||||
next_cursor=next_cursor,
|
next_cursor=next_cursor,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def find_or_create(self, name: str) -> tuple[Artist, bool]:
|
||||||
|
"""Return (artist, created). Slug-keyed; idempotent under races."""
|
||||||
|
cleaned = (name or "").strip()
|
||||||
|
if not cleaned:
|
||||||
|
raise ValueError("artist name must not be empty")
|
||||||
|
slug = slugify(cleaned)
|
||||||
|
|
||||||
|
existing = (await self.session.execute(
|
||||||
|
select(Artist).where(Artist.slug == slug)
|
||||||
|
)).scalar_one_or_none()
|
||||||
|
if existing is not None:
|
||||||
|
return existing, False
|
||||||
|
|
||||||
|
artist = Artist(name=cleaned, slug=slug)
|
||||||
|
self.session.add(artist)
|
||||||
|
try:
|
||||||
|
await self.session.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
await self.session.rollback()
|
||||||
|
existing = (await self.session.execute(
|
||||||
|
select(Artist).where(Artist.slug == slug)
|
||||||
|
)).scalar_one()
|
||||||
|
return existing, False
|
||||||
|
await self.session.commit()
|
||||||
|
return artist, True
|
||||||
|
|
||||||
|
async def autocomplete(self, prefix: str, limit: int = 20) -> list[Artist]:
|
||||||
|
cleaned = (prefix or "").strip()
|
||||||
|
if not cleaned:
|
||||||
|
return []
|
||||||
|
like = f"%{cleaned.lower()}%"
|
||||||
|
prefix_like = f"{cleaned.lower()}%"
|
||||||
|
# Rank: exact (0) < prefix (1) < substring (2).
|
||||||
|
rank = func.case(
|
||||||
|
(func.lower(Artist.name) == cleaned.lower(), 0),
|
||||||
|
(func.lower(Artist.name).like(prefix_like), 1),
|
||||||
|
else_=2,
|
||||||
|
).label("rank")
|
||||||
|
rows = (await self.session.execute(
|
||||||
|
select(Artist, rank)
|
||||||
|
.where(func.lower(Artist.name).like(like))
|
||||||
|
.order_by(rank, Artist.name.asc())
|
||||||
|
.limit(limit)
|
||||||
|
)).all()
|
||||||
|
return [a for a, _ in rows]
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
from backend.app.models import Artist
|
||||||
|
from backend.app.services.artist_service import ArtistService
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.integration
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_find_or_create_creates_new(db):
|
||||||
|
svc = ArtistService(db)
|
||||||
|
artist, created = await svc.find_or_create("Brand New")
|
||||||
|
assert created is True
|
||||||
|
assert artist.id is not None
|
||||||
|
assert artist.slug == "brand-new"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_find_or_create_idempotent_on_same_name(db):
|
||||||
|
svc = ArtistService(db)
|
||||||
|
a1, c1 = await svc.find_or_create("Alice")
|
||||||
|
a2, c2 = await svc.find_or_create("Alice")
|
||||||
|
assert c1 is True
|
||||||
|
assert c2 is False
|
||||||
|
assert a1.id == a2.id
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_find_or_create_rejects_empty_name(db):
|
||||||
|
svc = ArtistService(db)
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
await svc.find_or_create(" ")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_autocomplete_ranks_exact_prefix_substring(db):
|
||||||
|
db.add_all([
|
||||||
|
Artist(name="Alice", slug="alice"),
|
||||||
|
Artist(name="Alice Cooper", slug="alice-cooper"),
|
||||||
|
Artist(name="Malice", slug="malice"),
|
||||||
|
Artist(name="Bob", slug="bob"),
|
||||||
|
])
|
||||||
|
await db.flush()
|
||||||
|
svc = ArtistService(db)
|
||||||
|
rows = await svc.autocomplete("alice")
|
||||||
|
names = [r.name for r in rows]
|
||||||
|
assert names[0] == "Alice" # exact first
|
||||||
|
assert names[1] == "Alice Cooper" # then prefix
|
||||||
|
assert "Malice" in names # then substring
|
||||||
|
assert "Bob" not in names
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_autocomplete_empty_query_returns_empty(db):
|
||||||
|
svc = ArtistService(db)
|
||||||
|
assert await svc.autocomplete("") == []
|
||||||
Reference in New Issue
Block a user