97 lines
2.5 KiB
Bash
Executable File
97 lines
2.5 KiB
Bash
Executable File
#!/bin/bash
|
|
# Database Restore Script for Coolify
|
|
# Restores PostgreSQL database from backup
|
|
|
|
set -e
|
|
|
|
BACKUP_DIR="${1:-backups/latest}"
|
|
|
|
if [ ! -d "$BACKUP_DIR" ]; then
|
|
echo "❌ Error: Backup directory not found: $BACKUP_DIR"
|
|
echo "Usage: $0 [backup_directory]"
|
|
exit 1
|
|
fi
|
|
|
|
# Load environment variables
|
|
if [ -f .env.production ]; then
|
|
export $(cat .env.production | grep -v '^#' | xargs)
|
|
elif [ -f .env.local ]; then
|
|
export $(cat .env.local | grep -v '^#' | xargs)
|
|
fi
|
|
|
|
# Get DATABASE_URL
|
|
DB_URL="${RUNTIME_DATABASE_URL:-$DATABASE_URL}"
|
|
|
|
if [ -z "$DB_URL" ]; then
|
|
echo "❌ Error: DATABASE_URL or RUNTIME_DATABASE_URL not set"
|
|
exit 1
|
|
fi
|
|
|
|
# Extract connection details
|
|
DB_NAME=$(echo $DB_URL | sed -n 's/.*\/\([^?]*\).*/\1/p')
|
|
DB_USER=$(echo $DB_URL | sed -n 's/.*:\/\/\([^:]*\):.*/\1/p')
|
|
DB_PASS=$(echo $DB_URL | sed -n 's/.*:\/\/[^:]*:\([^@]*\)@.*/\1/p')
|
|
DB_HOST=$(echo $DB_URL | sed -n 's/.*@\([^:]*\):.*/\1/p')
|
|
DB_PORT=$(echo $DB_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p' || echo "5432")
|
|
|
|
echo "🔄 Restoring database..."
|
|
echo " Host: $DB_HOST"
|
|
echo " Port: $DB_PORT"
|
|
echo " Database: $DB_NAME"
|
|
echo " User: $DB_USER"
|
|
echo " Backup: $BACKUP_DIR"
|
|
|
|
# Check if full_dump.sql exists
|
|
if [ -f "$BACKUP_DIR/full_dump.sql" ]; then
|
|
echo "📦 Restoring from full dump..."
|
|
PGPASSWORD="$DB_PASS" psql \
|
|
-h "$DB_HOST" \
|
|
-p "$DB_PORT" \
|
|
-U "$DB_USER" \
|
|
-d "$DB_NAME" \
|
|
-f "$BACKUP_DIR/full_dump.sql"
|
|
else
|
|
echo "📋 Restoring schema..."
|
|
if [ -f "$BACKUP_DIR/schema.sql" ]; then
|
|
PGPASSWORD="$DB_PASS" psql \
|
|
-h "$DB_HOST" \
|
|
-p "$DB_PORT" \
|
|
-U "$DB_USER" \
|
|
-d "$DB_NAME" \
|
|
-f "$BACKUP_DIR/schema.sql"
|
|
fi
|
|
|
|
echo "💾 Restoring data..."
|
|
if [ -f "$BACKUP_DIR/data.sql" ]; then
|
|
PGPASSWORD="$DB_PASS" psql \
|
|
-h "$DB_HOST" \
|
|
-p "$DB_PORT" \
|
|
-U "$DB_USER" \
|
|
-d "$DB_NAME" \
|
|
-f "$BACKUP_DIR/data.sql"
|
|
fi
|
|
fi
|
|
|
|
# Run Prisma migrations if migrations directory exists
|
|
if [ -d "$BACKUP_DIR/migrations" ]; then
|
|
echo "🔄 Running Prisma migrations..."
|
|
# Copy migrations temporarily
|
|
TEMP_MIGRATIONS="prisma/migrations.backup"
|
|
if [ -d "prisma/migrations" ]; then
|
|
mv prisma/migrations "$TEMP_MIGRATIONS"
|
|
fi
|
|
cp -r "$BACKUP_DIR/migrations" prisma/
|
|
|
|
# Run migrations
|
|
npx prisma migrate deploy || echo "⚠️ Migration deploy failed, trying db push..."
|
|
npx prisma db push || echo "⚠️ DB push failed"
|
|
|
|
# Restore original migrations
|
|
if [ -d "$TEMP_MIGRATIONS" ]; then
|
|
rm -rf prisma/migrations
|
|
mv "$TEMP_MIGRATIONS" prisma/migrations
|
|
fi
|
|
fi
|
|
|
|
echo "✅ Restore complete!"
|