[refactor] postgres-init,solution: DB 구조 재편 — 스키마 해체 · 공용 콘텐츠 한 벌 · 마이그레이션 체계
도메인별 스키마(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>
This commit is contained in:
1 parent
7bbeb068a8
commit
64ce467f21
189 files changed
+13374
-5023
No files matched your search
@@ -5,7 +5,7 @@ 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 facts
|
||||
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
|
||||
@@ -21,17 +21,17 @@ _ACTIVE = _PUBLISHED + _CANDIDATE
|
||||
|
||||
def _unit_cond(unit_id):
|
||||
"""unit_id 는 NULL 비교라 == 로 걸면 안 된다(사업장 단위 fact 를 못 찾는다)."""
|
||||
return facts.unit_id.is_(None) if unit_id is None else facts.unit_id == unit_id
|
||||
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: facts) -> ErrorType:
|
||||
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, facts]:
|
||||
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, place_facts]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -39,11 +39,11 @@ class IFactCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, facts]:
|
||||
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, facts]:
|
||||
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, place_facts]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -68,18 +68,18 @@ class IFactCRUD(ABC):
|
||||
|
||||
|
||||
class FactCRUD(IFactCRUD):
|
||||
async def add_fact(self, cdb: AsyncSession, fact: facts) -> ErrorType:
|
||||
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, facts]:
|
||||
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, place_facts]:
|
||||
try:
|
||||
query = (
|
||||
select(facts)
|
||||
.where(facts.fact_id == fact_id, facts.place_id == place_id, facts.deleted == False) # noqa: E712
|
||||
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)
|
||||
@@ -101,19 +101,19 @@ class FactCRUD(IFactCRUD):
|
||||
active_only=True → REJECTED·EXPIRED 이력 제외 (관리 화면 기본: 노출값 + 후보)
|
||||
"""
|
||||
try:
|
||||
conditions = [facts.place_id == place_id, facts.deleted == False] # noqa: E712
|
||||
conditions = [place_facts.place_id == place_id, place_facts.deleted == False] # noqa: E712
|
||||
if unit_id is not None:
|
||||
conditions.append(facts.unit_id == unit_id)
|
||||
conditions.append(place_facts.unit_id == unit_id)
|
||||
if publishable_only:
|
||||
conditions.append(facts.status.in_(_PUBLISHED))
|
||||
conditions.append(place_facts.status.in_(_PUBLISHED))
|
||||
elif status is not None:
|
||||
conditions.append(facts.status == status)
|
||||
conditions.append(place_facts.status == status)
|
||||
elif active_only:
|
||||
conditions.append(facts.status.in_(_ACTIVE))
|
||||
conditions.append(place_facts.status.in_(_ACTIVE))
|
||||
|
||||
# 노출값이 먼저, 그 아래 후보. 같은 key 끼리 붙어 보이게 정렬한다.
|
||||
query = select(facts).where(and_(*conditions)).order_by(
|
||||
facts.key.asc(), facts.status.desc(), facts.collected_at.desc()
|
||||
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 [])
|
||||
@@ -121,17 +121,17 @@ class FactCRUD(IFactCRUD):
|
||||
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, facts]:
|
||||
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(facts)
|
||||
select(place_facts)
|
||||
.where(and_(
|
||||
facts.place_id == place_id,
|
||||
facts.key == key,
|
||||
facts.deleted == False, # noqa: E712
|
||||
facts.status.in_(_PUBLISHED),
|
||||
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)
|
||||
@@ -144,20 +144,20 @@ class FactCRUD(IFactCRUD):
|
||||
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, facts]:
|
||||
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, place_facts]:
|
||||
"""같은 출처가 이미 올려둔 후보. 재수집이 같은 후보를 계속 쌓지 않도록 갱신 대상을 찾는다."""
|
||||
try:
|
||||
query = (
|
||||
select(facts)
|
||||
select(place_facts)
|
||||
.where(and_(
|
||||
facts.place_id == place_id,
|
||||
facts.key == key,
|
||||
facts.source_type == source_type,
|
||||
facts.deleted == False, # noqa: E712
|
||||
facts.status.in_(_CANDIDATE),
|
||||
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(facts.collected_at.desc())
|
||||
.order_by(place_facts.collected_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
||||
@@ -176,7 +176,7 @@ class FactCRUD(IFactCRUD):
|
||||
values = {"collected_at": ts, "updated_at": ts}
|
||||
if source_url:
|
||||
values["source_url"] = source_url
|
||||
query = update(facts).where(facts.fact_id == fact_id, facts.deleted == False).values(**values) # noqa: E712
|
||||
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)
|
||||
@@ -186,8 +186,8 @@ class FactCRUD(IFactCRUD):
|
||||
"""기존 후보를 새 수집값으로 갱신. 같은 출처의 후보가 계속 쌓이는 것을 막는다."""
|
||||
try:
|
||||
query = (
|
||||
update(facts)
|
||||
.where(facts.fact_id == fact_id, facts.status.in_(_CANDIDATE), facts.deleted == False) # noqa: E712
|
||||
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)
|
||||
@@ -202,11 +202,11 @@ class FactCRUD(IFactCRUD):
|
||||
허용 전이 판정 자체는 service 가 FACT_STATUS_TRANSITIONS 로 먼저 한다."""
|
||||
try:
|
||||
query = (
|
||||
update(facts)
|
||||
update(place_facts)
|
||||
.where(
|
||||
facts.fact_id == fact_id,
|
||||
facts.status.in_(tuple(from_statuses)),
|
||||
facts.deleted == False, # noqa: E712
|
||||
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)
|
||||
)
|
||||
@@ -221,15 +221,15 @@ class FactCRUD(IFactCRUD):
|
||||
지우지 않고 이력으로 남긴다 — 예전에 뭐가 나갔는지 추적할 수 있어야 한다."""
|
||||
try:
|
||||
conditions = [
|
||||
facts.place_id == place_id,
|
||||
facts.key == key,
|
||||
facts.deleted == False, # noqa: E712
|
||||
facts.status.in_(_PUBLISHED),
|
||||
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(facts.fact_id != except_fact_id)
|
||||
query = update(facts).where(and_(*conditions)).values(status=FactStatus.EXPIRED.value, updated_at=ts)
|
||||
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)
|
||||
@@ -241,15 +241,15 @@ class FactCRUD(IFactCRUD):
|
||||
후보를 그대로 두면 사람 확인 큐에 이미 처리된 항목이 계속 남는다."""
|
||||
try:
|
||||
conditions = [
|
||||
facts.place_id == place_id,
|
||||
facts.key == key,
|
||||
facts.deleted == False, # noqa: E712
|
||||
facts.status.in_(_CANDIDATE),
|
||||
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(facts.fact_id != except_fact_id)
|
||||
query = update(facts).where(and_(*conditions)).values(status=FactStatus.REJECTED.value, updated_at=ts)
|
||||
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)
|
||||
|
||||
Reference in new issue
Block a user