统一 Repository 方案:添加 db 基类和子图模型 + 通讯录 API 支持真实数据库
Some checks failed
构建并部署 AI Agent 服务 / deploy (push) Has been cancelled

This commit is contained in:
2026-04-27 16:37:45 +08:00
parent 0cb9571db7
commit 29016f8792
6 changed files with 460 additions and 57 deletions

97
backend/app/db/init_db.py Normal file
View File

@@ -0,0 +1,97 @@
"""
子图数据库表初始化
在 FastAPI 启动时创建表
"""
from typing import Optional
async def init_subgraph_tables(conn):
"""
初始化子图所需的表
Args:
conn: 数据库连接(来自 AsyncPostgresSaver
"""
# 1. contacts 表(通讯录)
await _create_contacts_table(conn)
# 2. words 表(词典)
await _create_words_table(conn)
# 3. news 表(资讯)
await _create_news_table(conn)
async def _create_contacts_table(conn):
"""创建 contacts 表"""
sql = """
CREATE TABLE IF NOT EXISTS contacts (
id VARCHAR(64) PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
name VARCHAR(100) NOT NULL,
phone VARCHAR(32),
email VARCHAR(100),
company VARCHAR(100),
position VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_contacts_user (user_id)
);
"""
try:
async with conn.cursor() as cur:
await cur.execute(sql)
# 注释掉 INFO 打印,避免噪声
except Exception as e:
print(f"contacts 表可能已存在: {e}")
async def _create_words_table(conn):
"""创建 words 表"""
sql = """
CREATE TABLE IF NOT EXISTS words (
id VARCHAR(64) PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
word VARCHAR(100) NOT NULL,
phonetic VARCHAR(100),
part_of_speech VARCHAR(50),
definition TEXT,
examples TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_words_user (user_id),
INDEX idx_words_word (word)
);
"""
try:
async with conn.cursor() as cur:
await cur.execute(sql)
except Exception as e:
print(f"words 表可能已存在: {e}")
async def _create_news_table(conn):
"""创建 news 表"""
sql = """
CREATE TABLE IF NOT EXISTS news (
id VARCHAR(64) PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
title VARCHAR(200) NOT NULL,
content TEXT,
url VARCHAR(500),
source VARCHAR(100),
keywords TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_news_user (user_id)
);
"""
try:
async with conn.cursor() as cur:
await cur.execute(sql)
except Exception as e:
print(f"news 表可能已存在: {e}")