dropdb: Drop a PostgreSQL Database in CI
dropdb dbname deletes a PostgreSQL database; --if-exists makes it safe to run when the database may not exist.
To reset test state between runs, dropdb removes a database in one command. The two CI concerns are tolerating a missing database and dealing with open connections that block the drop.
What it does
dropdb issues DROP DATABASE for the named database. By default it errors if the database is absent or if other sessions are connected to it. --if-exists suppresses the missing-database error and -f (Postgres 13+) forcibly terminates other connections first.
Common usage
# safe reset: no error if it is already gone
dropdb -h db -U postgres --if-exists appdb_test
# force-drop even with open connections (Postgres 13+)
dropdb -h db -U postgres -f appdb_testOptions
| Flag | What it does |
|---|---|
| --if-exists | Do not error if the database does not exist |
| -f / --force | Terminate other connections, then drop (v13+) |
| -h / -p / -U | Standard connection flags |
| -e | Echo the SQL that dropdb runs |
| -i | Prompt before dropping (avoid in CI) |
In CI
Use --if-exists in teardown so a first run (where the database was never created) does not fail the step. If a leftover test process still holds a connection, add -f on Postgres 13+ to force the drop instead of failing. Never leave the interactive -i flag on in a pipeline; it will hang waiting for confirmation.
Common errors in CI
"dropdb: error: database removal failed: ERROR: database \"appdb_test\" is being accessed by other users" means open sessions block the drop; use -f (v13+) or terminate them with pg_terminate_backend. "ERROR: database \"appdb_test\" does not exist" without --if-exists means it was already dropped; add --if-exists. "permission denied" means the role does not own the database.