3

In Postgresql I have several databases starting with hdb prefix.

What I am looking for is to to forcefully drop all such dbs, terminating existing connections if any.

I tried below way:

DO
$do$
DECLARE
   _db text;
BEGIN
FOR _db  IN
    SELECT datname FROM pg_stat_activity where datname ilike 'hdb%'
LOOP
    EXECUTE 'REVOKE CONNECT ON DATABASE ' || _db||' FROM public;';
    EXECUTE 'DROP DATABASE ' || _db;

END LOOP;
END
$do$;

But that says,

ERROR: DROP DATABASE cannot be executed from a function or multi-command string

1
  • 2
    Since you can't do it with a database function, write client code. Commented Aug 19, 2019 at 11:37

1 Answer 1

7

This is how I drop test databases with a client script (Linux):

#!/bin/bash

PREFIX='hdb'
export PGPASSWORD=postgres
export PGUSER=postgres
export PGHOST=localhost
export PGPORT=5432

TEST_DB_LIST=$(psql -l | awk '{ print $1 }' | grep '^[a-z]' | grep -v template | grep -v postgres)
for TEST_DB in $TEST_DB_LIST ; do
    if [ $(echo $TEST_DB | sed "s%^$PREFIX%%") != $TEST_DB ]
    then
        echo "Dropping $TEST_DB"
        dropdb --if-exists $TEST_DB
    fi
done
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but I want to make it OS independent.
@Pratik With which client (scripting) language?
As mentioned, using PostgreSQL script.
And nothing has changed: It is not possible in a database function.
For more information, check out its reference copyprogramming.com/howto/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.