run.sh 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/bin/bash
  2. set -e
  3. image="$1"
  4. export POSTGRES_USER='my cool postgres user'
  5. export POSTGRES_PASSWORD='my cool postgres password'
  6. export POSTGRES_DB='my cool postgres database'
  7. cname="postgres-container-$RANDOM-$RANDOM"
  8. cid="$(docker run -d -e POSTGRES_USER -e POSTGRES_PASSWORD -e POSTGRES_DB --name "$cname" "$image")"
  9. trap "docker rm -f $cid > /dev/null" EXIT
  10. psql() {
  11. docker run --rm -i \
  12. --link "$cname":postgres \
  13. --entrypoint psql \
  14. -e PGPASSWORD="$POSTGRES_PASSWORD" \
  15. "$image" \
  16. --host postgres \
  17. --username "$POSTGRES_USER" \
  18. --dbname "$POSTGRES_DB" \
  19. --quiet --no-align --tuples-only \
  20. "$@"
  21. }
  22. tries=10
  23. while ! echo 'SELECT 1' | psql &> /dev/null; do
  24. (( tries-- ))
  25. if [ $tries -le 0 ]; then
  26. echo >&2 'postgres failed to accept connetions in a reasonable amount of time!'
  27. echo 'SELECT 1' | psql # to hopefully get a useful error message
  28. false
  29. fi
  30. sleep 2
  31. done
  32. echo 'CREATE TABLE test (a INT, b INT, c VARCHAR(255))' | psql
  33. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 0 ]
  34. psql <<'EOSQL'
  35. INSERT INTO test VALUES (1, 2, 'hello')
  36. EOSQL
  37. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 1 ]
  38. psql <<'EOSQL'
  39. INSERT INTO test VALUES (2, 3, 'goodbye!')
  40. EOSQL
  41. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 2 ]
  42. echo 'DELETE FROM test WHERE a = 1' | psql
  43. [ "$(echo 'SELECT COUNT(*) FROM test' | psql)" = 1 ]
  44. [ "$(echo 'SELECT c FROM test' | psql)" = "goodbye!" ]
  45. echo 'DROP TABLE test' | psql