58 lines
2.0 KiB
Python
58 lines
2.0 KiB
Python
"""使用 Flask 应用执行数据库迁移(兼容 SQLite 和 PostgreSQL)"""
|
||
import sys
|
||
import os
|
||
|
||
# 添加项目根目录到 Python 路径
|
||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'api'))
|
||
|
||
from insurance.app import app
|
||
from insurance.db.compat import db
|
||
|
||
def add_column():
|
||
"""添加 baodan_conversation_id 字段。"""
|
||
with app.app_context():
|
||
try:
|
||
from sqlalchemy import text, inspect
|
||
|
||
# 获取数据库方言
|
||
dialect = db.engine.dialect.name
|
||
print(f"数据库方言: {dialect}")
|
||
|
||
# 检查字段是否已存在
|
||
inspector = inspect(db.engine)
|
||
columns = [col['name'] for col in inspector.get_columns('insurance_chat_sessions')]
|
||
if 'baodan_conversation_id' in columns:
|
||
print("字段 baodan_conversation_id 已存在,跳过添加")
|
||
return
|
||
|
||
# 根据数据库类型执行不同的 SQL
|
||
if dialect == 'sqlite':
|
||
# SQLite 使用 ALTER TABLE ADD COLUMN
|
||
db.session.execute(text(
|
||
"ALTER TABLE insurance_chat_sessions "
|
||
"ADD COLUMN baodan_conversation_id VARCHAR(128)"
|
||
))
|
||
else:
|
||
# PostgreSQL 使用 ALTER TABLE ADD COLUMN
|
||
db.session.execute(text(
|
||
"ALTER TABLE insurance_chat_sessions "
|
||
"ADD COLUMN baodan_conversation_id VARCHAR(128) NULL"
|
||
))
|
||
|
||
db.session.commit()
|
||
print("成功添加 baodan_conversation_id 字段")
|
||
|
||
# 验证字段已添加
|
||
inspector = inspect(db.engine)
|
||
columns = [col['name'] for col in inspector.get_columns('insurance_chat_sessions')]
|
||
if 'baodan_conversation_id' in columns:
|
||
print("验证成功: 字段已添加到数据库")
|
||
|
||
except Exception as e:
|
||
print(f"添加字段失败: {e}")
|
||
db.session.rollback()
|
||
raise
|
||
|
||
if __name__ == "__main__":
|
||
add_column()
|