From e56b822ad9b702553838d6d57cd08ddd1a44d2a9 Mon Sep 17 00:00:00 2001 From: amoghjalan Date: Fri, 19 Apr 2024 17:45:36 +0530 Subject: [PATCH] Add check for database already existing --- init_db.sh | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/init_db.sh b/init_db.sh index 9f46f48ba..4fd049151 100644 --- a/init_db.sh +++ b/init_db.sh @@ -21,10 +21,15 @@ wait_for_postgres() { # Wait for PostgreSQL to become available wait_for_postgres - -su - postgres -c "psql -U postgres -c 'CREATE DATABASE \"$POSTGRES_DB\";'" -su - postgres -c "psql -U postgres -d \"$POSTGRES_DB\" -c 'GRANT ALL PRIVILEGES ON DATABASE \"$POSTGRES_DB\" TO \"$POSTGRES_USER\";'" -su - postgres -c "psql -U postgres -c 'ALTER USER \"$POSTGRES_USER\" WITH ENCRYPTED PASSWORD '\''$POSTGRES_PASSWORD'\'';'" +# Check if the database already exists +if su - postgres -c "psql -U postgres -lqt | cut -d \| -f 1 | grep -qw $POSTGRES_DB"; then + echo "Database $POSTGRES_DB already exists" +else + # Create the database if it doesn't exist + su - postgres -c "psql -U postgres -c 'CREATE DATABASE \"$POSTGRES_DB\";'" + su - postgres -c "psql -U postgres -d \"$POSTGRES_DB\" -c 'GRANT ALL PRIVILEGES ON DATABASE \"$POSTGRES_DB\" TO \"$POSTGRES_USER\";'" + su - postgres -c "psql -U postgres -c 'ALTER USER \"$POSTGRES_USER\" WITH ENCRYPTED PASSWORD '\''$POSTGRES_PASSWORD'\'';'" +fi # Construct the database URL DB_URL="postgresql://$POSTGRES_USER:$POSTGRES_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DB?sslmode=disable"