Created
August 17, 2024 18:27
-
-
Save eirenik0/3dc02fde0993bf4464bc5cf2a3e7ab28 to your computer and use it in GitHub Desktop.
Help to drop all triggers, types and tables in PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Drop all triggers | |
DO $$ | |
DECLARE | |
r RECORD; | |
BEGIN | |
-- Loop through all tables in the 'public' schema | |
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') | |
LOOP | |
-- Drop all triggers associated with each table | |
EXECUTE 'DO $$ BEGIN EXECUTE ''DROP TRIGGER IF EXISTS ALL ON ' || quote_ident(r.tablename) || '''; EXCEPTION WHEN others THEN NULL; END $$;'; | |
END LOOP; | |
END $$; | |
-- Drop all custom types | |
DO $$ | |
DECLARE | |
r RECORD; | |
BEGIN | |
-- Loop through all custom types in the 'public' schema | |
FOR r IN (SELECT typname FROM pg_type WHERE typnamespace = 'public'::regnamespace AND typtype = 'c') | |
LOOP | |
-- Drop each custom type | |
EXECUTE 'DROP TYPE IF EXISTS ' || quote_ident(r.typname) || ' CASCADE'; | |
END LOOP; | |
END $$; | |
-- Drop Views | |
DO $$ | |
DECLARE | |
r RECORD; | |
BEGIN | |
-- Loop through all views in the 'public' schema | |
FOR r IN (SELECT table_name FROM information_schema.views WHERE table_schema = 'public') | |
LOOP | |
-- Drop each view | |
EXECUTE 'DROP VIEW IF EXISTS ' || quote_ident(r.table_name) || ' CASCADE'; | |
END LOOP; | |
END $$; | |
-- Drop tables | |
DROP SCHEMA public CASCADE; | |
CREATE SCHEMA public; | |
-- Verify drops | |
SELECT * FROM pg_trigger WHERE tgname != 'RI_ConstraintTrigger'; | |
SELECT * FROM pg_type WHERE typnamespace = 'public'::regnamespace AND typtype = 'c'; | |
SELECT table_name FROM information_schema.views WHERE table_schema = 'public'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment