feat(insta-lab): db migration — trending_keywords.source + account_preferences + CRUD
- Idempotent ALTER TABLE adds source column (default 'manual') + idx_tk_source index - New account_preferences table seeded with economy/psychology/celebrity at weight=1.0 - add_trending_keyword now accepts optional source param - New helpers: add_external_trend, list_trends, get_preferences, upsert_preferences - test_db updated: six→seven tables; test_preferences_crud.py (7 new tests, all pass) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -101,6 +101,29 @@ def init_db() -> None:
|
||||
)
|
||||
""")
|
||||
|
||||
# source column for trending_keywords (idempotent ALTER)
|
||||
cols = [r[1] for r in conn.execute("PRAGMA table_info(trending_keywords)").fetchall()]
|
||||
if "source" not in cols:
|
||||
conn.execute("ALTER TABLE trending_keywords ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'")
|
||||
conn.execute("CREATE INDEX IF NOT EXISTS idx_tk_source ON trending_keywords(source, suggested_at DESC)")
|
||||
|
||||
# account_preferences — 카테고리 가중치
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS account_preferences (
|
||||
category TEXT PRIMARY KEY,
|
||||
weight REAL NOT NULL DEFAULT 1.0,
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
)
|
||||
""")
|
||||
# seed defaults if table empty
|
||||
existing = conn.execute("SELECT COUNT(*) FROM account_preferences").fetchone()[0]
|
||||
if existing == 0:
|
||||
for cat in ("economy", "psychology", "celebrity"):
|
||||
conn.execute(
|
||||
"INSERT INTO account_preferences(category, weight) VALUES(?,?)",
|
||||
(cat, 1.0),
|
||||
)
|
||||
|
||||
|
||||
# ── news_articles ────────────────────────────────────────────────
|
||||
def add_news_article(row: Dict[str, Any]) -> int:
|
||||
@@ -132,8 +155,12 @@ def list_news_articles(category: Optional[str] = None, days: int = 1) -> List[Di
|
||||
def add_trending_keyword(row: Dict[str, Any]) -> int:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO trending_keywords(keyword, category, score, articles_count) VALUES(?,?,?,?)",
|
||||
(row["keyword"], row["category"], float(row.get("score", 0.0)), int(row.get("articles_count", 0))),
|
||||
"INSERT INTO trending_keywords(keyword, category, score, articles_count, source) VALUES(?,?,?,?,?)",
|
||||
(
|
||||
row["keyword"], row["category"],
|
||||
float(row.get("score", 0.0)), int(row.get("articles_count", 0)),
|
||||
row.get("source", "manual"),
|
||||
),
|
||||
)
|
||||
return cur.lastrowid
|
||||
|
||||
@@ -276,3 +303,50 @@ def get_prompt_template(name: str) -> Optional[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
row = conn.execute("SELECT * FROM prompt_templates WHERE name=?", (name,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
# ── external trends ─────────────────────────────────────────────
|
||||
def add_external_trend(row: Dict[str, Any]) -> int:
|
||||
"""`source` 필수 — naver_popular | google_trends. trending_keywords에 인서트."""
|
||||
if "source" not in row:
|
||||
raise ValueError("add_external_trend requires 'source' field")
|
||||
return add_trending_keyword(row)
|
||||
|
||||
|
||||
def list_trends(source: Optional[str] = None, category: Optional[str] = None,
|
||||
days: int = 1) -> List[Dict[str, Any]]:
|
||||
sql = "SELECT * FROM trending_keywords WHERE suggested_at >= datetime('now', ?)"
|
||||
params: List[Any] = [f"-{int(days)} days"]
|
||||
if source and source != "all":
|
||||
sql += " AND source=?"
|
||||
params.append(source)
|
||||
if category:
|
||||
sql += " AND category=?"
|
||||
params.append(category)
|
||||
sql += " ORDER BY suggested_at DESC, score DESC"
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
# ── account_preferences ─────────────────────────────────────────
|
||||
def get_preferences() -> List[Dict[str, Any]]:
|
||||
with _conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT category, weight, updated_at FROM account_preferences ORDER BY category ASC"
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def upsert_preferences(weights: Dict[str, float]) -> None:
|
||||
"""전체 upsert. 기존에 있던 카테고리는 weight 갱신, 신규는 INSERT.
|
||||
명시되지 않은 기존 카테고리는 그대로 둔다 (삭제 X). 삭제 필요 시 별도 API로."""
|
||||
with _conn() as conn:
|
||||
for cat, w in weights.items():
|
||||
conn.execute("""
|
||||
INSERT INTO account_preferences(category, weight)
|
||||
VALUES(?,?)
|
||||
ON CONFLICT(category) DO UPDATE SET
|
||||
weight=excluded.weight,
|
||||
updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')
|
||||
""", (cat, float(w)))
|
||||
|
||||
Reference in New Issue
Block a user