Skip to content

Instantly share code, notes, and snippets.

@datachomp
Created December 6, 2019 14:57
Show Gist options
  • Save datachomp/9701a8685e50d10be4ec02e0c4a06dfc to your computer and use it in GitHub Desktop.
Save datachomp/9701a8685e50d10be4ec02e0c4a06dfc to your computer and use it in GitHub Desktop.
-- create table for bad db names
create table things(database_name text);
-- insert some junk into it
insert into things values ('db1'),('db2'),('db3');
-- create the dropper proc
--call database_deleter();
CREATE OR REPLACE PROCEDURE database_deleter()
AS $proc$
DECLARE
database text;
BEGIN
-- build the loop of db names from the table
FOR database IN SELECT database_name
FROM things
LOOP
-- send a notice about what db is about to reach enlightenment
RAISE NOTICE 'DELETING: %', database;
-- use dynamic SQL to plug the variable into the statement to be executed
EXECUTE format('DROP DATABASE IF EXISTS %s', database )
USING database;
END LOOP;
END;
$proc$ LANGUAGE plpgsql;
-- call the procedure:
call database_deleter();
-- This does result in the following:
rob=# call database_deleter();
NOTICE: DELETING: db1
ERROR: DROP DATABASE cannot be executed from a function
CONTEXT: SQL statement "DROP DATABASE IF EXISTS db1"
PL/pgSQL function database_deleter() line 9 at EXECUTE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment