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
This commit is contained in:
Hrishikesh 2021-06-29 01:46:54 +05:30 committed by GitHub
parent ac7f26d210
commit 84385cbf2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
}