Skip to content

Instantly share code, notes, and snippets.

@wboykinm
Last active October 4, 2019 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wboykinm/aee904e60f14d23dd30a to your computer and use it in GitHub Desktop.
Save wboykinm/aee904e60f14d23dd30a to your computer and use it in GitHub Desktop.
Footgun - delete a whole mess of tables by wildcard, with cascade. Obviously this will blow up in your face at some point.

Footgun

PostgreSQL function to delete a batch of tables at once, including by wildcard. Beware.

footgun

Usage

SELECT footgun('schema', 'tablename');
CREATE OR REPLACE FUNCTION footgun(IN _schema TEXT, IN _parttionbase TEXT)
RETURNS void
LANGUAGE plpgsql
AS
$$
DECLARE
row record;
BEGIN
FOR row IN
SELECT
table_schema,
table_name
FROM
information_schema.tables
WHERE
table_type = 'BASE TABLE'
AND
table_schema = _schema
AND
table_name ILIKE (_parttionbase || '%')
LOOP
EXECUTE 'DROP TABLE ' || quote_ident(row.table_schema) || '.' || quote_ident(row.table_name) || ' CASCADE';
RAISE INFO 'Dropped table: %', quote_ident(row.table_schema) || '.' || quote_ident(row.table_name);
END LOOP;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment