Kamixitong/update_mysql_schema.py

84 lines
3.4 KiB
Python
Raw Normal View History

2025-11-11 23:04:01 +08:00
import os
import sys
# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 在导入应用之前加载环境变量
try:
from dotenv import load_dotenv
if load_dotenv():
print("成功加载.env文件")
except ImportError:
print("python-dotenv未安装跳过.env文件加载")
from app import create_app, db
from sqlalchemy import text
# 创建应用实例
app = create_app()
with app.app_context():
try:
# 检查是否需要添加 is_deleted 字段
result = db.session.execute(text("SHOW COLUMNS FROM admin LIKE 'is_deleted'"))
if result.fetchone() is None:
print("Adding is_deleted column to admin table...")
db.session.execute(text("ALTER TABLE admin ADD COLUMN is_deleted INTEGER NOT NULL DEFAULT 0"))
print("✓ Added is_deleted column")
else:
print("is_deleted column already exists")
# 检查是否需要添加 delete_time 字段
result = db.session.execute(text("SHOW COLUMNS FROM admin LIKE 'delete_time'"))
if result.fetchone() is None:
print("Adding delete_time column to admin table...")
db.session.execute(text("ALTER TABLE admin ADD COLUMN delete_time DATETIME NULL"))
print("✓ Added delete_time column")
else:
print("delete_time column already exists")
# 检查是否需要添加 phone 字段(如果不存在)
result = db.session.execute(text("SHOW COLUMNS FROM admin LIKE 'phone'"))
if result.fetchone() is None:
print("Adding phone column to admin table...")
db.session.execute(text("ALTER TABLE admin ADD COLUMN phone VARCHAR(16) NULL"))
print("✓ Added phone column")
else:
print("phone column already exists")
# 创建 audit_log 表(如果不存在)
result = db.session.execute(text("SHOW TABLES LIKE 'audit_log'"))
if result.fetchone() is None:
print("Creating audit_log table...")
db.session.execute(text("""
CREATE TABLE audit_log (
log_id INTEGER NOT NULL AUTO_INCREMENT,
admin_id INTEGER NOT NULL,
action VARCHAR(32) NOT NULL,
target_type VARCHAR(32) NOT NULL,
target_id INTEGER,
details TEXT,
ip_address VARCHAR(32),
user_agent VARCHAR(256),
create_time DATETIME NOT NULL,
PRIMARY KEY (log_id),
FOREIGN KEY (admin_id) REFERENCES admin (admin_id)
)
"""))
# 创建索引
db.session.execute(text("CREATE INDEX ix_audit_log_admin_id ON audit_log (admin_id)"))
db.session.execute(text("CREATE INDEX ix_audit_log_action ON audit_log (action)"))
db.session.execute(text("CREATE INDEX ix_audit_log_create_time ON audit_log (create_time)"))
print("✓ Created audit_log table")
else:
print("audit_log table already exists")
# 提交所有更改
db.session.commit()
print("\n✓ Database schema update completed!")
except Exception as e:
print(f"Database schema update failed: {e}")
import traceback
traceback.print_exc()