Files
supply-intelligence/scripts/run_migrations.sh
2026-05-12 18:49:52 +08:00

106 lines
3.2 KiB
Bash

#!/bin/bash
# Migration runner for supply-intelligence
# Supports both in-memory mode (no DB) and PostgreSQL mode (via DATABASE_URL)
#
# Usage:
# ./scripts/run_migrations.sh # runs all pending migrations
# ./scripts/run_migrations.sh --status # show migration status
# ./scripts/run_migrations.sh --baseline <id> # baseline an existing DB
set -e
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
MIGRATIONS_DIR="${PROJECT_DIR}/migrations"
DATABASE_URL="${DATABASE_URL:-}"
# Resolve absolute path to migrations folder
MIGRATIONS_DIR="$(cd "$MIGRATIONS_DIR" && pwd)"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERR]${NC} $*" >&2; }
run_postgres_migrations() {
if [ -z "$DATABASE_URL" ]; then
log_error "DATABASE_URL not set. Cannot run SQL migrations."
log_info "Set DATABASE_URL to run PostgreSQL migrations."
return 1
fi
local conn="$DATABASE_URL"
local db_name
db_name=$(echo "$conn" | sed -E 's|.*/([^?]+)(\?.*)?|\1|')
echo "CREATE TABLE IF NOT EXISTS schema_history (
installed_rank INTEGER PRIMARY KEY,
version VARCHAR(50),
description VARCHAR(200),
type VARCHAR(20),
script VARCHAR(1000),
checksum BIGINT,
installed_by VARCHAR(100),
installed_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
execution_time_ms BIGINT,
success SMALLINT
);" | PGPASSWORD="${PGPASSWORD:-}" psql -h "${PGHOST:-localhost}" -U "${PGUSER:-supply}" -d "$db_name" 2>/dev/null || true
log_info "PostgreSQL migration runner ready"
log_info "DB: $db_name"
log_info "Migrations dir: $MIGRATIONS_DIR"
local count=0
for f in "$MIGRATIONS_DIR"/*.sql; do
[ -e "$f" ] || continue
echo " $(basename "$f")"
count=$((count + 1))
done
log_info "Found $count SQL migration file(s)"
}
run_inmemory_migrations() {
log_info "In-memory mode: migrations are embedded in application startup"
log_info "Set DATABASE_URL to enable PostgreSQL migration runner"
echo ""
echo "Available migrations in $MIGRATIONS_DIR:"
local count=0
for f in "$MIGRATIONS_DIR"/*.sql; do
[ -e "$f" ] || continue
echo " $(basename "$f")"
count=$((count + 1))
done
log_info "Total: $count migration(s)"
}
main() {
case "${1:-}" in
--status)
if [ -n "$DATABASE_URL" ]; then
log_info "PostgreSQL mode"
run_postgres_migrations
else
log_info "In-memory mode (no DATABASE_URL)"
run_inmemory_migrations
fi
;;
--baseline)
log_warn "Baseline not implemented — use golang-migrate or flyway"
;;
*)
if [ -n "$DATABASE_URL" ]; then
log_info "Running PostgreSQL migrations..."
run_postgres_migrations
else
log_info "No DATABASE_URL — showing available migrations"
run_inmemory_migrations
fi
;;
esac
}
main "$@"