init-db.sh 1.3 KB

1234567891011121314151617181920212223242526272829303132
  1. #!/bin/bash
  2. set -e
  3. trap 'echo "An error occurred. Exiting..."; exit 1' ERR
  4. cmd="$@"
  5. # Construct DATABASE_URL from environment variables if not already set
  6. if [ -z "$DATABASE_URL" ]; then
  7. export DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
  8. fi
  9. echo "Waiting for PostgreSQL to be ready..."
  10. until pg_isready -d "$DATABASE_URL" -q; do
  11. echo "PostgreSQL is unavailable - sleeping 2s..."
  12. sleep 2
  13. done
  14. echo "PostgreSQL is ready!"
  15. echo "Applying database migrations..."
  16. if ! npx prisma migrate deploy 2>/dev/null; then
  17. # P3005: existing DB without migration history (from db push).
  18. # Create empty migration table so migrate deploy can run.
  19. # 0_init is fully idempotent — safe on any DB state.
  20. echo "Existing database detected. Creating migration table..."
  21. npx prisma db execute --stdin <<< 'CREATE TABLE IF NOT EXISTS "_prisma_migrations" ("id" VARCHAR(36) PRIMARY KEY NOT NULL, "checksum" VARCHAR(64) NOT NULL, "finished_at" TIMESTAMPTZ, "migration_name" VARCHAR(255) NOT NULL, "logs" TEXT, "rolled_back_at" TIMESTAMPTZ, "started_at" TIMESTAMPTZ NOT NULL DEFAULT now(), "applied_steps_count" INTEGER NOT NULL DEFAULT 0)'
  22. npx prisma migrate deploy
  23. fi
  24. echo "Migrations applied successfully!"
  25. echo "Starting application..."
  26. exec $cmd