added database setup script

This commit is contained in:
Brian Bjarke Jensen
2025-10-27 00:03:05 +01:00
parent fa837d2380
commit b007e6183b
2 changed files with 83 additions and 0 deletions
+41
View File
@@ -0,0 +1,41 @@
name: Database Setup Automation
on:
# Trigger the workflow manually from the Gitea UI
workflow_dispatch:
jobs:
create_db_and_user:
# Use a standard Linux runner environment
runs-on: ubuntu-latest
# NOTE: The job will run inside a Docker image with the psql client.
container:
image: postgres:15-alpine
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Configure and Create PostgreSQL Resources
# Set environment variables from the Gitea Secrets
env:
POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }}
POSTGRES_PORT: ${{ secrets.POSTGRES_PORT }}
POSTGRES_ADMIN_USER: ${{ secrets.POSTGRES_ADMIN_USER }}
POSTGRES_ADMIN_PASSWORD: ${{ secrets.POSTGRES_ADMIN_PASSWORD }}
NEW_DB_NAME: ${{ secrets.NEW_DB_NAME }}
NEW_DB_USER: ${{ secrets.NEW_DB_USER }}
NEW_DB_PASSWORD: ${{ secrets.NEW_DB_PASSWORD }}
run: |
echo "Running database creation script..."
# Export the admin password so psql can use it automatically
export PGPASSWORD=$POSTGRES_ADMIN_PASSWORD
# Execute the script
./scripts/create_db_user.sh
# Unset the password variable for security
unset PGPASSWORD
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
set -e # Exit immediately if a command exits with a non-zero status.
# --- 1. Set up Connection Variables ---
HOST=$POSTGRES_HOST
PORT=$POSTGRES_PORT
DB_NAME=$NEW_DB_NAME
DB_USER=$NEW_DB_USER
DB_PASSWORD=$NEW_DB_PASSWORD
# --- 2. Build the SQL Commands ---
# NOTE: The IF NOT EXISTS ensures the script can be run safely multiple times.
SQL_COMMANDS=$(cat <<-END_SQL
-- Create user role with login and password
DO
\$body\$
BEGIN
IF NOT EXISTS (
SELECT
FROM pg_catalog.pg_user
WHERE usename = '$DB_USER') THEN
CREATE ROLE $DB_USER WITH LOGIN PASSWORD '$DB_PASSWORD';
END IF;
END
\$body\$;
-- Create database owned by the new user (if it doesn't exist)
SELECT 'CREATE DATABASE $DB_NAME OWNER $DB_USER'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME')\gexec
END_SQL
)
# --- 3. Execute the SQL Commands ---
echo "Attempting to connect to $HOST to execute SQL..."
echo "$SQL_COMMANDS" | psql \
--host=$HOST \
--port=$PORT \
--username=$POSTGRES_ADMIN_USER \
--dbname=postgres \
--set ON_ERROR_STOP=on
echo "PostgreSQL database '$DB_NAME' and user '$DB_USER' created/verified successfully."