#!/bin/sh -eux
db="$1"
owner="${2:-$db}"
-sudo -u postgres psql template1 -a -f - <<-EOF
- \set ON_ERROR_STOP on
- DO LANGUAGE plpgsql \$\$
- BEGIN
- IF NOT EXISTS (
- SELECT *
- FROM pg_catalog.pg_user
- WHERE usename = '$owner'
- LIMIT 1
- ) THEN
- CREATE ROLE $owner
- LOGIN
- NOCREATEDB
- NOCREATEROLE
- NOINHERIT
- NOSUPERUSER;
- END IF;
- END;
- \$\$;
- EOF
case $(sudo -u postgres psql template1 -t -c \
- "SELECT datname FROM pg_catalog.pg_database WHERE datname = '$db' LIMIT 1") in
+ "SELECT datname
+ FROM pg_catalog.pg_database
+ WHERE datname = '$db'
+ LIMIT 1"
+ ) in
(" $db") true;;
(*)
- sudo -u postgres psql template1 -a -f - <<-EOF
- \set ON_ERROR_STOP on
+ sudo -u postgres psql template1 -a -f - --set ON_ERROR_STOP=1 <<-EOF
CREATE DATABASE $db WITH OWNER=$owner;
EOF
;;
esac
-sudo -u postgres psql template1 -a -f - <<-EOF
- \set ON_ERROR_STOP on
+sudo -u postgres psql template1 -a -f - --set ON_ERROR_STOP=1 <<-EOF
REVOKE ALL ON DATABASE $db FROM public;
EOF
-sudo -u postgres psql "$db" -a -f - <<-EOF
- \set ON_ERROR_STOP on
+sudo -u postgres psql "$db" -a -f - --set ON_ERROR_STOP=1 <<-EOF
GRANT ALL ON SCHEMA public TO $owner WITH GRANT OPTION;
EOF