diff --git a/README.md b/README.md index 8c74d0e..6cd164d 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,13 @@ npm run dev - [接口规划](docs/api.md) - [业务规则](docs/business-rules.md) - [分销网管理后台设计方案](docs/分销网管理后台设计方案.md) + +### 分销独立测试库 + +启动 MySQL 后,可将当前开发库复制到独立测试库 `hfb_sys_distribution_test`,源库保持不变: + +```bash +./scripts/clone-distribution-test-db.sh +``` + +脚本支持通过 `SOURCE_MYSQL_*` 和 `TEST_MYSQL_*` 环境变量指定源库、目标库连接。测试配置模板见 `backend/.env.distribution-test.example`。 diff --git a/scripts/clone-distribution-test-db.sh b/scripts/clone-distribution-test-db.sh new file mode 100755 index 0000000..8b946af --- /dev/null +++ b/scripts/clone-distribution-test-db.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail + +# 将当前 MySQL 数据库复制到独立测试库。源库只读,导入不会修改源库。 +# 可通过环境变量覆盖连接:SOURCE_MYSQL_HOST/PORT/USER/PASSWORD/DATABASE、TEST_MYSQL_*。 + +source_host="${SOURCE_MYSQL_HOST:-127.0.0.1}" +source_port="${SOURCE_MYSQL_PORT:-13306}" +source_user="${SOURCE_MYSQL_USER:-hfb}" +source_password="${SOURCE_MYSQL_PASSWORD:-secret}" +source_database="${SOURCE_MYSQL_DATABASE:-hfb_sys}" +test_host="${TEST_MYSQL_HOST:-127.0.0.1}" +test_port="${TEST_MYSQL_PORT:-13306}" +test_user="${TEST_MYSQL_USER:-hfb}" +test_password="${TEST_MYSQL_PASSWORD:-secret}" +test_database="${TEST_MYSQL_DATABASE:-hfb_sys_distribution_test}" +dump_file="${DISTRIBUTION_TEST_DUMP:-${TMPDIR:-/tmp}/hfb-distribution-${source_database}.sql}" + +for command in mysqldump mysql; do + command -v "${command}" >/dev/null || { printf '缺少命令: %s\n' "${command}" >&2; exit 127; } +done +[[ "${test_database}" =~ ^[A-Za-z0-9_]+$ ]] || { printf '测试库名称不合法\n' >&2; exit 2; } + +printf '导出源库 %s:%s/%s -> %s\n' "${source_host}" "${source_port}" "${source_database}" "${dump_file}" +MYSQL_PWD="${source_password}" mysqldump \ + --host="${source_host}" --port="${source_port}" --user="${source_user}" \ + --single-transaction --routines --triggers --events --hex-blob \ + "${source_database}" >"${dump_file}" + +printf '重建独立测试库 %s:%s/%s\n' "${test_host}" "${test_port}" "${test_database}" +MYSQL_PWD="${test_password}" mysql --host="${test_host}" --port="${test_port}" --user="${test_user}" \ + -e "DROP DATABASE IF EXISTS \`${test_database}\`; CREATE DATABASE \`${test_database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" + +printf '导入测试库并完成校验\n' +MYSQL_PWD="${test_password}" mysql --host="${test_host}" --port="${test_port}" --user="${test_user}" "${test_database}" <"${dump_file}" +MYSQL_PWD="${test_password}" mysql --host="${test_host}" --port="${test_port}" --user="${test_user}" "${test_database}" \ + -N -B -e "SELECT COUNT(*) AS table_count FROM information_schema.tables WHERE table_schema='${test_database}';" +printf '测试库已就绪: %s\n' "${test_database}"