Files
linkup/backend/tools/migrate_db.py
T
2026-10-29 16:27:16 +08:00

230 lines
8.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Bidirectional SQLite/MySQL migration for LinkUp.
Examples:
python tools/migrate_db.py sqlite-to-mysql --sqlite ./data/linkup.db \
--mysql-url mysql+pymysql://linkup:secret@127.0.0.1:3306/linkup
python tools/migrate_db.py mysql-to-sqlite --mysql-url mysql+pymysql://... \
--sqlite ./data/linkup-copy.db
The script is deliberately idempotent: rows are merged by their primary key,
so it can be resumed after a network interruption. Use --truncate only when a
fresh target database is intended.
"""
from __future__ import annotations
import argparse
import os
import sys
import tomllib
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine, delete, inspect, insert, select, text, update
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from db_schema import TABLES, metadata
DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "config.toml"
TABLE_ORDER = [
"users",
"user_stats",
"email_verifications",
"login_verifications",
"password_resets",
"user_known_ips",
"sessions",
"student_verifications",
"invite_codes",
"invite_relations",
"credit_adjustments",
"point_entries",
"tasks",
"task_defaults",
"notifications",
"reports",
]
# 新增表允许从旧库迁移时暂不存在;目标库会由 metadata.create_all 自动建表。
OPTIONAL_SOURCE_TABLES = {"task_defaults", "notifications", "password_resets", "user_known_ips"}
DEFAULTS: dict[str, dict[str, Any]] = {
"email_verifications": {"attempts": 0},
"login_verifications": {"attempts": 0},
"user_stats": {
"points_balance": 750, "withdrawable_points": 0, "credit_score": 70,
"breach_count": 0, "commitments_count": 0, "completed_tasks": 0,
"current_streak": 0,
},
"invite_codes": {"max_uses": 2, "used_count": 0},
"point_entries": {"withdrawable_delta": 0},
"tasks": {"reward": 0, "status": "open"},
"reports": {"status": "open"},
}
def load_config(path: Path) -> dict[str, Any]:
if not path.exists():
return {}
with path.open("rb") as handle:
return tomllib.load(handle)
def sqlite_url(path: str) -> str:
resolved = Path(path).expanduser().resolve()
resolved.parent.mkdir(parents=True, exist_ok=True)
return f"sqlite:///{resolved.as_posix()}"
def mysql_url(value: str) -> str:
url = value.strip()
if url.startswith("mysql://"):
return "mysql+pymysql://" + url[len("mysql://"):]
if url.startswith("mysql+pymysql://"):
return url
if url.startswith("mysql+asyncmy://"):
return "mysql+pymysql://" + url[len("mysql+asyncmy://"):]
raise ValueError("MySQL URL 必须以 mysql://、mysql+pymysql:// 或 mysql+asyncmy:// 开头")
def make_engine(url: str, label: str) -> Engine:
kwargs: dict[str, Any] = {"future": True, "pool_pre_ping": True}
if url.startswith("sqlite://"):
kwargs["connect_args"] = {"check_same_thread": False, "timeout": 60}
else:
kwargs.update(pool_size=5, max_overflow=10, pool_recycle=1800)
print(f"[LinkUp] 连接{label}: {url.split('@')[-1]}")
return create_engine(url, **kwargs)
def table_map() -> dict[str, Any]:
return {table.name: table for table in TABLES}
def source_rows(connection, table, available_columns: set[str]) -> list[dict[str, Any]]:
selected = [column for column in table.c if column.name in available_columns]
if not selected:
return []
result = connection.execute(select(*selected))
return [dict(row) for row in result.mappings().all()]
def normalise_row(table, row: dict[str, Any]) -> dict[str, Any]:
values: dict[str, Any] = {}
defaults = DEFAULTS.get(table.name, {})
for column in table.c:
if column.name in row:
values[column.name] = row[column.name]
elif column.name in defaults:
values[column.name] = defaults[column.name]
elif column.nullable or column.primary_key:
values[column.name] = None
return values
def merge_rows(connection, table, rows: list[dict[str, Any]]) -> tuple[int, int]:
primary_keys = [column.name for column in table.primary_key.columns]
inserted = updated = 0
for original in rows:
row = normalise_row(table, original)
if any(row.get(key) is None for key in primary_keys):
continue
condition = [table.c[key] == row[key] for key in primary_keys]
exists = connection.execute(select(table).where(*condition).limit(1)).first()
if exists:
connection.execute(update(table).where(*condition).values(**row))
updated += 1
else:
connection.execute(insert(table).values(**row))
inserted += 1
return inserted, updated
def truncate_target(connection, tables: dict[str, Any]) -> None:
for name in reversed(TABLE_ORDER):
connection.execute(delete(tables[name]))
def migrate(args: argparse.Namespace) -> None:
config = load_config(Path(args.config).resolve())
database = config.get("database", {})
source_is_sqlite = args.direction == "sqlite-to-mysql"
source_sqlite = args.sqlite or database.get("path", "./data/linkup.db")
source_mysql = args.mysql_url or os.getenv("DATABASE_URL") or database.get("url", "")
if source_is_sqlite:
if not source_mysql:
raise SystemExit("缺少目标 MySQL URL,请使用 --mysql-url")
source_engine = make_engine(sqlite_url(source_sqlite), "SQLite 源库")
target_engine = make_engine(mysql_url(source_mysql), "MySQL 目标库")
else:
if not source_mysql:
raise SystemExit("缺少源 MySQL URL,请使用 --mysql-url")
target_sqlite = args.sqlite or "./data/linkup-migrated.db"
source_engine = make_engine(mysql_url(source_mysql), "MySQL 源库")
target_engine = make_engine(sqlite_url(target_sqlite), "SQLite 目标库")
tables = table_map()
try:
metadata.create_all(target_engine)
# Node 版本的旧 SQLite 数据库可能在 tasks 表中还没有 claimer_id。
# MySQL 已存在该字段时 ALTER 会失败,安全忽略即可。
with target_engine.begin() as target_schema:
try:
target_schema.execute(text("ALTER TABLE tasks ADD COLUMN claimer_id VARCHAR(64)"))
except Exception:
pass
try:
target_schema.execute(text("ALTER TABLE tasks ADD COLUMN school VARCHAR(160)"))
except Exception:
pass
try:
target_schema.execute(text("UPDATE tasks SET school = place WHERE school IS NULL"))
except Exception:
pass
source_inspector = inspect(source_engine)
available = {name: {column["name"] for column in source_inspector.get_columns(name)} for name in TABLE_ORDER if source_inspector.has_table(name)}
missing = [name for name in TABLE_ORDER if name not in available and name not in OPTIONAL_SOURCE_TABLES]
if missing:
raise SystemExit(f"源数据库缺少表:{', '.join(missing)}")
with target_engine.begin() as target:
if args.truncate:
print("[LinkUp] 清空目标表(--truncate)")
truncate_target(target, tables)
with source_engine.connect() as source:
total_inserted = total_updated = 0
for name in TABLE_ORDER:
if name not in available:
print(f"[LinkUp] {name}: 源库暂无,跳过")
continue
table = tables[name]
rows = source_rows(source, table, available[name])
inserted, updated = merge_rows(target, table, rows)
total_inserted += inserted
total_updated += updated
print(f"[LinkUp] {name}: {len(rows)} 行,新增 {inserted},更新 {updated}")
print(f"[LinkUp] 迁移完成:新增 {total_inserted} 行,更新 {total_updated} 行")
finally:
source_engine.dispose()
target_engine.dispose()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="LinkUp SQLite/MySQL 双向迁移工具")
parser.add_argument("direction", choices=("sqlite-to-mysql", "mysql-to-sqlite"))
parser.add_argument("--sqlite", help="SQLite 文件路径")
parser.add_argument("--mysql-url", help="MySQL 连接串")
parser.add_argument("--config", default=str(DEFAULT_CONFIG), help="配置文件路径(默认 backend/config.toml)")
parser.add_argument("--truncate", action="store_true", help="迁移前清空目标库,危险操作,请确认目标库可重建")
return parser.parse_args()
if __name__ == "__main__":
try:
migrate(parse_args())
except (SQLAlchemyError, ValueError) as error:
print(f"[LinkUp] 迁移失败:{error}", file=sys.stderr)
raise SystemExit(1)