008: personal database iwanhae owned by admin role
This commit is contained in:
@@ -48,6 +48,7 @@ For a private repo you need an auth strategy:
|
|||||||
| 005 | mount-pgdata | /dev/sdb (20G) -> /var/lib/postgresql, fstab |
|
| 005 | mount-pgdata | /dev/sdb (20G) -> /var/lib/postgresql, fstab |
|
||||||
| 006 | install-postgres | PG 18 via PGDG repo, cluster on the disk |
|
| 006 | install-postgres | PG 18 via PGDG repo, cluster on the disk |
|
||||||
| 007 | postgres-admin-role | iwanhae OS user -> PG superuser (peer auth) |
|
| 007 | postgres-admin-role | iwanhae OS user -> PG superuser (peer auth) |
|
||||||
|
| 008 | create-db-iwanhae | database `iwanhae` owned by admin role |
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in New Issue
Block a user