baodan/api/insurance/db/migrate_012.py
2026-07-12 14:17:18 +08:00

58 lines
1.9 KiB
Python

# -*- coding: utf-8 -*-
"""迁移脚本:添加企微群聊配置表。"""
import logging
from sqlalchemy import text
from insurance.db.compat import db
def migrate():
"""创建 wecom_group_configs 表。"""
try:
from sqlalchemy import inspect
inspector = inspect(db.engine)
if inspector.has_table("wecom_group_configs"):
logging.info("wecom_group_configs 表已存在,跳过创建")
return
dialect = db.engine.dialect.name
id_type = "INTEGER PRIMARY KEY AUTOINCREMENT" if dialect == "sqlite" else "SERIAL PRIMARY KEY"
bool_type = "BOOLEAN DEFAULT TRUE" if dialect != "sqlite" else "BOOLEAN DEFAULT 1"
db.session.execute(text(f"""
CREATE TABLE wecom_group_configs (
id {id_type},
chatid VARCHAR(128) NOT NULL UNIQUE,
aibotid VARCHAR(128),
name VARCHAR(128),
webhook_url TEXT,
status VARCHAR(16) DEFAULT 'active',
auto_discovered {bool_type},
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_seen_at TIMESTAMP NULL
)
"""))
db.session.execute(text(
"CREATE INDEX idx_wecom_group_configs_chatid "
"ON wecom_group_configs (chatid)"
))
db.session.commit()
logging.info("成功创建 wecom_group_configs 表")
except Exception as e:
logging.error("创建企微群聊配置表失败: %s", e)
db.session.rollback()
raise
def downgrade():
"""删除 wecom_group_configs 表。"""
try:
db.session.execute(text("DROP TABLE IF EXISTS wecom_group_configs"))
db.session.commit()
except Exception as e:
logging.error("删除 wecom_group_configs 表失败: %s", e)
db.session.rollback()
raise