도메인별 스키마(company·place·fact·local·site·job)를 걷어내고 public 한 벌로 폈다.
스키마 한정자가 붙은 순간부터 ORM·raw SQL·테스트 픽스처가 각자 그 이름을 들고 다녀야 했다.
- 공용 콘텐츠를 한 테이블로 되돌린다. spots·region_stories 를 따로 파 놓고 보니
같은 성격이 세 곳으로 갈라져 있었다 — `area_contents` 가 처음부터 content_type 으로
종류를 가르는 설계였고 그걸 쓰면 됐다. 관계(거리·숨김)만 `place_area_refs` 로 남긴다.
- migrations/ + scripts/migrate.py: `init.sql` 은 **DB 를 처음 만들 때만** 돈다. 파일에
컬럼을 더해도 이미 데이터가 든 DB 에는 반영되지 않는다 — 실제로 TourAPI 가 주변 정보를
받아 와도 저장할 곳이 없어 축제·맛집이 0건이었고, 화면에는 "그냥 안 나오는 것" 으로만 보였다.
DECISIONS.md 가 예고한 그대로다("운영 DB 가 생기는 순간 다시 필요해진다").
Alembic 을 쓰지 않는 이유는 스키마 정의가 이미 두 곳(ORM·init.sql)이라 세 번째를
더하면 어긋날 자리가 하나 더 생기기 때문이다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
257 lines
12 KiB
Python
257 lines
12 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Optional, Tuple
|
|
|
|
from sqlalchemy import and_, select, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import place_facts
|
|
from common.enums import ErrorType, FactStatus
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
# ★ 사이트에 나가는 상태. PUBLISHABLE_FACT_STATUSES 와 같은 집합이어야 한다.
|
|
# 유니크 인덱스(uq_facts_published_*)의 조건과도 같아야 한다.
|
|
_PUBLISHED = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value)
|
|
# 후보 — 재수집이 올려놓은 확인 대기 항목. 여러 건 공존한다.
|
|
_CANDIDATE = (FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value)
|
|
# 화면에 보이는 것 전체(이력 제외).
|
|
_ACTIVE = _PUBLISHED + _CANDIDATE
|
|
|
|
|
|
def _unit_cond(unit_id):
|
|
"""unit_id 는 NULL 비교라 == 로 걸면 안 된다(사업장 단위 fact 를 못 찾는다)."""
|
|
return place_facts.unit_id.is_(None) if unit_id is None else place_facts.unit_id == unit_id
|
|
|
|
|
|
# fact CRUD. 항상 place_id 로 스코프한다.
|
|
class IFactCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_fact(self, cdb: AsyncSession, fact: place_facts) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, place_facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_facts(self, cdb: AsyncSession, place_id, unit_id, status, publishable_only, active_only) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, place_facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, place_facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status, ts) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status, data: dict) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
|
|
class FactCRUD(IFactCRUD):
|
|
async def add_fact(self, cdb: AsyncSession, fact: place_facts) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, fact)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, place_facts]:
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(place_facts.fact_id == fact_id, place_facts.place_id == place_id, place_facts.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def list_facts(
|
|
self, cdb: AsyncSession, place_id, unit_id=None, status: Optional[int] = None,
|
|
publishable_only: bool = False, active_only: bool = True,
|
|
) -> Tuple[ErrorType, list]:
|
|
"""fact 목록.
|
|
publishable_only=True → ★ VERIFIED·CORRECTED 만 (사이트 렌더·발행 게이트가 쓰는 경로)
|
|
active_only=True → REJECTED·EXPIRED 이력 제외 (관리 화면 기본: 노출값 + 후보)
|
|
"""
|
|
try:
|
|
conditions = [place_facts.place_id == place_id, place_facts.deleted == False] # noqa: E712
|
|
if unit_id is not None:
|
|
conditions.append(place_facts.unit_id == unit_id)
|
|
if publishable_only:
|
|
conditions.append(place_facts.status.in_(_PUBLISHED))
|
|
elif status is not None:
|
|
conditions.append(place_facts.status == status)
|
|
elif active_only:
|
|
conditions.append(place_facts.status.in_(_ACTIVE))
|
|
|
|
# 노출값이 먼저, 그 아래 후보. 같은 key 끼리 붙어 보이게 정렬한다.
|
|
query = select(place_facts).where(and_(*conditions)).order_by(
|
|
place_facts.key.asc(), place_facts.status.desc(), place_facts.collected_at.desc()
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
return (err_type, list(rows) if err_type == ErrorType.SUCCESS else [])
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, []
|
|
|
|
async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, place_facts]:
|
|
"""★ 지금 사이트에 나가고 있는 값. 없으면 (SUCCESS, None).
|
|
유니크 인덱스가 1건만 허용하므로 결과는 0 또는 1건이다."""
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(and_(
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_PUBLISHED),
|
|
_unit_cond(unit_id),
|
|
))
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
return ErrorType.SUCCESS, (row_list[0] if row_list else None)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, place_facts]:
|
|
"""같은 출처가 이미 올려둔 후보. 재수집이 같은 후보를 계속 쌓지 않도록 갱신 대상을 찾는다."""
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(and_(
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.source_type == source_type,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
))
|
|
.order_by(place_facts.collected_at.desc())
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
return ErrorType.SUCCESS, (row_list[0] if row_list else None)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]:
|
|
"""★ 재수집했는데 값이 그대로일 때 — 검증 상태를 건드리지 않고 '언제 다시 확인했는지'만 갱신한다.
|
|
|
|
이게 없으면 값이 안 바뀌었는데도 재수집마다 검증이 초기화돼 사이트에서 사실이 사라진다."""
|
|
try:
|
|
values = {"collected_at": ts, "updated_at": ts}
|
|
if source_url:
|
|
values["source_url"] = source_url
|
|
query = update(place_facts).where(place_facts.fact_id == fact_id, place_facts.deleted == False).values(**values) # noqa: E712
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status: int, ts) -> Tuple[ErrorType, int]:
|
|
"""기존 후보를 새 수집값으로 갱신. 같은 출처의 후보가 계속 쌓이는 것을 막는다."""
|
|
try:
|
|
query = (
|
|
update(place_facts)
|
|
.where(place_facts.fact_id == fact_id, place_facts.status.in_(_CANDIDATE), place_facts.deleted == False) # noqa: E712
|
|
.values(value=value, source_url=source_url, status=status, collected_at=ts, updated_at=ts)
|
|
)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status: int, data: dict) -> Tuple[ErrorType, int]:
|
|
"""검증 상태 전이 — **출발 상태를 WHERE 에 걸어** 조건부로만 바꾼다.
|
|
|
|
적용행수 0 = 그 사이 다른 사람이 이미 상태를 바꿨다는 뜻(동시 처리 가드).
|
|
허용 전이 판정 자체는 service 가 FACT_STATUS_TRANSITIONS 로 먼저 한다."""
|
|
try:
|
|
query = (
|
|
update(place_facts)
|
|
.where(
|
|
place_facts.fact_id == fact_id,
|
|
place_facts.status.in_(tuple(from_statuses)),
|
|
place_facts.deleted == False, # noqa: E712
|
|
)
|
|
.values(status=to_status, updated_at=GTime.UTC(), **data)
|
|
)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
"""현재 노출값을 EXPIRED 로 내려 자리를 비운다(후보 승격·직접 교체 직전에 호출).
|
|
|
|
지우지 않고 이력으로 남긴다 — 예전에 뭐가 나갔는지 추적할 수 있어야 한다."""
|
|
try:
|
|
conditions = [
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_PUBLISHED),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(place_facts.fact_id != except_fact_id)
|
|
query = update(place_facts).where(and_(*conditions)).values(status=FactStatus.EXPIRED.value, updated_at=ts)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
"""남은 후보를 REJECTED 로 정리한다(하나를 승격시켰으니 나머지는 판정된 셈).
|
|
|
|
후보를 그대로 두면 사람 확인 큐에 이미 처리된 항목이 계속 남는다."""
|
|
try:
|
|
conditions = [
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(place_facts.fact_id != except_fact_id)
|
|
query = update(place_facts).where(and_(*conditions)).values(status=FactStatus.REJECTED.value, updated_at=ts)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|