190 lines
7.1 KiB
Python
190 lines
7.1 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
SQLite → MySQL 数据迁移脚本
|
||
|
||
用法:
|
||
# 先装依赖
|
||
pip install pymysql
|
||
|
||
# 确保 MySQL 已建库(utf8mb4)
|
||
# CREATE DATABASE sdmu CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||
|
||
# 执行迁移(环境变量配置目标 MySQL)
|
||
MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_USER=root MYSQL_PASSWORD=xxx MYSQL_DB=sdmu \
|
||
python3 app/migrate_to_mysql.py
|
||
|
||
# 或用命令行参数
|
||
python3 app/migrate_to_mysql.py --host localhost --port 3306 --user root --password xxx --db sdmu
|
||
|
||
# --dry-run 只打印不写
|
||
python3 app/migrate_to_mysql.py --host ... --dry-run
|
||
|
||
注意:
|
||
本脚本直接用 SQLAlchemy 连 MySQL 建表+插数据,不走 create_app(),
|
||
不会启动抢课引擎等后台线程,可安全运行。
|
||
建表依赖 app/models.py 里的模型定义(仅取 db 元数据,不初始化应用)。
|
||
"""
|
||
import argparse
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
# 添加项目路径
|
||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||
|
||
|
||
def _build_mysql_uri(host, port, user, password, db):
|
||
"""构造 MySQL 连接串"""
|
||
return f"mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset=utf8mb4"
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="SQLite → MySQL 数据迁移")
|
||
parser.add_argument('--host', default=os.environ.get('MYSQL_HOST', 'localhost'))
|
||
parser.add_argument('--port', type=int, default=int(os.environ.get('MYSQL_PORT', '3306')))
|
||
parser.add_argument('--user', default=os.environ.get('MYSQL_USER', 'root'))
|
||
parser.add_argument('--password', default=os.environ.get('MYSQL_PASSWORD', ''))
|
||
parser.add_argument('--db', default=os.environ.get('MYSQL_DB', 'sdmu'))
|
||
parser.add_argument('--sqlite', default=str(Path(__file__).parent.parent / 'app.db'),
|
||
help='SQLite 文件路径(默认 app.db)')
|
||
parser.add_argument('--dry-run', action='store_true', help='只读不写,打印每表行数')
|
||
parser.add_argument('--batch-size', type=int, default=500, help='批量插入大小')
|
||
args = parser.parse_args()
|
||
|
||
# ===== 0. 在导入 app 之前设好 DATABASE_URL,避免 config 读到 SQLite =====
|
||
mysql_uri = _build_mysql_uri(args.host, args.port, args.user, args.password, args.db)
|
||
os.environ['DATABASE_URL'] = mysql_uri
|
||
|
||
from sqlalchemy import create_engine, MetaData, select, text
|
||
|
||
# ===== 1. 读 SQLite =====
|
||
sqlite_uri = f"sqlite:///{args.sqlite}"
|
||
if not Path(args.sqlite).exists():
|
||
print(f"[ERROR] SQLite 文件不存在: {args.sqlite}")
|
||
sys.exit(1)
|
||
|
||
print(f"[1/4] 读取 SQLite: {args.sqlite}")
|
||
sqlite_engine = create_engine(sqlite_uri, echo=False)
|
||
sqlite_meta = MetaData()
|
||
sqlite_meta.reflect(bind=sqlite_engine)
|
||
|
||
tables = sorted(sqlite_meta.tables.keys())
|
||
print(f" 发现 {len(tables)} 张表: {', '.join(tables)}")
|
||
|
||
# 先读全部数据到内存
|
||
all_data = {}
|
||
for table_name in tables:
|
||
table = sqlite_meta.tables[table_name]
|
||
with sqlite_engine.connect() as conn:
|
||
rows = conn.execute(select(table)).fetchall()
|
||
all_data[table_name] = [dict(row._mapping) for row in rows]
|
||
print(f" {table_name}: {len(all_data[table_name])} 行")
|
||
|
||
if args.dry_run:
|
||
print("\n[dry-run] 只读模式,不写入 MySQL")
|
||
total = sum(len(v) for v in all_data.values())
|
||
print(f"[dry-run] 共 {total} 行待迁移")
|
||
return
|
||
|
||
# ===== 2. 连 MySQL 并建表 =====
|
||
print(f"\n[2/4] 连接 MySQL: {args.host}:{args.port}/{args.db}")
|
||
try:
|
||
mysql_engine = create_engine(mysql_uri, echo=False)
|
||
with mysql_engine.connect() as conn:
|
||
conn.execute(text("SELECT 1"))
|
||
except Exception as e:
|
||
print(f"[ERROR] 连接 MySQL 失败: {e}")
|
||
print(" 请确认:")
|
||
print(" 1. MySQL 已启动")
|
||
print(f" 2. 数据库 {args.db} 已创建(utf8mb4)")
|
||
print(" CREATE DATABASE sdmu CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")
|
||
print(" 3. 用户名密码正确")
|
||
sys.exit(1)
|
||
|
||
# 用模型定义建表(只导入 models 注册表结构,不调 create_app)
|
||
print(" 建表(先删旧表)...")
|
||
from app.models import db
|
||
# 先删旧表(上次迁移可能建了字段长度不够的表)
|
||
db.metadata.drop_all(mysql_engine)
|
||
# 用模型注册的 metadata 在 MySQL 上建表
|
||
db.metadata.create_all(mysql_engine)
|
||
|
||
# 读取 MySQL 表结构
|
||
mysql_meta = MetaData()
|
||
mysql_meta.reflect(bind=mysql_engine)
|
||
mysql_tables = mysql_meta.tables
|
||
|
||
# ===== 3. 批量插入数据 =====
|
||
print(f"\n[3/4] 迁移数据(batch_size={args.batch_size})")
|
||
|
||
# 临时禁用外键检查,避免插入顺序问题
|
||
with mysql_engine.connect() as conn:
|
||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 0"))
|
||
|
||
for table_name in tables:
|
||
if table_name not in mysql_tables:
|
||
print(f" [SKIP] {table_name}: MySQL 无此表")
|
||
continue
|
||
|
||
rows = all_data[table_name]
|
||
if not rows:
|
||
print(f" [SKIP] {table_name}: 无数据")
|
||
continue
|
||
|
||
table = mysql_tables[table_name]
|
||
inserted = 0
|
||
for i in range(0, len(rows), args.batch_size):
|
||
batch = rows[i:i + args.batch_size]
|
||
try:
|
||
with mysql_engine.begin() as conn:
|
||
conn.execute(table.insert(), batch)
|
||
inserted += len(batch)
|
||
except Exception as e:
|
||
# 批量失败,逐行插入跳过重复
|
||
print(f" [WARN] {table_name} 批次 {i} 失败: {e},尝试逐行...")
|
||
for row in batch:
|
||
try:
|
||
with mysql_engine.begin() as conn:
|
||
conn.execute(table.insert(), [row])
|
||
inserted += 1
|
||
except Exception:
|
||
continue # 跳过重复/冲突行
|
||
|
||
print(f" {table_name}: 插入 {inserted}/{len(rows)} 行")
|
||
|
||
# 恢复外键检查
|
||
with mysql_engine.connect() as conn:
|
||
conn.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
|
||
|
||
# ===== 4. 校验行数 =====
|
||
print(f"\n[4/4] 校验行数")
|
||
all_ok = True
|
||
for table_name in tables:
|
||
if table_name not in mysql_tables:
|
||
continue
|
||
table = mysql_tables[table_name]
|
||
with mysql_engine.connect() as conn:
|
||
result = conn.execute(select(table))
|
||
mysql_rows = result.fetchall()
|
||
mysql_count = len(mysql_rows)
|
||
sqlite_count = len(all_data[table_name])
|
||
status = "OK" if mysql_count == sqlite_count else "MISMATCH"
|
||
if status != "OK":
|
||
all_ok = False
|
||
print(f" {table_name}: SQLite={sqlite_count} MySQL={mysql_count} [{status}]")
|
||
|
||
print("\n[完成] 迁移结束")
|
||
if not all_ok:
|
||
print(" [WARN] 部分表行数不一致,请检查")
|
||
print(" 下一步: 设 DATABASE_URL 环境变量指向 MySQL,重启应用")
|
||
print(f" export DATABASE_URL='{mysql_uri}'")
|
||
|
||
# 关闭 engine
|
||
mysql_engine.dispose()
|
||
sqlite_engine.dispose()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|