fix(sql): fix sql script

This commit is contained in:
2026-01-31 11:11:55 +08:00
parent ce12b997f4
commit d071e1a27d
32 changed files with 1687 additions and 133 deletions

74
scripts/db/migrate.sh Normal file
View File

@@ -0,0 +1,74 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
load_database_url_from_env_file() {
local env_file="$1"
local line value
while IFS= read -r line || [[ -n "${line}" ]]; do
line="${line#"${line%%[![:space:]]*}"}"
[[ -z "${line}" || "${line}" == \#* ]] && continue
line="${line#export }"
if [[ "${line}" == DATABASE_URL=* ]]; then
value="${line#DATABASE_URL=}"
value="${value%$'\r'}"
value="${value%\"}"
value="${value#\"}"
value="${value%\'}"
value="${value#\'}"
printf '%s' "${value}"
return 0
fi
done < "${env_file}"
return 1
}
DATABASE_URL="${DATABASE_URL:-}"
if [[ -z "${DATABASE_URL}" && -f "${ROOT_DIR}/.env" ]]; then
DATABASE_URL="$(load_database_url_from_env_file "${ROOT_DIR}/.env" || true)"
fi
if [[ -z "${DATABASE_URL}" ]]; then
echo "DATABASE_URL is required (export it, or set it in ${ROOT_DIR}/.env)"
exit 1
fi
if ! command -v psql >/dev/null 2>&1; then
echo "psql not found in PATH"
exit 127
fi
TARGET_VERSION="${TARGET_VERSION:-}"
DRY_RUN="${DRY_RUN:-0}"
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -c "CREATE TABLE IF NOT EXISTS iam_schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())"
shopt -s nullglob
migrations=( "${SCRIPT_DIR}/migrations/"*.sql )
if [[ ${#migrations[@]} -eq 0 ]]; then
echo "No migration files found: ${SCRIPT_DIR}/migrations/*.sql"
exit 1
fi
for file in "${migrations[@]}"; do
base="$(basename "${file}")"
version="${base%%_*}"
if [[ -n "${TARGET_VERSION}" && "${version}" > "${TARGET_VERSION}" ]]; then
continue
fi
applied="$(psql "${DATABASE_URL}" -At -c "SELECT 1 FROM iam_schema_migrations WHERE version='${version}' LIMIT 1" || true)"
if [[ "${applied}" == "1" ]]; then
continue
fi
echo "Applying ${version} (${base})"
if [[ "${DRY_RUN}" == "1" ]]; then
continue
fi
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -f "${file}"
psql "${DATABASE_URL}" -v ON_ERROR_STOP=1 -c "INSERT INTO iam_schema_migrations(version) VALUES ('${version}') ON CONFLICT DO NOTHING"
done
echo "Migrations completed"