I have a function that looks like this:
BEGIN
DROP DATABASE IF EXISTS db_1;
END;
I'm getting the following error:
ERROR: DROP DATABASE cannot be executed from a function or multi-command string.
Is it not possible to drop a database from a stored procedure in PostgreSQL? I'm using plpgsql.
The error message is just a s clear as the manual on this:
A plgpsql function is surrounded by a transaction block automatically. The long and the short of it: you cannot do that - directly. Is there a particular reason you can't just call the DDL command?
You can circumvent these restrictions with the additional module dblink as @Igor suggested. You need to install it once per database - the one where you call dblink functions, not the (other) one you execute commands in.
Allows you to write a function using
dblink_exec()
like this:quote_ident()
prevents possible SQL injection.Call:
On success you see:
The connection string could even point to the same db your session runs in. The command runs outside a transaction block, which has two consequences:
DROP DATABASE
"by way of a proxy" from within a function.You could create a
FOREIGN DATA WRAPPER
and aFOREIGN SERVER
to store a connection and simplify the call:Using default maintenance db
postgres
, which would be obvious choice. But any db is possible.Simplified function making use of that:
you can't do it from a procedure, because the
drop database
can't be executed inside a transaction, and a stored procedure is considered as a transaction itself. (See reference)What about the dropdb ?