init_database.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.7 sqlx-cli --no-default-features --features postgres"
  14. echo >&2 "to install it."
  15. exit 1
  16. fi
  17. source env.sh
  18. if [[ -z "${SKIP_DOCKER}" ]]
  19. then
  20. RUNNING_POSTGRES_CONTAINER=$(docker ps --filter 'name=postgres' --format '{{.ID}}')
  21. if [[ -n $RUNNING_POSTGRES_CONTAINER ]]; then
  22. echo >&2 "there is a postgres container already running, kill it with"
  23. echo >&2 " docker kill ${RUNNING_POSTGRES_CONTAINER}"
  24. exit 1
  25. fi
  26. docker run \
  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. --name "postgres_$(date '+%s')" \
  33. postgres -N 1000
  34. fi
  35. # Keep pinging Postgres until it's ready to accept commands
  36. until PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -U "${DB_USER}" -p "${DB_PORT}" -d "postgres" -c '\q'; do
  37. >&2 echo "Postgres is still unavailable - sleeping"
  38. sleep 1
  39. done
  40. >&2 echo "Postgres is up and running on port ${DB_PORT} - running migrations now!"
  41. export DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}
  42. sqlx database create
  43. sqlx migrate run
  44. >&2 echo "Postgres has been migrated, ready to go!"