Files
syops/backend/scripts/ci_check_migrations.sh
2026-03-29 11:45:36 +08:00

81 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
MIGRATIONS_DIR="${BACKEND_DIR}/migrations/versions"
FLASK_BIN="${BACKEND_DIR}/venv/bin/flask"
PYTHON_BIN="${BACKEND_DIR}/venv/bin/python3"
BASELINE_DB="${BACKEND_DIR}/local_test.db"
if [[ ! -x "${FLASK_BIN}" ]]; then
echo "[ci-check] missing flask executable: ${FLASK_BIN}"
exit 2
fi
if [[ ! -x "${PYTHON_BIN}" ]]; then
echo "[ci-check] missing python executable: ${PYTHON_BIN}"
exit 2
fi
TMP_DB="/tmp/hxops_ci_migration_${RANDOM}_$$.db"
TMP_LOG="/tmp/hxops_ci_migration_${RANDOM}_$$.log"
BEFORE_LIST="/tmp/hxops_ci_before_${RANDOM}_$$.txt"
AFTER_LIST="/tmp/hxops_ci_after_${RANDOM}_$$.txt"
cleanup() {
rm -f "${TMP_DB}" "${TMP_LOG}" "${BEFORE_LIST}" "${AFTER_LIST}"
}
trap cleanup EXIT
cd "${BACKEND_DIR}"
find "${MIGRATIONS_DIR}" -maxdepth 1 -type f -name "*.py" | sort > "${BEFORE_LIST}"
export DATABASE_URL="sqlite:///${TMP_DB}"
echo "[ci-check] DATABASE_URL=${DATABASE_URL}"
if [[ -f "${BASELINE_DB}" ]]; then
echo "[ci-check] step0: seed temp db from baseline local_test.db"
cp "${BASELINE_DB}" "${TMP_DB}"
else
echo "[ci-check] step0: baseline local_test.db not found, using empty temp db"
fi
echo "[ci-check] step1: upgrade temp db to head"
if ! "${FLASK_BIN}" --app manage.py db upgrade; then
echo "[ci-check] db upgrade failed."
if [[ -f "${BASELINE_DB}" ]]; then
echo "[ci-check] baseline exists but upgrade still failed. Please inspect migration chain."
else
echo "[ci-check] this repo's historical migrations may not support empty-db bootstrap."
echo "[ci-check] add/commit backend/local_test.db as baseline, or fix early revisions."
fi
exit 1
fi
echo "[ci-check] step2: schema drift check"
"${PYTHON_BIN}" scripts/check_schema_drift.py --database-url "${DATABASE_URL}"
echo "[ci-check] step3: autogenerate dry-check"
if ! "${FLASK_BIN}" --app manage.py db migrate -m "__ci_drift_check__" > "${TMP_LOG}" 2>&1; then
cat "${TMP_LOG}"
echo "[ci-check] migrate command failed."
exit 1
fi
find "${MIGRATIONS_DIR}" -maxdepth 1 -type f -name "*.py" | sort > "${AFTER_LIST}"
NEW_FILES="$(comm -13 "${BEFORE_LIST}" "${AFTER_LIST}" || true)"
if [[ -n "${NEW_FILES}" ]]; then
echo "[ci-check] DRIFT: autogenerate produced new migration(s):"
echo "${NEW_FILES}"
while IFS= read -r f; do
[[ -z "${f}" ]] && continue
rm -f "${f}"
done <<< "${NEW_FILES}"
echo "[ci-check] removed temporary generated migration file(s); please add a real migration."
exit 1
fi
echo "[ci-check] OK: no schema drift detected."