From 4c21cccae346e85022de89a040edf722897aa2f6 Mon Sep 17 00:00:00 2001 From: iwanhae Date: Mon, 31 Aug 2026 16:31:53 +0900 Subject: [PATCH] 008: personal database iwanhae owned by admin role --- README.md | 1 + migrations/008-create-db-iwanhae.sh | 47 +++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 migrations/008-create-db-iwanhae.sh diff --git a/README.md b/README.md index 101f6c5..5790193 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ For a private repo you need an auth strategy: | 005 | mount-pgdata | /dev/sdb (20G) -> /var/lib/postgresql, fstab | | 006 | install-postgres | PG 18 via PGDG repo, cluster on the disk | | 007 | postgres-admin-role | iwanhae OS user -> PG superuser (peer auth) | +| 008 | create-db-iwanhae | database `iwanhae` owned by admin role | ## Roadmap diff --git a/migrations/008-create-db-iwanhae.sh b/migrations/008-create-db-iwanhae.sh new file mode 100644 index 0000000..85c6c8e --- /dev/null +++ b/migrations/008-create-db-iwanhae.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# 008-create-db-iwanhae - Create the personal database `iwanhae` owned by +# the admin role from 007, so plain `psql` works without -d. +# up: CREATE DATABASE iwanhae OWNER iwanhae (skip if it already exists) +# down: DROP DATABASE - refuses while it contains user objects (data safety) +set -euo pipefail + +DB=iwanhae +ROLE=iwanhae + +db_exists() { + runuser -u postgres -- psql -v ON_ERROR_STOP=1 -tAc \ + "SELECT 1 FROM pg_database WHERE datname='$DB'" | grep -q 1 +} + +user_object_count() { + runuser -u postgres -- psql -v ON_ERROR_STOP=1 -d "$DB" -tAc \ + "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') + AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')" | tr -d ' ' +} + +case "${1:-}" in + up) + if db_exists; then + echo " database $DB already exists - skipping" + else + runuser -u postgres -- psql -v ON_ERROR_STOP=1 -qc \ + "CREATE DATABASE $DB OWNER $ROLE" + echo " database $DB created, owner $ROLE" + fi + ;; + down) + if ! db_exists; then + echo " database $DB does not exist - nothing to do" + exit 0 + fi + if [[ $(user_object_count) -gt 0 ]]; then + echo "refusing to drop $DB - it contains user objects (data would be lost)" >&2 + echo "drop it manually if you really want: runuser -u postgres -- psql -c 'DROP DATABASE $DB WITH (FORCE)'" >&2 + exit 1 + fi + runuser -u postgres -- psql -v ON_ERROR_STOP=1 -qc \ + "DROP DATABASE $DB WITH (FORCE)" # FORCE: kick lingering psql sessions + echo " database $DB dropped (was empty)" + ;; +esac