From 905b4f87db83362ba7b29eaf7c92b6a0b98fb34d Mon Sep 17 00:00:00 2001 From: vijay Date: Fri, 9 Jan 2026 01:52:25 +0000 Subject: [PATCH] Add postgres_new_db_user --- postgres_new_db_user | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 postgres_new_db_user diff --git a/postgres_new_db_user b/postgres_new_db_user new file mode 100644 index 0000000..3ab66ea --- /dev/null +++ b/postgres_new_db_user @@ -0,0 +1,49 @@ +#!/usr/bin/env bash + +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."