Files
37duAutomation/desktop/controlplane/tools/migrate_sqlite_to_mysql.py
T
puddy 84d3e103ec refactor: 整体迁移控制面至MySQL + 替换UI框架为Element Plus
1. 移除naive-ui依赖,迁移前端至Element Plus
2. 重构后端数据库层,切换为MySQL替代SQLite
3. 调整项目部署架构,停止exe打包改为源码部署
4. 新增设备上报接口与相关数据库模型
5. 优化配置路径与SQL语法,替换为MySQL占位符格式
6. 调整站点名称与文案,统一为「37du 插件管理平台」
7. 新增SQLite到MySQL迁移脚本
2026-09-16 15:58:45 +08:00

167 lines
7.5 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.
# -*- coding: utf-8 -*-
"""SQLite → MySQL 一次性迁移脚本(37du 控制面)。
将历史 controlplane.db(SQLite)中的业务数据迁入 MySQL(MYSQL_DB 库)。
- 幂等:有唯一键的表用 ON DUPLICATE KEY UPDATE,可重复执行;
audit_logs / runtime_reports 无唯一键(纯追加日志),请勿重复执行,否则会追加副本。
- plugin_grants 已并入 account_plugins(MySQL 版无独立 plugin_grants 表),
迁移时以 plugin_grants 的 can_download/can_run 覆盖同名 account_plugins 行。
用法(在 desktop/ 目录下执行,模块搜索根 = desktop/):
.venv\\Scripts\\python.exe -m controlplane.tools.migrate_sqlite_to_mysql
前提:
- controlplane/.env 已配置 MYSQL_*(迁移目标);
- 脚本会自动建库建表(幂等 DDL),无需手工先建。
"""
from __future__ import annotations
import sqlite3
import sys
from pathlib import Path
# 兼容两种执行方式:python -m controlplane.tools.xxx(desktop/ 为搜索根)或直接跑脚本
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import pymysql # noqa: E402
from pymysql.cursors import DictCursor # noqa: E402
from controlplane.core import config # noqa: E402
from controlplane.core.db import _ensure_database, _init_db # noqa: E402
def _mysql() -> pymysql.connections.Connection:
return pymysql.connect(
host=config.MYSQL_HOST, port=config.MYSQL_PORT,
user=config.MYSQL_USER, password=config.MYSQL_PASSWORD,
database=config.MYSQL_DB, charset="utf8mb4",
cursorclass=DictCursor, autocommit=False)
def _sqlite_cols(conn: sqlite3.Connection, table: str) -> set:
try:
return {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()}
except sqlite3.OperationalError:
return set()
def _common_cols(conn: sqlite3.Connection, table: str, wanted: list) -> list:
have = _sqlite_cols(conn, table)
return [c for c in wanted if c in have]
def _upsert(mysql, table: str, columns: list, rows: list) -> int:
"""按唯一键幂等写入;columns 含目标列名(与 SQLite 同名)。"""
if not columns or not rows:
return 0
ph = ", ".join(["%s"] * len(columns))
sets = ", ".join(f"{c} = VALUES({c})" for c in columns)
sql = (f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph}) "
f"ON DUPLICATE KEY UPDATE {sets}")
with mysql.cursor() as cur:
for r in rows:
cur.execute(sql, tuple(r))
mysql.commit()
return len(rows)
def _insert_append(mysql, table: str, columns: list, rows: list) -> int:
"""日志类纯追加写入(无唯一键,重复执行会追加副本)。"""
if not columns or not rows:
return 0
ph = ", ".join(["%s"] * len(columns))
sql = f"INSERT INTO {table}({', '.join(columns)}) VALUES ({ph})"
with mysql.cursor() as cur:
for r in rows:
cur.execute(sql, tuple(r))
mysql.commit()
return len(rows)
def _main() -> int:
if not config.MYSQL_HOST:
print("[migrate] 未配置 MySQL(MYSQL_HOST),请先配置 controlplane/.env")
return 1
src = config.DB_PATH
if not src.is_file():
print(f"[migrate] 未找到 SQLite 源库:{src},无需迁移")
return 0
print(f"[migrate] 源库(SQLite):{src}")
print(f"[migrate] 目标(MySQL):{config.MYSQL_DB}@{config.MYSQL_HOST}:{config.MYSQL_PORT}")
_ensure_database()
_init_db() # 幂等建表 + 登记迁移版本,保证目标结构就绪
mysql = _mysql()
try:
with sqlite3.connect(str(src)) as sconn:
sconn.row_factory = sqlite3.Row
# ---- 1) accounts(id 自增不迁移,账号唯一键幂等) ----
cols = _common_cols(sconn, "accounts", [
"account", "password_hash", "salt", "is_admin", "dept", "nickname",
"dingtalk_uid", "must_change_pwd", "avatar", "status", "created_at"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM accounts")] if cols else []
print(f"[migrate] accounts: {_upsert(mysql, 'accounts', cols, rows)}")
# ---- 2) plugins ----
cols = _common_cols(sconn, "plugins", [
"id", "name", "latest_version", "description", "category", "icon",
"status", "force_min_version", "force_deadline", "manifest", "created_at"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM plugins")] if cols else []
print(f"[migrate] plugins: {_upsert(mysql, 'plugins', cols, rows)}")
# ---- 3) plugin_versions(id 不迁移) ----
cols = _common_cols(sconn, "plugin_versions", [
"plugin_id", "version", "filename", "uploaded_at", "sha256", "size_bytes"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM plugin_versions")] if cols else []
print(f"[migrate] plugin_versions: {_upsert(mysql, 'plugin_versions', cols, rows)}")
# ---- 4) account_plugins + plugin_grants 合并(后者权限位覆盖前者) ----
a_cols = _common_cols(sconn, "account_plugins", ["account", "plugin_id"])
a_rows = [tuple(r[c] for c in a_cols) for r in sconn.execute(
f"SELECT {', '.join(a_cols)} FROM account_plugins")] if a_cols else []
g_cols = _common_cols(sconn, "plugin_grants",
["account", "plugin_id", "can_download", "can_run"])
g_rows = [tuple(r[c] for c in g_cols) for r in sconn.execute(
f"SELECT {', '.join(g_cols)} FROM plugin_grants")] if g_cols else []
acc_rows = []
for _a, _p in a_rows:
acc_rows.append((_a, _p, 1, 1))
for _a, _p, _d, _rn in g_rows:
acc_rows.append((_a, _p, int(_d), int(_rn)))
print(f"[migrate] account_plugins(合并 plugin_grants): "
f"{_upsert(mysql, 'account_plugins', ['account', 'plugin_id', 'can_download', 'can_run'], acc_rows)}")
# ---- 5) account_platforms ----
cols = _common_cols(sconn, "account_platforms", ["account", "platform_id"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM account_platforms")] if cols else []
print(f"[migrate] account_platforms: {_upsert(mysql, 'account_platforms', cols, rows)}")
# ---- 6) audit_logs / 7) runtime_reports(纯追加,id 不迁移) ----
cols = _common_cols(sconn, "audit_logs", ["account", "action", "target", "detail", "at"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM audit_logs")] if cols else []
print(f"[migrate] audit_logs(追加): {_insert_append(mysql, 'audit_logs', cols, rows)}")
cols = _common_cols(sconn, "runtime_reports", [
"account", "device_id", "plugin_id", "version", "status", "msg",
"duration_sec", "at"])
rows = [tuple(r[c] for c in cols) for r in sconn.execute(
f"SELECT {', '.join(cols)} FROM runtime_reports")] if cols else []
print(f"[migrate] runtime_reports(追加): {_insert_append(mysql, 'runtime_reports', cols, rows)}")
finally:
mysql.close()
print("[migrate] 完成:devices/chrome_releases/system_settings 为 MySQL 新增表,无历史数据,跳过")
return 0
if __name__ == "__main__":
sys.exit(_main())