[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)
|
||||
|
||||
@@ -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 faqs
|
||||
from common.database.model.models import place_faqs
|
||||
from common.enums import ErrorType, FactStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -21,7 +21,7 @@ class IFaqCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_faq(self, cdb: AsyncSession, faq: faqs) -> ErrorType:
|
||||
async def add_faq(self, cdb: AsyncSession, faq: place_faqs) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -33,26 +33,26 @@ class IFaqCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, faqs]:
|
||||
async def get_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, place_faqs]:
|
||||
pass
|
||||
|
||||
|
||||
class FaqCRUD(IFaqCRUD):
|
||||
async def list_faqs(self, cdb: AsyncSession, place_id, publishable_only: bool = False) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
conds = [faqs.place_id == place_id, faqs.deleted == False] # noqa: E712
|
||||
conds.append(faqs.status.in_(_PUBLISHABLE if publishable_only else _ACTIVE))
|
||||
query = select(faqs).where(and_(*conds)).order_by(faqs.sort_order.asc(), faqs.created_at.asc())
|
||||
conds = [place_faqs.place_id == place_id, place_faqs.deleted == False] # noqa: E712
|
||||
conds.append(place_faqs.status.in_(_PUBLISHABLE if publishable_only else _ACTIVE))
|
||||
query = select(place_faqs).where(and_(*conds)).order_by(place_faqs.sort_order.asc(), place_faqs.created_at.asc())
|
||||
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_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, faqs]:
|
||||
async def get_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, place_faqs]:
|
||||
try:
|
||||
query = select(faqs).where(
|
||||
faqs.faq_id == faq_id, faqs.place_id == place_id, faqs.deleted == False # noqa: E712
|
||||
query = select(place_faqs).where(
|
||||
place_faqs.faq_id == faq_id, place_faqs.place_id == place_id, place_faqs.deleted == False # noqa: E712
|
||||
).limit(1)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
@@ -64,7 +64,7 @@ class FaqCRUD(IFaqCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def add_faq(self, cdb: AsyncSession, faq: faqs) -> ErrorType:
|
||||
async def add_faq(self, cdb: AsyncSession, faq: place_faqs) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, faq)
|
||||
except Exception as ex:
|
||||
@@ -78,11 +78,11 @@ class FaqCRUD(IFaqCRUD):
|
||||
재생성이 사람의 판단을 덮어쓰면 fact 쪽 규칙과 어긋난다."""
|
||||
try:
|
||||
query = (
|
||||
update(faqs)
|
||||
update(place_faqs)
|
||||
.where(
|
||||
faqs.place_id == place_id,
|
||||
faqs.deleted == False, # noqa: E712
|
||||
faqs.status.in_((FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value)),
|
||||
place_faqs.place_id == place_id,
|
||||
place_faqs.deleted == False, # noqa: E712
|
||||
place_faqs.status.in_((FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value)),
|
||||
)
|
||||
.values(status=FactStatus.EXPIRED.value, updated_at=ts)
|
||||
)
|
||||
@@ -94,8 +94,8 @@ class FaqCRUD(IFaqCRUD):
|
||||
async def transition(self, cdb: AsyncSession, faq_id, from_statuses, to_status: int, data: dict) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
query = (
|
||||
update(faqs)
|
||||
.where(faqs.faq_id == faq_id, faqs.status.in_(tuple(from_statuses)), faqs.deleted == False) # noqa: E712
|
||||
update(place_faqs)
|
||||
.where(place_faqs.faq_id == faq_id, place_faqs.status.in_(tuple(from_statuses)), place_faqs.deleted == False) # noqa: E712
|
||||
.values(status=to_status, updated_at=GTime.UTC(), **data)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
|
||||
@@ -2,73 +2,97 @@ from sqlalchemy import and_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import local_contents
|
||||
from common.database.model.models import area_contents
|
||||
from common.enums import ErrorType, LocalContentType
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
class LocalContentCRUD:
|
||||
async def list(self, db, status: int | None = None, region_code: str | None = None):
|
||||
conds = [local_contents.deleted == False, local_contents.content_type == LocalContentType.FESTIVAL.value] # noqa: E712
|
||||
"""축제·관광지·맛집·날씨 전 종류. ★ 예전엔 FESTIVAL 로 고정돼 있어 sync_region 이 받은
|
||||
관광지·맛집이 이 목록에 영영 안 보였다(admin 화면이 축제만 검수/발행하는 줄 알게 됨)."""
|
||||
conds = [area_contents.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
conds.append(local_contents.status == status)
|
||||
conds.append(area_contents.status == status)
|
||||
if region_code:
|
||||
conds.append(local_contents.region_code == region_code)
|
||||
conds.append(area_contents.region_code == region_code)
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db, select(local_contents).where(and_(*conds)).order_by(local_contents.collected_at.desc())
|
||||
db, select(area_contents).where(and_(*conds)).order_by(area_contents.collected_at.desc())
|
||||
)
|
||||
|
||||
async def insert(self, db, row):
|
||||
return await DB_SESSION_MNG.insert(db, row)
|
||||
|
||||
async def get_by_external_id(self, db, region_code: str, external_id: str):
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(local_contents).where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.content_type == LocalContentType.FESTIVAL.value,
|
||||
local_contents.external_id == external_id,
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
).limit(1),
|
||||
)
|
||||
return err, rows[0] if rows else None
|
||||
|
||||
async def publish(self, db, ids: list, user_id):
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(local_contents).where(
|
||||
local_contents.local_content_id.in_(ids), local_contents.deleted == False # noqa: E712
|
||||
update(area_contents).where(
|
||||
area_contents.local_content_id.in_(ids), area_contents.deleted == False # noqa: E712
|
||||
).values(status=2, published_at=GTime.UTC(), published_by=user_id, updated_at=GTime.UTC()),
|
||||
)
|
||||
|
||||
async def update(self, db, content_id, data: dict):
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(local_contents).where(
|
||||
local_contents.local_content_id == content_id, local_contents.deleted == False # noqa: E712
|
||||
update(area_contents).where(
|
||||
area_contents.local_content_id == content_id, area_contents.deleted == False # noqa: E712
|
||||
).values(**data, updated_at=GTime.UTC()),
|
||||
)
|
||||
|
||||
async def end(self, db, content_id):
|
||||
return await self.update(db, content_id, {"status": 3})
|
||||
|
||||
async def list_keyed(self, db, region_code: str, content_type: int):
|
||||
"""지역 × 종류의 외부 ID 있는 행 전부(축제·관광지·맛집). 동기화가 기존값과 비교할 때 쓴다."""
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(area_contents).where(
|
||||
area_contents.region_code == region_code,
|
||||
area_contents.content_type == content_type,
|
||||
area_contents.external_id.isnot(None),
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
),
|
||||
)
|
||||
|
||||
async def upsert_keyed(self, db, values: dict):
|
||||
"""외부 ID 로 식별되는 행(축제·관광지·맛집)의 삽입/갱신.
|
||||
|
||||
★ uq_local_contents_keyed 부분 유니크 인덱스에 태운다 — 같은 지역을 두 번 동기화해도
|
||||
중복 행이 생기지 않고 기존 값만 갱신된다."""
|
||||
stmt = pg_insert(area_contents).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[area_contents.region_code, area_contents.content_type, area_contents.external_id],
|
||||
index_where=and_(area_contents.deleted == False, area_contents.external_id.isnot(None)), # noqa: E712
|
||||
set_={
|
||||
"title": stmt.excluded.title,
|
||||
"body": stmt.excluded.body,
|
||||
"source": stmt.excluded.source,
|
||||
"status": stmt.excluded.status,
|
||||
"collected_at": stmt.excluded.collected_at,
|
||||
"display_end_at": stmt.excluded.display_end_at,
|
||||
"published_at": stmt.excluded.published_at,
|
||||
"updated_at": GTime.UTC(),
|
||||
},
|
||||
)
|
||||
return await DB_SESSION_MNG.add(db, stmt)
|
||||
|
||||
async def get_weather(self, db, region_code: str):
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(local_contents).where(
|
||||
local_contents.region_code == region_code,
|
||||
local_contents.content_type == LocalContentType.WEATHER.value,
|
||||
local_contents.external_id.is_(None),
|
||||
local_contents.deleted == False, # noqa: E712
|
||||
select(area_contents).where(
|
||||
area_contents.region_code == region_code,
|
||||
area_contents.content_type == LocalContentType.WEATHER.value,
|
||||
area_contents.external_id.is_(None),
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
).limit(1),
|
||||
)
|
||||
return err, rows[0] if rows else None
|
||||
|
||||
async def upsert_weather(self, db, values: dict):
|
||||
stmt = pg_insert(local_contents).values(**values)
|
||||
stmt = pg_insert(area_contents).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[local_contents.region_code, local_contents.content_type],
|
||||
index_where=and_(local_contents.deleted == False, local_contents.external_id.is_(None)), # noqa: E712
|
||||
index_elements=[area_contents.region_code, area_contents.content_type],
|
||||
index_where=and_(area_contents.deleted == False, area_contents.external_id.is_(None)), # noqa: E712
|
||||
set_={
|
||||
"source": stmt.excluded.source,
|
||||
"body": stmt.excluded.body,
|
||||
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy import and_, func, or_, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import media
|
||||
from common.database.model.models import place_photos
|
||||
from common.enums import ErrorType, MediaStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -45,20 +45,20 @@ class MediaCRUD(IMediaCRUD):
|
||||
★ alt_required=True 는 status 필터와 짝으로만 쓴다 — alt 가 빈 사진은 빌더가 렌더하지
|
||||
않으므로(services/snapshot.py), '발행되면 실릴 것'을 물었을 때 승인만 보면 답이 틀린다."""
|
||||
try:
|
||||
conditions = [media.place_id == place_id, media.deleted == False] # noqa: E712
|
||||
conditions = [place_photos.place_id == place_id, place_photos.deleted == False] # noqa: E712
|
||||
if status is not None:
|
||||
conditions.append(media.status == status)
|
||||
conditions.append(place_photos.status == status)
|
||||
if unlabeled_only:
|
||||
conditions.append(
|
||||
or_(media.alt_text.is_(None), func.btrim(media.alt_text) == "")
|
||||
or_(place_photos.alt_text.is_(None), func.btrim(place_photos.alt_text) == "")
|
||||
)
|
||||
if unit_id is not None:
|
||||
conditions.append(media.unit_id == unit_id)
|
||||
conditions.append(place_photos.unit_id == unit_id)
|
||||
if alt_required:
|
||||
# 공백만 있는 alt 도 빌더에선 '없음'이다 — 같은 기준으로 거른다.
|
||||
conditions.append(media.alt_text.is_not(None))
|
||||
conditions.append(func.btrim(media.alt_text) != "")
|
||||
query = select(media).where(and_(*conditions)).order_by(media.sort_order.asc(), media.created_at.asc())
|
||||
conditions.append(place_photos.alt_text.is_not(None))
|
||||
conditions.append(func.btrim(place_photos.alt_text) != "")
|
||||
query = select(place_photos).where(and_(*conditions)).order_by(place_photos.sort_order.asc(), place_photos.created_at.asc())
|
||||
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:
|
||||
@@ -72,8 +72,8 @@ class MediaCRUD(IMediaCRUD):
|
||||
라벨·alt 는 저장하되(사람이 보고 고칠 재료), 승인 상태로 올리지 않는 게 핵심이다."""
|
||||
try:
|
||||
query = (
|
||||
update(media)
|
||||
.where(media.media_id == media_id, media.deleted == False) # noqa: E712
|
||||
update(place_photos)
|
||||
.where(place_photos.media_id == media_id, place_photos.deleted == False) # noqa: E712
|
||||
.values(label=label, alt_text=alt_text, vision_confidence=confidence, status=status, updated_at=ts)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
@@ -85,8 +85,8 @@ class MediaCRUD(IMediaCRUD):
|
||||
"""사람이 사진을 승인/반려한다."""
|
||||
try:
|
||||
query = (
|
||||
update(media)
|
||||
.where(media.media_id == media_id, media.place_id == place_id, media.deleted == False) # noqa: E712
|
||||
update(place_photos)
|
||||
.where(place_photos.media_id == media_id, place_photos.place_id == place_id, place_photos.deleted == False) # noqa: E712
|
||||
.values(status=status, updated_at=ts)
|
||||
)
|
||||
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
from sqlalchemy import and_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import area_contents, place_area_refs
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
class PlaceContentCRUD:
|
||||
"""업장 주변의 지역 콘텐츠.
|
||||
|
||||
★ 실체와 관계가 갈려 있다 (2026-09-09).
|
||||
예전에는 한 테이블이 값을 통째로 들고 있었고 키가 place_id 라, 업장마다 TourAPI
|
||||
응답이 복제됐다 — 실측 조이모텔 한 곳에 144행이고 같은 축제가 업장 수만큼 늘었다.
|
||||
지금은 실체가 `area_contents` 에 한 행(전국 공용, external_id 로 유일)이고
|
||||
`place_area_refs` 에는 그 업장에서만 다른 것 — 거리와 숨김 — 만 남는다.
|
||||
그래서 읽을 때 조인이 하나 는다. 그 값으로 복제를 없앴다.
|
||||
"""
|
||||
|
||||
async def list_by_place(self, db, place_id, *, include_hidden: bool = True):
|
||||
"""이 업장 주변의 콘텐츠. 실체(area_contents)와 거리(place_area_refs)를 함께 준다."""
|
||||
conds = [
|
||||
place_area_refs.place_id == place_id,
|
||||
place_area_refs.deleted == False, # noqa: E712
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
]
|
||||
if not include_hidden:
|
||||
conds.append(place_area_refs.hidden == False) # noqa: E712
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(
|
||||
area_contents.local_content_id,
|
||||
area_contents.content_type,
|
||||
area_contents.external_id,
|
||||
area_contents.title,
|
||||
area_contents.body,
|
||||
area_contents.latitude,
|
||||
area_contents.longitude,
|
||||
area_contents.display_end_at,
|
||||
# ★ 이름을 옛 컬럼과 맞춘다 — 읽는 쪽(snapshot)이 행을 그대로 쓰던 모양이다.
|
||||
place_area_refs.distance_m.label("distance_m"),
|
||||
place_area_refs.hidden.label("hidden"),
|
||||
)
|
||||
.join(area_contents, area_contents.local_content_id == place_area_refs.local_content_id)
|
||||
.where(and_(*conds))
|
||||
.order_by(
|
||||
area_contents.content_type.asc(),
|
||||
place_area_refs.distance_m.asc(),
|
||||
),
|
||||
)
|
||||
|
||||
async def upsert_content(self, db, values: dict):
|
||||
"""공용 콘텐츠 한 건. (source, external_id) 가 같으면 갱신한다 — 지역과 무관하게 한 벌이다.
|
||||
|
||||
★ RETURNING 을 쓰지 않는다. 세션 매니저의 execute 는 SELECT 만 받고
|
||||
("DO NOT USE NON-SELECT QUERY IN DBJOB"), 쓰기는 add 로 간다. id 는 뒤이어 조회한다.
|
||||
"""
|
||||
stmt = pg_insert(area_contents).values(**values)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[area_contents.source, area_contents.external_id],
|
||||
index_where=and_(
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
area_contents.external_id.isnot(None),
|
||||
),
|
||||
set_={
|
||||
"title": stmt.excluded.title,
|
||||
"body": stmt.excluded.body,
|
||||
"latitude": stmt.excluded.latitude,
|
||||
"longitude": stmt.excluded.longitude,
|
||||
"region_code": stmt.excluded.region_code,
|
||||
"display_end_at": stmt.excluded.display_end_at,
|
||||
"collected_at": stmt.excluded.collected_at,
|
||||
"updated_at": GTime.UTC(),
|
||||
},
|
||||
)
|
||||
return await DB_SESSION_MNG.add(db, stmt)
|
||||
|
||||
async def find_content_id(self, db, source: int, external_id: str):
|
||||
"""방금 upsert 한 공용 콘텐츠의 id."""
|
||||
return await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(area_contents.local_content_id).where(
|
||||
area_contents.source == source,
|
||||
area_contents.external_id == external_id,
|
||||
area_contents.deleted == False, # noqa: E712
|
||||
).limit(1),
|
||||
)
|
||||
|
||||
async def upsert_ref(self, db, place_id, local_content_id, distance_m):
|
||||
"""업장 ↔ 콘텐츠 관계. ★ hidden 은 건드리지 않는다 — 운영자가 숨긴 것을 재수집이 되살리면 안 된다."""
|
||||
stmt = pg_insert(place_area_refs).values(
|
||||
place_id=place_id, local_content_id=local_content_id, distance_m=distance_m, deleted=False,
|
||||
)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=[place_area_refs.place_id, place_area_refs.local_content_id],
|
||||
set_={"distance_m": stmt.excluded.distance_m, "deleted": False, "updated_at": GTime.UTC()},
|
||||
)
|
||||
return await DB_SESSION_MNG.add(db, stmt)
|
||||
|
||||
async def soft_delete_missing(self, db, place_id, keep_ids: set):
|
||||
"""이번 응답에 없는 **관계**를 끊는다. 실체(area_contents)는 지우지 않는다 —
|
||||
다른 업장이 같은 장소를 가리키고 있을 수 있다."""
|
||||
err, rows = await DB_SESSION_MNG.execute(
|
||||
db,
|
||||
select(place_area_refs.local_content_id).where(
|
||||
place_area_refs.place_id == place_id,
|
||||
place_area_refs.deleted == False, # noqa: E712
|
||||
),
|
||||
)
|
||||
# 단일 컬럼 SELECT 라 행이 스칼라로 온다.
|
||||
# ★ 단일 컬럼 SELECT 는 세션 매니저가 scalars() 로 편다 — 행이 곧 값이다.
|
||||
gone = [r for r in (rows or []) if r not in keep_ids]
|
||||
if not gone:
|
||||
return err, 0
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(place_area_refs)
|
||||
.where(place_area_refs.place_id == place_id, place_area_refs.local_content_id.in_(gone))
|
||||
.values(deleted=True, updated_at=GTime.UTC()),
|
||||
)
|
||||
|
||||
async def set_hidden(self, db, place_id, local_content_id, hidden: bool):
|
||||
"""이 업장에서만 숨긴다. 실체는 그대로라 다른 업장에는 계속 보인다."""
|
||||
return await DB_SESSION_MNG.add_with_rowcount(
|
||||
db,
|
||||
update(place_area_refs)
|
||||
.where(
|
||||
place_area_refs.place_id == place_id,
|
||||
place_area_refs.local_content_id == local_content_id,
|
||||
place_area_refs.deleted == False, # noqa: E712
|
||||
)
|
||||
.values(hidden=hidden, updated_at=GTime.UTC()),
|
||||
)
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy import and_, delete, func, or_, 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_links, places, units
|
||||
from common.database.model.models import place_channels, places, place_units
|
||||
from common.enums import ErrorType
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -38,11 +38,11 @@ class IPlaceCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, units]:
|
||||
async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, place_units]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_unit(self, cdb: AsyncSession, unit: units) -> ErrorType:
|
||||
async def add_unit(self, cdb: AsyncSession, unit: place_units) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -50,7 +50,7 @@ class IPlaceCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_link(self, cdb: AsyncSession, link: place_links) -> ErrorType:
|
||||
async def add_link(self, cdb: AsyncSession, link: place_channels) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -156,9 +156,9 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
async def list_units(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
query = (
|
||||
select(units)
|
||||
.where(units.place_id == place_id, units.deleted == False) # noqa: E712
|
||||
.order_by(units.sort_order.asc(), units.created_at.asc())
|
||||
select(place_units)
|
||||
.where(place_units.place_id == place_id, place_units.deleted == False) # noqa: E712
|
||||
.order_by(place_units.sort_order.asc(), place_units.created_at.asc())
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
return (err_type, list(rows) if err_type == ErrorType.SUCCESS else [])
|
||||
@@ -166,11 +166,11 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, units]:
|
||||
async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, place_units]:
|
||||
try:
|
||||
query = (
|
||||
select(units)
|
||||
.where(units.unit_id == unit_id, units.place_id == place_id, units.deleted == False) # noqa: E712
|
||||
select(place_units)
|
||||
.where(place_units.unit_id == unit_id, place_units.place_id == place_id, place_units.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
||||
@@ -183,7 +183,7 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def add_unit(self, cdb: AsyncSession, unit: units) -> ErrorType:
|
||||
async def add_unit(self, cdb: AsyncSession, unit: place_units) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, unit)
|
||||
except Exception as ex:
|
||||
@@ -193,17 +193,17 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
async def list_links(self, cdb: AsyncSession, place_id, confirmed_only: bool = False) -> Tuple[ErrorType, list]:
|
||||
"""채널 URL 목록. confirmed_only=True 면 ★ 크롤링 대상(확정된 URL)만."""
|
||||
try:
|
||||
conditions = [place_links.place_id == place_id, place_links.deleted == False] # noqa: E712
|
||||
conditions = [place_channels.place_id == place_id, place_channels.deleted == False] # noqa: E712
|
||||
if confirmed_only:
|
||||
conditions.append(place_links.confirmed_at.is_not(None))
|
||||
query = select(place_links).where(and_(*conditions)).order_by(place_links.discovered_at.asc())
|
||||
conditions.append(place_channels.confirmed_at.is_not(None))
|
||||
query = select(place_channels).where(and_(*conditions)).order_by(place_channels.discovered_at.asc())
|
||||
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 add_link(self, cdb: AsyncSession, link: place_links) -> ErrorType:
|
||||
async def add_link(self, cdb: AsyncSession, link: place_channels) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, link)
|
||||
except Exception as ex:
|
||||
@@ -218,12 +218,12 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
경로를 늘리지 않으려고 일부러 좁게 열어 둔다(collect_service.discover_naver_place)."""
|
||||
try:
|
||||
query = (
|
||||
update(place_links)
|
||||
update(place_channels)
|
||||
.where(
|
||||
place_links.place_id == place_id,
|
||||
place_links.url == url,
|
||||
place_links.confirmed_at.is_(None),
|
||||
place_links.deleted == False, # noqa: E712
|
||||
place_channels.place_id == place_id,
|
||||
place_channels.url == url,
|
||||
place_channels.confirmed_at.is_(None),
|
||||
place_channels.deleted == False, # noqa: E712
|
||||
)
|
||||
.values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts)
|
||||
)
|
||||
@@ -246,11 +246,11 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
생성 시점에만 근거로 넘긴다(services/copy_service.py)."""
|
||||
try:
|
||||
query = (
|
||||
update(place_links)
|
||||
update(place_channels)
|
||||
.where(
|
||||
place_links.place_id == place_id,
|
||||
place_links.url == url,
|
||||
place_links.deleted == False, # noqa: E712
|
||||
place_channels.place_id == place_id,
|
||||
place_channels.url == url,
|
||||
place_channels.deleted == False, # noqa: E712
|
||||
)
|
||||
.values(raw=raw, updated_at=GTime.UTC())
|
||||
)
|
||||
@@ -263,12 +263,12 @@ class PlaceCRUD(IPlaceCRUD):
|
||||
"""미확정 링크만 확정한다(이미 확정된 건 rowcount 0 — 동시 처리 가드)."""
|
||||
try:
|
||||
query = (
|
||||
update(place_links)
|
||||
update(place_channels)
|
||||
.where(
|
||||
place_links.link_id == link_id,
|
||||
place_links.place_id == place_id,
|
||||
place_links.confirmed_at.is_(None),
|
||||
place_links.deleted == False, # noqa: E712
|
||||
place_channels.link_id == link_id,
|
||||
place_channels.place_id == place_id,
|
||||
place_channels.confirmed_at.is_(None),
|
||||
place_channels.deleted == False, # noqa: E712
|
||||
)
|
||||
.values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts)
|
||||
)
|
||||
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy import and_, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, publish_logs, site_versions, sites
|
||||
from common.database.model.models import places, site_publish_logs, site_versions, sites
|
||||
from common.enums import BuildStatus, ErrorType, SiteStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
@@ -54,7 +54,7 @@ class ISiteCRUD(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_log(self, cdb: AsyncSession, log: publish_logs) -> ErrorType:
|
||||
async def add_log(self, cdb: AsyncSession, log: site_publish_logs) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -214,7 +214,7 @@ class SiteCRUD(ISiteCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def add_log(self, cdb: AsyncSession, log: publish_logs) -> ErrorType:
|
||||
async def add_log(self, cdb: AsyncSession, log: site_publish_logs) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, log)
|
||||
except Exception as ex:
|
||||
@@ -224,9 +224,9 @@ class SiteCRUD(ISiteCRUD):
|
||||
async def list_logs(self, cdb: AsyncSession, site_id, limit: int = 50) -> Tuple[ErrorType, list]:
|
||||
try:
|
||||
query = (
|
||||
select(publish_logs)
|
||||
.where(publish_logs.site_id == site_id, publish_logs.deleted == False) # noqa: E712
|
||||
.order_by(publish_logs.created_at.desc())
|
||||
select(site_publish_logs)
|
||||
.where(site_publish_logs.site_id == site_id, site_publish_logs.deleted == False) # noqa: E712
|
||||
.order_by(site_publish_logs.created_at.desc())
|
||||
.limit(limit)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
|
||||
Reference in new issue
Block a user