#!/bin/bash # Apply database migrations automatically # This script should be run on container startup or periodically set -e POSTGRES_HOST="${POSTGRES_HOST:-db}" POSTGRES_DB="${POSTGRES_DB:-daarion}" POSTGRES_USER="${POSTGRES_USER:-postgres}" POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-postgres}" MIGRATIONS_DIR="${MIGRATIONS_DIR:-/opt/microdao-daarion/migrations}" echo "📊 Applying database migrations..." echo "Host: $POSTGRES_HOST" echo "Database: $POSTGRES_DB" echo "Migrations dir: $MIGRATIONS_DIR" # Wait for PostgreSQL to be ready echo "⏳ Waiting for PostgreSQL..." for i in {1..30}; do if PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$POSTGRES_HOST" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT 1;" > /dev/null 2>&1; then echo "✅ PostgreSQL is ready" break fi if [ $i -eq 30 ]; then echo "❌ PostgreSQL is not ready after 30 attempts" exit 1 fi sleep 1 done # Apply all migrations in order echo "📋 Applying migrations..." for migration_file in "$MIGRATIONS_DIR"/*.sql; do if [ -f "$migration_file" ]; then migration_name=$(basename "$migration_file") echo " Applying: $migration_name" # Apply migration (ignore errors for already applied migrations) PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$POSTGRES_HOST" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -f "$migration_file" 2>&1 | grep -v "already exists\|does not exist" || true fi done echo "✅ Migrations applied"