008: personal database iwanhae owned by admin role

This commit is contained in:
wan
2026-08-31 16:31:53 +09:00
parent 29e87149eb
commit 4c21cccae3
2 changed files with 48 additions and 0 deletions
+47
View File
@@ -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