77 lines
2.2 KiB
Python
77 lines
2.2 KiB
Python
|
|
"""迁移脚本 002:创建角色表
|
|||
|
|
|
|||
|
|
使用方式:
|
|||
|
|
python -m insurance.db.migrate_002
|
|||
|
|
|
|||
|
|
或在应用启动时自动执行(需要配置 MIGRATION_ENABLED=true)
|
|||
|
|
"""
|
|||
|
|
from sqlalchemy import text
|
|||
|
|
from insurance.db.compat import db
|
|||
|
|
|
|||
|
|
|
|||
|
|
def migrate():
|
|||
|
|
"""执行迁移:创建角色表。"""
|
|||
|
|
print("[migrate_002] 开始执行迁移...")
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
# 检查表是否已存在
|
|||
|
|
result = db.session.execute(text("""
|
|||
|
|
SELECT EXISTS (
|
|||
|
|
SELECT FROM information_schema.tables
|
|||
|
|
WHERE table_name = 'insurance_roles'
|
|||
|
|
)
|
|||
|
|
"""))
|
|||
|
|
|
|||
|
|
if result.scalar():
|
|||
|
|
print("[migrate_002] 表已存在,跳过")
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
# 创建角色表
|
|||
|
|
print("[migrate_002] 创建 insurance_roles 表")
|
|||
|
|
db.session.execute(text("""
|
|||
|
|
CREATE TABLE insurance_roles (
|
|||
|
|
id SERIAL PRIMARY KEY,
|
|||
|
|
name VARCHAR(64) UNIQUE NOT NULL,
|
|||
|
|
description VARCHAR(256) DEFAULT '',
|
|||
|
|
permissions TEXT DEFAULT '[]',
|
|||
|
|
builtin BOOLEAN DEFAULT FALSE,
|
|||
|
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|||
|
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|||
|
|
)
|
|||
|
|
"""))
|
|||
|
|
|
|||
|
|
# 添加注释
|
|||
|
|
db.session.execute(text("""
|
|||
|
|
COMMENT ON TABLE insurance_roles IS '系统角色表'
|
|||
|
|
"""))
|
|||
|
|
db.session.execute(text("""
|
|||
|
|
COMMENT ON COLUMN insurance_roles.name IS '角色名称'
|
|||
|
|
"""))
|
|||
|
|
db.session.execute(text("""
|
|||
|
|
COMMENT ON COLUMN insurance_roles.permissions IS '权限列表JSON'
|
|||
|
|
"""))
|
|||
|
|
db.session.execute(text("""
|
|||
|
|
COMMENT ON COLUMN insurance_roles.builtin IS '是否内置角色'
|
|||
|
|
"""))
|
|||
|
|
|
|||
|
|
db.session.commit()
|
|||
|
|
|
|||
|
|
print("[migrate_002] 迁移完成!")
|
|||
|
|
return True
|
|||
|
|
|
|||
|
|
except Exception as e:
|
|||
|
|
db.session.rollback()
|
|||
|
|
print(f"[migrate_002] 迁移失败: {e}")
|
|||
|
|
return False
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
from flask import Flask
|
|||
|
|
from configs.app_config import AppConfig
|
|||
|
|
|
|||
|
|
app = Flask(__name__)
|
|||
|
|
app.config.from_object(AppConfig)
|
|||
|
|
|
|||
|
|
with app.app_context():
|
|||
|
|
migrate()
|