init_database.sh 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #!/usr/bin/env bash
  2. set -x
  3. set -eo pipefail
  4. if ! [ -x "$(command -v psql)" ]; then
  5. echo >&2 "Error: `psql` is not installed."
  6. echo >&2 "install using brew: brew install libpq."
  7. echo >&2 "link to /usr/local/bin: brew link --force libpq ail"
  8. exit 1
  9. fi
  10. if ! [ -x "$(command -v sqlx)" ]; then
  11. echo >&2 "Error: `sqlx` is not installed."
  12. echo >&2 "Use:"
  13. echo >&2 " cargo install --version=^0.5.6 sqlx-cli --no-default-features --features postgres"
  14. echo >&2 "to install it."
  15. exit 1
  16. fi
  17. if [[ -z "${SKIP_DOCKER}" ]]
  18. then
  19. RUNNING_POSTGRES_CONTAINER=$(docker ps --filter 'name=postgres' --format '{{.ID}}')
  20. if [[ -n $RUNNING_POSTGRES_CONTAINER ]]; then
  21. echo >&2 "there is a postgres container already running, kill it with"
  22. echo >&2 " docker kill ${RUNNING_POSTGRES_CONTAINER}"
  23. exit 1
  24. fi
  25. docker run \
  26. --name="flowy" \
  27. -e POSTGRES_USER=${DB_USER} \
  28. -e POSTGRES_PASSWORD=${DB_PASSWORD} \
  29. -e POSTGRES_DB=${DB_NAME} \
  30. -p "${DB_PORT}":5432 \
  31. -d postgres \
  32. postgres -N 1000
  33. fi
  34. # Keep pinging Postgres until it's ready to accept commands
  35. until PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do
  36. >&2 echo "Postgres is still unavailable - sleeping"
  37. sleep 1
  38. done
  39. >&2 echo "Postgres is up and running on port ${DB_PORT} - running migrations now!"
  40. export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}
  41. sqlx database create
  42. sqlx migrate run
  43. >&2 echo "Postgres has been migrated, ready to go!"