|
| 1 | +import glob |
| 2 | +import importlib |
| 3 | +import os |
| 4 | + |
| 5 | +from tortoise import Tortoise |
| 6 | + |
| 7 | +from core.settings import data_root |
| 8 | + |
| 9 | + |
| 10 | +async def init_db(): |
| 11 | + try: |
| 12 | + # 使用正确的Tortoise初始化配置格式 |
| 13 | + db_config = { |
| 14 | + "db_url": f"sqlite://{data_root}/filecodebox.db", |
| 15 | + "modules": {"models": ["apps.base.models"]}, |
| 16 | + "use_tz": False, |
| 17 | + "timezone": "Asia/Shanghai" |
| 18 | + } |
| 19 | + |
| 20 | + await Tortoise.init(**db_config) |
| 21 | + |
| 22 | + # 创建migrations表 |
| 23 | + await Tortoise.get_connection("default").execute_script(""" |
| 24 | + CREATE TABLE IF NOT EXISTS migrates ( |
| 25 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 26 | + migration_file VARCHAR(255) NOT NULL UNIQUE, |
| 27 | + executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP |
| 28 | + ) |
| 29 | + """) |
| 30 | + |
| 31 | + # 执行迁移 |
| 32 | + await execute_migrations() |
| 33 | + |
| 34 | + except Exception as e: |
| 35 | + print(f"数据库初始化失败: {str(e)}") |
| 36 | + raise |
| 37 | + |
| 38 | + |
| 39 | +async def execute_migrations(): |
| 40 | + """执行数据库迁移""" |
| 41 | + try: |
| 42 | + # 收集迁移文件 |
| 43 | + migration_files = [] |
| 44 | + for root, dirs, files in os.walk("apps"): |
| 45 | + if "migrations" in dirs: |
| 46 | + migration_path = os.path.join(root, "migrations") |
| 47 | + migration_files.extend(glob.glob(os.path.join(migration_path, "migrations_*.py"))) |
| 48 | + |
| 49 | + # 按文件名排序 |
| 50 | + migration_files.sort() |
| 51 | + |
| 52 | + for migration_file in migration_files: |
| 53 | + file_name = os.path.basename(migration_file) |
| 54 | + |
| 55 | + # 检查是否已执行 |
| 56 | + executed = await Tortoise.get_connection("default").execute_query( |
| 57 | + "SELECT id FROM migrates WHERE migration_file = ?", [file_name] |
| 58 | + ) |
| 59 | + |
| 60 | + if not executed[1]: |
| 61 | + print(f"执行迁移: {file_name}") |
| 62 | + # 导入并执行migration |
| 63 | + module_path = migration_file.replace("/", ".").replace("\\", ".").replace(".py", "") |
| 64 | + try: |
| 65 | + migration_module = importlib.import_module(module_path) |
| 66 | + if hasattr(migration_module, "migrate"): |
| 67 | + await migration_module.migrate() |
| 68 | + # 记录执行 |
| 69 | + await Tortoise.get_connection("default").execute_query( |
| 70 | + "INSERT INTO migrates (migration_file) VALUES (?)", |
| 71 | + [file_name] |
| 72 | + ) |
| 73 | + print(f"迁移完成: {file_name}") |
| 74 | + except Exception as e: |
| 75 | + print(f"迁移 {file_name} 执行失败: {str(e)}") |
| 76 | + raise |
| 77 | + |
| 78 | + except Exception as e: |
| 79 | + print(f"迁移过程发生错误: {str(e)}") |
| 80 | + raise |
0 commit comments