Scripts/postgres_new_db_user

51 lines
2.3 KiB
Bash

#!/usr/bin/env bash
# wget -O /tmp/postgres_new_db_user.sh https://git.technozone.com.au/vijay/Scripts/raw/branch/main/postgres_new_db_user && bash /tmp/postgres_new_db_user.sh && rm -f /tmp/postgres_new_db_user.sh
echo "=== PostgreSQL Database & User Setup ==="
read -p "Enter new database name: " DB_NAME
read -p "Enter new username: " DB_USER
read -s -p "Enter new password: " DB_PASS
echo ""
read -p "Enter PostgreSQL superuser (default: postgres): " PG_SUPER
PG_SUPER=${PG_SUPER:-postgres}
# Optional: change host/port if needed
PG_HOST="localhost"
PG_PORT="5432"
echo ""
echo "Creating user and database..."
# Create user
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -tc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER';" | grep -q 1 \
|| psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -c "CREATE ROLE $DB_USER WITH LOGIN PASSWORD '$DB_PASS';"
# Create database
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -tc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME';" | grep -q 1 \
|| psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
echo "Granting permissions..."
# Grant DB connect
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "GRANT CONNECT, TEMPORARY ON DATABASE $DB_NAME TO $DB_USER;"
# Schema permissions
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "GRANT USAGE, CREATE ON SCHEMA public TO $DB_USER;"
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "ALTER SCHEMA public OWNER TO $DB_USER;"
# Existing tables & sequences
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO $DB_USER;"
psql -U "$PG_SUPER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO $DB_USER;"
# Future tables & sequences
psql -U "$DB_USER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO $DB_USER;"
psql -U "$DB_USER" -h "$PG_HOST" -p "$PG_PORT" -d "$DB_NAME" -c "ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON SEQUENCES TO $DB_USER;"
echo ""
echo "=== Setup Complete ==="
echo "Database: $DB_NAME"
echo "User: $DB_USER"
echo "Schema owner: $DB_USER"
echo "Full R/W on existing + future tables granted."