Files
ailine/backend/app/db/init_db.py

98 lines
2.5 KiB
Python
Raw Normal View History

"""
子图数据库表初始化
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}")