Files
hfb_sys/scripts/clone-distribution-test-db.sh
T

39 lines
2.1 KiB
Bash
Executable File

#!/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}"