몰이 열린 집합이라 와이드 컬럼(gmarket_*, st11_* …) 대신 JSONB 한 컬럼으로 담는다 — 몰 추가 시 마이그레이션 0. naver/coupang/final 3선 컬럼은 그래프 하위호환 유지. - models: price_history.by_mall JSONB 추가 - crud: record/list 에 by_mall 왕복(json.dumps + CAST jsonb) - handler: _price_snapshot 에 summarize_by_mall 적재, final 은 소스무관 전체 최저로 - protocol/service: history API 응답에 by_mall 노출 - migrations/2026-07-09: 기존 dev DB 동기화용 ALTER(추적 파일) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
68 lines
2.8 KiB
Python
68 lines
2.8 KiB
Python
"""최저가 스냅샷 CRUD — 트리거 시점마다 기록하고, 상품별 시계열로 조회(그래프)."""
|
|
|
|
import json
|
|
|
|
from sqlalchemy import text
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.enums import DBType, DBWRType
|
|
|
|
_FIELDS = (
|
|
"product_code", "job_id", "outcome", "matched_count",
|
|
"naver_lowest", "naver_name", "naver_url",
|
|
"coupang_lowest", "coupang_name", "coupang_url",
|
|
"final_lowest", "final_source",
|
|
)
|
|
|
|
|
|
class PriceHistory:
|
|
DB = DBType.MAIN.value
|
|
|
|
async def record(self, event: dict):
|
|
"""스냅샷 1건 저장. triggered_at 은 now()(관측 시각). 로깅 실패가 검색을 막지 않도록 호출부에서 예외 처리."""
|
|
sql = text("""
|
|
INSERT INTO price_history
|
|
(product_code, job_id, outcome, matched_count,
|
|
naver_lowest, naver_name, naver_url,
|
|
coupang_lowest, coupang_name, coupang_url,
|
|
final_lowest, final_source, by_mall)
|
|
VALUES
|
|
(:product_code, :job_id, :outcome, :matched_count,
|
|
:naver_lowest, :naver_name, :naver_url,
|
|
:coupang_lowest, :coupang_name, :coupang_url,
|
|
:final_lowest, :final_source, CAST(:by_mall AS jsonb))
|
|
""")
|
|
params = {k: event.get(k) for k in _FIELDS}
|
|
by_mall = event.get("by_mall")
|
|
params["by_mall"] = json.dumps(by_mall) if by_mall is not None else None
|
|
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_WRITE.value)
|
|
try:
|
|
await s.execute(sql, params)
|
|
await s.commit()
|
|
except Exception:
|
|
await s.rollback()
|
|
raise
|
|
finally:
|
|
await DB_SESSION_MNG.end_session(self.DB, DBWRType.DB_WRITE.value)
|
|
|
|
async def list_by_product(self, product_code: str, limit: int = 100) -> list[dict]:
|
|
"""상품의 최근 스냅샷을 시각 오름차순(그래프 플롯용)으로 반환. 최근 limit 건."""
|
|
sql = text("""
|
|
SELECT * FROM (
|
|
SELECT triggered_at, outcome, matched_count,
|
|
naver_lowest, naver_name, naver_url,
|
|
coupang_lowest, coupang_name, coupang_url,
|
|
final_lowest, final_source, by_mall
|
|
FROM price_history
|
|
WHERE product_code = :pc
|
|
ORDER BY triggered_at DESC
|
|
LIMIT :lim
|
|
) t ORDER BY triggered_at ASC
|
|
""")
|
|
s = await DB_SESSION_MNG.start_session(self.DB, DBWRType.DB_READ.value)
|
|
try:
|
|
rows = (await s.execute(sql, {"pc": product_code, "lim": limit})).mappings().all()
|
|
return [dict(r) for r in rows]
|
|
finally:
|
|
await DB_SESSION_MNG.end_session(self.DB, DBWRType.DB_READ.value)
|