|
|
@@ -261,7 +261,15 @@ MYSQL_PWD={shlex.quote(require_env('PROD_MYSQL_PASS'))} {SOURCE_DUMP} \
|
|
|
log(f"旧生产 {source_db} 快照完成;导入输出 {len(load_out or b'')} 字节")
|
|
|
|
|
|
|
|
|
-def clone_database(source_db: str, destination_db: str) -> None:
|
|
|
+def drop_database(name: str) -> None:
|
|
|
+ if database_exists(name):
|
|
|
+ mysql(f"DROP DATABASE `{name}`;")
|
|
|
+ log(f"已删除可重建的影子库:{name}")
|
|
|
+
|
|
|
+
|
|
|
+def clone_database(source_db: str, destination_db: str, *, replace: bool = False) -> None:
|
|
|
+ if replace:
|
|
|
+ drop_database(destination_db)
|
|
|
create_empty_database(destination_db)
|
|
|
dump_cmd = ["docker", "exec", "-e", "MYSQL_PWD", MYSQL_CONTAINER, "mysqldump",
|
|
|
"-uroot", "--single-transaction", "--quick", "--skip-lock-tables",
|
|
|
@@ -391,17 +399,27 @@ def all_base_tables(schema: str) -> list[str]:
|
|
|
|
|
|
|
|
|
def build_scope_tables() -> None:
|
|
|
- for table in ("_legacy_scope_website", "_legacy_scope_nav", "_legacy_scope_article", "_legacy_scope_template"):
|
|
|
+ for table in ("_legacy_scope_website", "_legacy_scope_nav", "_legacy_scope_article",
|
|
|
+ "_legacy_scope_template", "_legacy_article_map"):
|
|
|
mysql(f"DROP TABLE IF EXISTS `{table}`;", SWITCH_APPS)
|
|
|
mysql(
|
|
|
"CREATE TABLE _legacy_scope_website (id INT PRIMARY KEY);"
|
|
|
"CREATE TABLE _legacy_scope_nav (id INT PRIMARY KEY);"
|
|
|
"CREATE TABLE _legacy_scope_article (id INT PRIMARY KEY);"
|
|
|
- "CREATE TABLE _legacy_scope_template (id INT PRIMARY KEY);", SWITCH_APPS)
|
|
|
+ "CREATE TABLE _legacy_scope_template (id INT PRIMARY KEY);"
|
|
|
+ "CREATE TABLE _legacy_article_map (old_id INT PRIMARY KEY, new_id INT NOT NULL UNIQUE);", SWITCH_APPS)
|
|
|
mysql(f"INSERT INTO _legacy_scope_website SELECT websiteid FROM {LEGACY_APPS}.website;", SWITCH_APPS)
|
|
|
mysql(f"INSERT INTO _legacy_scope_nav SELECT navigationid FROM {LEGACY_APPS}.website_navigation;", SWITCH_APPS)
|
|
|
mysql(f"INSERT INTO _legacy_scope_article SELECT articleid FROM {LEGACY_APPS}.article;", SWITCH_APPS)
|
|
|
mysql(f"INSERT INTO _legacy_scope_template SELECT wtid FROM {LEGACY_APPS}.website_template;", SWITCH_APPS)
|
|
|
+ mysql(
|
|
|
+ "SET @next_article_id := (SELECT COALESCE(MAX(articleid),0) FROM article);"
|
|
|
+ "INSERT INTO _legacy_article_map (old_id,new_id) "
|
|
|
+ "SELECT l.articleid, (@next_article_id := @next_article_id + 1) "
|
|
|
+ f"FROM {LEGACY_APPS}.article l JOIN article t ON t.articleid=l.articleid "
|
|
|
+ "WHERE t.websiteid NOT IN (SELECT id FROM _legacy_scope_website) "
|
|
|
+ "ORDER BY l.articleid;", SWITCH_APPS)
|
|
|
+ log("已为与 HXCS 新站冲突的旧文章分配影子库新 ID:" + str(mysql("SELECT COUNT(*) FROM _legacy_article_map;", SWITCH_APPS).strip()))
|
|
|
|
|
|
|
|
|
def table_is_scoped(table: str, cols: set[str]) -> bool:
|
|
|
@@ -412,19 +430,17 @@ def scoped_delete_sql(table: str, cols: set[str], schema: str) -> str:
|
|
|
qtable = f"`{schema}`.`{table}`"
|
|
|
if "websiteid" in cols:
|
|
|
return f"DELETE FROM {qtable} WHERE websiteid IN (SELECT id FROM `{schema}`._legacy_scope_website);"
|
|
|
- if "wtid" in cols:
|
|
|
- return f"DELETE FROM {qtable} WHERE wtid IN (SELECT id FROM `{schema}`._legacy_scope_template);"
|
|
|
+ if "articleid" in cols:
|
|
|
+ return (f"DELETE t FROM {qtable} t LEFT JOIN `{schema}`.article a "
|
|
|
+ f"ON a.articleid=t.articleid WHERE a.websiteid IN "
|
|
|
+ f"(SELECT id FROM `{schema}`._legacy_scope_website);")
|
|
|
if "navigationid" in cols:
|
|
|
return (f"DELETE t FROM {qtable} t LEFT JOIN `{schema}`.website_navigation n "
|
|
|
- f"ON n.navigationid=t.navigationid WHERE t.navigationid IN "
|
|
|
- f"(SELECT id FROM `{schema}`._legacy_scope_nav) OR n.websiteid IN "
|
|
|
+ f"ON n.navigationid=t.navigationid WHERE n.websiteid IN "
|
|
|
f"(SELECT id FROM `{schema}`._legacy_scope_website) OR n.wtid IN "
|
|
|
f"(SELECT id FROM `{schema}`._legacy_scope_template);")
|
|
|
- if "articleid" in cols:
|
|
|
- return (f"DELETE t FROM {qtable} t LEFT JOIN `{schema}`.article a "
|
|
|
- f"ON a.articleid=t.articleid WHERE t.articleid IN "
|
|
|
- f"(SELECT id FROM `{schema}`._legacy_scope_article) OR a.websiteid IN "
|
|
|
- f"(SELECT id FROM `{schema}`._legacy_scope_website);")
|
|
|
+ if "wtid" in cols:
|
|
|
+ return f"DELETE FROM {qtable} WHERE wtid IN (SELECT id FROM `{schema}`._legacy_scope_template);"
|
|
|
return ""
|
|
|
|
|
|
|
|
|
@@ -446,38 +462,70 @@ def merge_legacy_into_shadow() -> dict:
|
|
|
if not common:
|
|
|
raise JobError(f"表 {table} 无同名字段")
|
|
|
keys = primary_columns(LEGACY_APPS, table) or unique_index_columns(LEGACY_APPS, table)
|
|
|
+ cols_sql = ",".join(f"`{c}`" for c in common)
|
|
|
if table_is_scoped(table, set(common)):
|
|
|
direct.append(table)
|
|
|
+ select_exprs = []
|
|
|
+ if table == "article_copy" and "article_copyid" in common:
|
|
|
+ select_exprs.append("(@next_article_copy_id := @next_article_copy_id + 1)")
|
|
|
+ else:
|
|
|
+ select_exprs.append("`article_copyid`" if "article_copyid" in common else None)
|
|
|
+ for col in common:
|
|
|
+ if col == "article_copyid" and table == "article_copy":
|
|
|
+ continue
|
|
|
+ if col == "articleid":
|
|
|
+ expr = f"COALESCE(article_map.new_id,l.`{col}`)"
|
|
|
+ else:
|
|
|
+ expr = f"l.`{col}`"
|
|
|
+ select_exprs.append(expr)
|
|
|
+ select_sql = ",".join(x for x in select_exprs if x)
|
|
|
+ join_sql = ""
|
|
|
+ if "articleid" in common:
|
|
|
+ join_sql = (f" LEFT JOIN `{SWITCH_APPS}`._legacy_article_map article_map "
|
|
|
+ f"ON article_map.old_id=l.articleid")
|
|
|
+ scoped_inserts.append(
|
|
|
+ f"INSERT INTO `{SWITCH_APPS}`.`{table}` ({cols_sql}) SELECT {select_sql} "
|
|
|
+ f"FROM `{LEGACY_APPS}`.`{table}` l{join_sql};")
|
|
|
else:
|
|
|
if not keys:
|
|
|
raise JobError(f"全局表 {table} 无主键或唯一键,不能安全合并")
|
|
|
update = ",".join(f"`{c}`=VALUES(`{c}`)" for c in common)
|
|
|
- cols_sql = ",".join(f"`{c}`" for c in common)
|
|
|
global_upserts.append(
|
|
|
f"INSERT INTO `{SWITCH_APPS}`.`{table}` ({cols_sql}) SELECT {cols_sql} "
|
|
|
f"FROM `{LEGACY_APPS}`.`{table}` ON DUPLICATE KEY UPDATE {update};")
|
|
|
- cols_sql = ",".join(f"`{c}`" for c in common)
|
|
|
- scoped_inserts.append(
|
|
|
- f"INSERT INTO `{SWITCH_APPS}`.`{table}` ({cols_sql}) SELECT {cols_sql} "
|
|
|
- f"FROM `{LEGACY_APPS}`.`{table}`;")
|
|
|
report[table] = {"columns": len(common), "scoped": table_is_scoped(table, set(common))}
|
|
|
- statements = ["SET NAMES utf8mb4;", "SET FOREIGN_KEY_CHECKS=0;", "START TRANSACTION;"]
|
|
|
+ statements = ["SET NAMES utf8mb4;", "SET FOREIGN_KEY_CHECKS=0;", "START TRANSACTION;",
|
|
|
+ f"SET @next_article_copy_id := (SELECT COALESCE(MAX(article_copyid),0) FROM `{SWITCH_APPS}`.article_copy);"]
|
|
|
for table in direct:
|
|
|
if table not in special:
|
|
|
sql = scoped_delete_sql(table, set(source_columns(LEGACY_APPS, table)), SWITCH_APPS)
|
|
|
if sql:
|
|
|
statements.append(sql)
|
|
|
+ support_tables = {"article_classify_manage", "website_manage",
|
|
|
+ "website_navigation_manage", "website_statistics"}
|
|
|
+ for table in support_tables & set(direct):
|
|
|
+ keys = primary_columns(LEGACY_APPS, table)
|
|
|
+ if len(keys) == 1:
|
|
|
+ key = keys[0]
|
|
|
+ statements.append(
|
|
|
+ f"DELETE t FROM `{SWITCH_APPS}`.`{table}` t JOIN `{LEGACY_APPS}`.`{table}` s "
|
|
|
+ f"ON s.`{key}`=t.`{key}`;")
|
|
|
statements.append("DELETE FROM `" + SWITCH_APPS + "`.article WHERE websiteid IN "
|
|
|
f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website);")
|
|
|
statements.append("DELETE FROM `" + SWITCH_APPS + "`.website_navigation WHERE websiteid IN "
|
|
|
f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website) OR wtid IN "
|
|
|
- f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_template);")
|
|
|
+ f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_template) OR navigationid IN "
|
|
|
+ f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_nav);")
|
|
|
statements.append("DELETE FROM `" + SWITCH_APPS + "`.website_template WHERE wtid IN "
|
|
|
f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_template);")
|
|
|
statements.append("DELETE FROM `" + SWITCH_APPS + "`.website WHERE websiteid IN "
|
|
|
f"(SELECT id FROM `{SWITCH_APPS}`._legacy_scope_website);")
|
|
|
statements.extend(global_upserts)
|
|
|
statements.extend(scoped_inserts)
|
|
|
+ statements.append(
|
|
|
+ f"UPDATE `{SWITCH_APPS}`.apply a JOIN `{SWITCH_APPS}`._legacy_article_map m "
|
|
|
+ "ON a.table_name IN ('article','ARTICLE') AND a.table_key='articleid' "
|
|
|
+ "AND a.table_key_value=CAST(m.old_id AS CHAR) SET a.table_key_value=CAST(m.new_id AS CHAR);")
|
|
|
statements.extend(["COMMIT;", "SET FOREIGN_KEY_CHECKS=1;"])
|
|
|
sql_path = REPORT_DIR / "merge.sql"
|
|
|
sql_path.write_text("\n".join(statements) + "\n", encoding="utf-8")
|
|
|
@@ -540,9 +588,9 @@ def protected_fingerprint(db: str, protected_ids: list[int]) -> dict:
|
|
|
"row_counts": {k: len(v) for k, v in data.items()}}
|
|
|
|
|
|
|
|
|
-def build_shadow() -> None:
|
|
|
- clone_database(TARGET_CORE, SWITCH_CORE)
|
|
|
- clone_database(TARGET_APPS, SWITCH_APPS)
|
|
|
+def build_shadow(*, replace: bool = False) -> None:
|
|
|
+ clone_database(TARGET_CORE, SWITCH_CORE, replace=replace)
|
|
|
+ clone_database(TARGET_APPS, SWITCH_APPS, replace=replace)
|
|
|
pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
|
|
|
atomic_json(PROTECTED_BEFORE, protected_fingerprint(TARGET_APPS, pre["protected_websites"]))
|
|
|
build_scope_tables()
|
|
|
@@ -555,6 +603,21 @@ def build_shadow() -> None:
|
|
|
raise JobError("HXCS 新建网站数据指纹发生变化,停止")
|
|
|
|
|
|
|
|
|
+def merge_shadow_existing() -> None:
|
|
|
+ pre = json.loads((REPORT_DIR / "preflight.json").read_text(encoding="utf-8"))
|
|
|
+ if not database_exists(SWITCH_CORE) or not database_exists(SWITCH_APPS):
|
|
|
+ raise JobError("shadow databases missing")
|
|
|
+ atomic_json(PROTECTED_BEFORE, protected_fingerprint(TARGET_APPS, pre["protected_websites"]))
|
|
|
+ build_scope_tables()
|
|
|
+ merge_legacy_into_shadow()
|
|
|
+ merge_core_tables()
|
|
|
+ after = protected_fingerprint(SWITCH_APPS, pre["protected_websites"])
|
|
|
+ atomic_json(REPORT_DIR / "protected-after.json", after)
|
|
|
+ before = json.loads(PROTECTED_BEFORE.read_text(encoding="utf-8"))
|
|
|
+ if before.get("sha256") != after.get("sha256"):
|
|
|
+ raise JobError("protected site fingerprint changed")
|
|
|
+
|
|
|
+
|
|
|
def normalize_path(value: str) -> str | None:
|
|
|
value = unquote(value.strip())
|
|
|
if not value or value.startswith(("#", "javascript:", "mailto:", "data:")):
|
|
|
@@ -733,14 +796,60 @@ def verify_database() -> dict:
|
|
|
keys = primary_columns(LEGACY_APPS, table) or unique_index_columns(LEGACY_APPS, table)
|
|
|
if not keys:
|
|
|
continue
|
|
|
- join = " AND ".join(f"d.`{k}`=s.`{k}`" for k in keys)
|
|
|
- compare = " OR ".join(f"NOT (d.`{c}` <=> s.`{c}`)" for c in common)
|
|
|
- missing = int(mysql(
|
|
|
- f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s LEFT JOIN `{SWITCH_APPS}`.`{table}` d "
|
|
|
- f"ON {join} WHERE d.`{keys[0]}` IS NULL;").strip() or "0")
|
|
|
- different = int(mysql(
|
|
|
- f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s JOIN `{SWITCH_APPS}`.`{table}` d "
|
|
|
- f"ON {join} WHERE {compare};").strip() or "0")
|
|
|
+ if table == "article":
|
|
|
+ join = "d.articleid=COALESCE(article_map.new_id,s.articleid)"
|
|
|
+ extra_join = f" LEFT JOIN `{SWITCH_APPS}`._legacy_article_map article_map ON article_map.old_id=s.articleid"
|
|
|
+ compare = " OR ".join(
|
|
|
+ ("NOT (d.articleid <=> COALESCE(article_map.new_id,s.articleid))" if c == "articleid"
|
|
|
+ else f"NOT (d.`{c}` <=> s.`{c}`)") for c in common)
|
|
|
+ missing = int(mysql(
|
|
|
+ f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.article s LEFT JOIN `{SWITCH_APPS}`.article d "
|
|
|
+ f"ON {join}{extra_join} WHERE d.articleid IS NULL;").strip() or "0")
|
|
|
+ different = int(mysql(
|
|
|
+ f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.article s JOIN `{SWITCH_APPS}`.article d "
|
|
|
+ f"ON {join}{extra_join} WHERE {compare};").strip() or "0")
|
|
|
+ elif table == "article_copy":
|
|
|
+ join = ("d.dcode=s.dcode AND d.articleid=COALESCE(article_map.new_id,s.articleid) "
|
|
|
+ "AND d.navigationid=s.navigationid AND d.create_time=s.create_time")
|
|
|
+ extra_join = f" LEFT JOIN `{SWITCH_APPS}`._legacy_article_map article_map ON article_map.old_id=s.articleid"
|
|
|
+ compare = " OR ".join(
|
|
|
+ ("NOT (d.articleid <=> COALESCE(article_map.new_id,s.articleid))" if c == "articleid"
|
|
|
+ else f"NOT (d.`{c}` <=> s.`{c}`)") for c in common if c != "article_copyid")
|
|
|
+ missing = int(mysql(
|
|
|
+ f"SELECT COUNT(DISTINCT s.article_copyid) FROM `{LEGACY_APPS}`.article_copy s "
|
|
|
+ f"LEFT JOIN `{SWITCH_APPS}`.article_copy d ON {join}{extra_join} "
|
|
|
+ "WHERE d.article_copyid IS NULL;").strip() or "0")
|
|
|
+ different = int(mysql(
|
|
|
+ f"SELECT COUNT(DISTINCT s.article_copyid) FROM `{LEGACY_APPS}`.article_copy s "
|
|
|
+ f"JOIN `{SWITCH_APPS}`.article_copy d ON {join}{extra_join} "
|
|
|
+ f"WHERE {compare};").strip() or "0")
|
|
|
+ else:
|
|
|
+ extra_join = ""
|
|
|
+ if "articleid" in common:
|
|
|
+ join = " AND ".join(f"d.`{k}`=s.`{k}`" for k in keys)
|
|
|
+ extra_join = f" LEFT JOIN `{SWITCH_APPS}`._legacy_article_map article_map ON article_map.old_id=s.articleid"
|
|
|
+ elif table == "apply":
|
|
|
+ join = " AND ".join(f"d.`{k}`=s.`{k}`" for k in keys)
|
|
|
+ extra_join = (f" LEFT JOIN `{SWITCH_APPS}`._legacy_article_map article_map "
|
|
|
+ "ON article_map.old_id=CAST(s.table_key_value AS UNSIGNED)")
|
|
|
+ else:
|
|
|
+ join = " AND ".join(f"d.`{k}`=s.`{k}`" for k in keys)
|
|
|
+ if table == "apply":
|
|
|
+ compare = " OR ".join(
|
|
|
+ ("NOT (d.table_key_value <=> CASE WHEN s.table_name IN ('article','ARTICLE') "
|
|
|
+ "AND s.table_key='articleid' THEN CAST(COALESCE(article_map.new_id,CAST(s.table_key_value AS UNSIGNED)) AS CHAR) "
|
|
|
+ "ELSE s.table_key_value END)" if c == "table_key_value"
|
|
|
+ else f"NOT (d.`{c}` <=> s.`{c}`)") for c in common)
|
|
|
+ else:
|
|
|
+ compare = " OR ".join(
|
|
|
+ ("NOT (d.articleid <=> COALESCE(article_map.new_id,s.articleid))" if c == "articleid"
|
|
|
+ else f"NOT (d.`{c}` <=> s.`{c}`)") for c in common)
|
|
|
+ missing = int(mysql(
|
|
|
+ f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s LEFT JOIN `{SWITCH_APPS}`.`{table}` d "
|
|
|
+ f"ON {join}{extra_join} WHERE d.`{keys[0]}` IS NULL;").strip() or "0")
|
|
|
+ different = int(mysql(
|
|
|
+ f"SELECT COUNT(*) FROM `{LEGACY_APPS}`.`{table}` s JOIN `{SWITCH_APPS}`.`{table}` d "
|
|
|
+ f"ON {join}{extra_join} WHERE {compare};").strip() or "0")
|
|
|
if missing or different:
|
|
|
mismatches.append({"table": table, "missing": missing, "different": different})
|
|
|
orphan_article_nav = int(mysql(
|
|
|
@@ -883,11 +992,32 @@ def run_mode(mode: str) -> None:
|
|
|
update_status(stage="verify")
|
|
|
verify()
|
|
|
update_status(stage="complete", state="complete", finished_at=now())
|
|
|
+ elif mode == "resume":
|
|
|
+ if not (REPORT_DIR / "preflight.json").is_file():
|
|
|
+ raise JobError("缺少 preflight.json,不能断点续跑")
|
|
|
+ for db in (LEGACY_CORE, LEGACY_APPS):
|
|
|
+ if not database_exists(db):
|
|
|
+ raise JobError(f"缺少旧生产快照库:{db}")
|
|
|
+ update_status(stage="build-shadow", resumed_at=now())
|
|
|
+ build_shadow(replace=True)
|
|
|
+ update_status(stage="stage-assets")
|
|
|
+ stage_assets()
|
|
|
+ update_status(stage="verify")
|
|
|
+ verify()
|
|
|
+ update_status(stage="complete", state="complete", finished_at=now())
|
|
|
+ elif mode == "continue-merge":
|
|
|
+ update_status(stage="build-shadow", continued_at=now())
|
|
|
+ merge_shadow_existing()
|
|
|
+ update_status(stage="stage-assets")
|
|
|
+ stage_assets()
|
|
|
+ update_status(stage="verify")
|
|
|
+ verify()
|
|
|
+ update_status(stage="complete", state="complete", finished_at=now())
|
|
|
elif mode == "refresh-delta":
|
|
|
raise JobError("refresh-delta 需要在正式切换前的停写窗口另行授权后实现/执行")
|
|
|
else:
|
|
|
raise JobError(f"未知模式:{mode}")
|
|
|
- if mode != "all":
|
|
|
+ if mode not in {"all", "resume", "continue-merge"}:
|
|
|
update_status(state="complete", stage=mode, finished_at=now())
|
|
|
except Exception as exc:
|
|
|
log("任务失败:" + str(exc))
|