Skip to content

Instantly share code, notes, and snippets.

@oleg-koval
Last active October 1, 2022 22:44
Show Gist options
  • Save oleg-koval/d28ee6b66c4bc3dc840c3dbe0ea7b5d5 to your computer and use it in GitHub Desktop.
Save oleg-koval/d28ee6b66c4bc3dc840c3dbe0ea7b5d5 to your computer and use it in GitHub Desktop.
Script to cleanup (truncate tables) data from Postgresql
CREATE OR REPLACE FUNCTION public.truncate_tables(username character varying)
RETURNS void
LANGUAGE plpgsql
AS $function$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
END LOOP;
END;
$function$
CREATE OR REPLACE FUNCTION f_truncate_tables(_username text)
RETURNS void AS
$func$
BEGIN
RAISE NOTICE '%',
-- EXECUTE -- dangerous, test before you execute!
(SELECT 'TRUNCATE TABLE '
|| string_agg(format('%I.%I', schemaname, tablename), ', ')
|| ' CASCADE'
FROM pg_tables
WHERE tableowner = _username
AND schemaname = 'public'
);
END
$func$ LANGUAGE plpgsql;
SELECT truncate_tables('root');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment