Keep user name same as database name

This commit is contained in:
Corbin Bartsch 2022-06-24 15:06:41 -04:00
parent 4f18650f85
commit 2c047bab97
Signed by: coredotbin
GPG Key ID: 32D3B80A08D93212

View File

@ -5,14 +5,14 @@ set -u
function create_user_and_database() { function create_user_and_database() {
local dbinfo=$1 local dbinfo=$1
IFS=":" read -r database user password <<< "$dbinfo" IFS=":" read -r database password <<< "$dbinfo"
echo " Creating user and database '$database'" echo " Creating user and database '$database'"
echo "Creating database '$database' with user '$user' and password '$password'" echo "Creating database '$database' with user '$user' and password '$password'"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "postgres" <<-EOSQL psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "postgres" <<-EOSQL
SELECT 'CREATE USER ' || LOWER(TRIM('$user')) AS create_user_query WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = LOWER(TRIM('$user')));\gexec 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
ALTER USER $user WITH ENCRYPTED PASSWORD '$password'; ALTER USER $database WITH ENCRYPTED PASSWORD '$password';
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 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 $user; GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
EOSQL EOSQL
} }