#!/usr/bin/env python # -*- coding: utf-8 -*- """ 更新数据库表结构 """ import sys import os # 添加项目路径 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from app import create_app, db from sqlalchemy import text def update_database(): """更新数据库表结构""" app = create_app() with app.app_context(): try: # 检查当前license_key列的长度 result = db.session.execute(text("PRAGMA table_info(license)")) columns = result.fetchall() license_key_column = None for column in columns: if column[1] == 'license_key': license_key_column = column break if license_key_column: print(f"当前license_key列类型: {license_key_column[2]}") # 如果长度是VARCHAR(32),则更新为VARCHAR(35) if "VARCHAR(32)" in str(license_key_column[2]).upper(): print("正在更新license_key列长度为VARCHAR(35)...") # SQLite不支持直接修改列类型,需要重建表 # 但我们可以添加一个新列,复制数据,然后删除旧列,再重命名新列 # 1. 添加新列 db.session.execute(text("ALTER TABLE license ADD COLUMN license_key_new VARCHAR(35)")) # 2. 复制数据 db.session.execute(text("UPDATE license SET license_key_new = license_key")) # 3. 删除旧列(SQLite不支持直接删除列,需要重建表) # 我们采用另一种方法:直接修改表结构(这在SQLite中比较复杂) print("注意:SQLite不支持直接修改列类型,需要手动处理") print("建议使用SQLite工具手动执行以下SQL:") print("ALTER TABLE license ALTER COLUMN license_key TYPE VARCHAR(35)") elif "VARCHAR(35)" in str(license_key_column[2]).upper(): print("license_key列已经是正确的长度") else: print(f"license_key列类型未知: {license_key_column[2]}") else: print("未找到license_key列!") except Exception as e: print(f"更新数据库结构时出错: {e}") import traceback traceback.print_exc() if __name__ == "__main__": update_database()