73 lines
2.1 KiB
Python
73 lines
2.1 KiB
Python
|
|
# -*- coding: utf-8 -*-
|
||
|
|
"""迁移脚本:添加 correction 字段到对话记录表。"""
|
||
|
|
import logging
|
||
|
|
from insurance.db.compat import db
|
||
|
|
|
||
|
|
|
||
|
|
def migrate():
|
||
|
|
"""添加 correction 字段到 insurance_chat_records 表。"""
|
||
|
|
try:
|
||
|
|
from sqlalchemy import inspect
|
||
|
|
|
||
|
|
# 检查字段是否已存在
|
||
|
|
inspector = inspect(db.engine)
|
||
|
|
columns = [col['name'] for col in inspector.get_columns('insurance_chat_records')]
|
||
|
|
if 'correction' in columns:
|
||
|
|
logging.info("字段 correction 已存在,跳过添加")
|
||
|
|
return
|
||
|
|
|
||
|
|
# 根据数据库方言执行不同的 SQL
|
||
|
|
dialect = db.engine.dialect.name
|
||
|
|
if dialect == 'sqlite':
|
||
|
|
db.session.execute(
|
||
|
|
"ALTER TABLE insurance_chat_records "
|
||
|
|
"ADD COLUMN correction TEXT"
|
||
|
|
)
|
||
|
|
else:
|
||
|
|
# PostgreSQL
|
||
|
|
db.session.execute(
|
||
|
|
"ALTER TABLE insurance_chat_records "
|
||
|
|
"ADD COLUMN correction TEXT NULL "
|
||
|
|
"COMMENT '用户纠错内容'"
|
||
|
|
)
|
||
|
|
|
||
|
|
db.session.commit()
|
||
|
|
logging.info("成功添加 correction 字段")
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logging.error("添加 correction 字段失败: %s", e)
|
||
|
|
db.session.rollback()
|
||
|
|
raise
|
||
|
|
|
||
|
|
|
||
|
|
def downgrade():
|
||
|
|
"""删除 correction 字段。"""
|
||
|
|
try:
|
||
|
|
from sqlalchemy import inspect
|
||
|
|
|
||
|
|
inspector = inspect(db.engine)
|
||
|
|
columns = [col['name'] for col in inspector.get_columns('insurance_chat_records')]
|
||
|
|
if 'correction' not in columns:
|
||
|
|
logging.info("字段 correction 不存在,跳过删除")
|
||
|
|
return
|
||
|
|
|
||
|
|
db.session.execute(
|
||
|
|
"ALTER TABLE insurance_chat_records DROP COLUMN correction"
|
||
|
|
)
|
||
|
|
db.session.commit()
|
||
|
|
logging.info("成功删除 correction 字段")
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logging.error("删除 correction 字段失败: %s", e)
|
||
|
|
db.session.rollback()
|
||
|
|
raise
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
import sys
|
||
|
|
sys.path.insert(0, ".")
|
||
|
|
from app import app
|
||
|
|
with app.app_context():
|
||
|
|
migrate()
|
||
|
|
print("迁移完成")
|