init-db.sh 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. # The Prisma CLI, the schema and the migrations live in their own folder so
  16. # the CLI's dependencies stay out of the server's node_modules (see Dockerfile).
  17. app_dir="$PWD"
  18. cd "$app_dir/tools"
  19. echo "Applying database migrations..."
  20. # Keep stderr rather than discarding it: when the retry below also fails, the
  21. # first error is the one that says why, and swallowing it left the container
  22. # dying with no reason recorded.
  23. migrate_err=$(mktemp)
  24. if ! npx prisma migrate deploy 2>"$migrate_err"; then
  25. echo "First migrate attempt failed:"
  26. sed 's/^/ /' "$migrate_err" >&2
  27. # P3005: existing DB without migration history (from db push).
  28. # Create empty migration table so migrate deploy can run.
  29. # 0_init is fully idempotent — safe on any DB state.
  30. echo "Existing database detected. Creating migration table..."
  31. 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)'
  32. npx prisma migrate deploy
  33. fi
  34. rm -f "$migrate_err"
  35. echo "Migrations applied successfully!"
  36. cd "$app_dir"
  37. # Photo embedding is the one thing here that depends on a native module, and
  38. # sharp's prebuilt binaries need an x86-64-v2 CPU. Some virtualised hosts do not
  39. # advertise one — Proxmox's default kvm64 processor model, for instance, reports
  40. # a baseline x86-64 even on modern hardware. Report it at boot rather than
  41. # leaving it to be found when a certificate comes out without its photos.
  42. # Never fatal: everything else in the app works without it.
  43. if ! sharp_error=$(node -e "require('sharp')" 2>&1); then
  44. echo "WARNING: sharp could not be loaded. Inspection certificates will render without photos."
  45. echo "$sharp_error" | sed 's/^/ /'
  46. fi
  47. echo "Starting application..."
  48. exec $cmd