Files
aitsc/migrations/versions/create_wx_tables.py
2025-02-23 09:07:52 +08:00

71 lines
2.4 KiB
Python

import pymysql
def upgrade_database():
"""创建微信用户相关表"""
try:
conn = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='food_db',
charset='utf8mb4'
)
cursor = conn.cursor()
# 创建微信用户表
cursor.execute("""
CREATE TABLE IF NOT EXISTS wx_user (
id INT PRIMARY KEY AUTO_INCREMENT,
openid VARCHAR(64) UNIQUE NOT NULL,
session_key VARCHAR(64),
unionid VARCHAR(64) UNIQUE,
nickname VARCHAR(100),
avatar_url VARCHAR(255),
gender INT DEFAULT 0,
country VARCHAR(50),
province VARCHAR(50),
city VARCHAR(50),
language VARCHAR(20),
phone VARCHAR(20),
is_active BOOLEAN DEFAULT TRUE,
last_login DATETIME DEFAULT CURRENT_TIMESTAMP,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
""")
print("创建wx_user表成功")
# 修改现有表添加外键
alter_statements = [
"ALTER TABLE prompt MODIFY user_id INT NULL",
"ALTER TABLE prompt ADD COLUMN wx_user_id INT",
"ALTER TABLE prompt ADD FOREIGN KEY (wx_user_id) REFERENCES wx_user(id)",
"ALTER TABLE feedback MODIFY user_id INT NULL",
"ALTER TABLE feedback ADD COLUMN wx_user_id INT",
"ALTER TABLE feedback ADD FOREIGN KEY (wx_user_id) REFERENCES wx_user(id)"
]
for statement in alter_statements:
try:
cursor.execute(statement)
print(f"执行成功: {statement}")
except Exception as e:
print(f"执行失败: {statement}")
print(f"错误: {str(e)}")
conn.commit()
print("\n=== 数据库升级完成 ===")
except Exception as e:
print(f"数据库升级失败: {str(e)}")
if 'conn' in locals():
conn.rollback()
finally:
if 'cursor' in locals():
cursor.close()
if 'conn' in locals():
conn.close()
if __name__ == '__main__':
upgrade_database()