From 84385cbf2ae59e6c4f1823ddb0f2c915a251360b Mon Sep 17 00:00:00 2001 From: Hrishikesh Date: Tue, 29 Jun 2021 01:46:54 +0530 Subject: [PATCH] Exists check for database and user - Added exists check for database and user - Added `--dbname "postgres"` in `psql` command - Added owner, utf8 encoding, collate and template --- create-multiple-postgresql-databases.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/create-multiple-postgresql-databases.sh b/create-multiple-postgresql-databases.sh index aa665fa..8cedaf0 100755 --- a/create-multiple-postgresql-databases.sh +++ b/create-multiple-postgresql-databases.sh @@ -6,9 +6,9 @@ set -u function create_user_and_database() { local database=$1 echo " Creating user and database '$database'" - psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL - CREATE USER $database; - CREATE DATABASE $database; + psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "postgres" <<-EOSQL + SELECT 'CREATE USER ' || LOWER(TRIM('$database')) AS create_user_query WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = LOWER(TRIM('$database')));\gexec + SELECT 'CREATE DATABASE ' || LOWER(TRIM('$database')) || ' WITH OWNER "$POSTGRES_USER" ENCODING "UTF8" LC_COLLATE = "en_US.UTF-8" LC_CTYPE = "en_US.UTF-8" TEMPLATE="template0"' AS create_table_query WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = LOWER(TRIM('$database')));\gexec GRANT ALL PRIVILEGES ON DATABASE $database TO $database; EOSQL }