From ba34362799517323e2c68d2fa5e3e8ac7cc6113f Mon Sep 17 00:00:00 2001 From: Alfredo Gutierrez Date: Mon, 22 Jan 2024 10:10:41 -0600 Subject: [PATCH] SQL Clean-up Script for Network Resets (#27) Signed-off-by: Alfredo Gutierrez --- scripts/db/cleanup.sql | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 scripts/db/cleanup.sql diff --git a/scripts/db/cleanup.sql b/scripts/db/cleanup.sql new file mode 100644 index 0000000..42d242b --- /dev/null +++ b/scripts/db/cleanup.sql @@ -0,0 +1,40 @@ +DO $$ +DECLARE + drop_schemas_cmd text; + drop_tables_cmd text; + drop_views_cmd text; +BEGIN + -- Prepare command to drop all non-system schemas except 'public' + SELECT INTO drop_schemas_cmd + string_agg('DROP SCHEMA ' || quote_ident(schema_name) || ' CASCADE', '; ') + FROM information_schema.schemata + WHERE schema_name NOT IN ('public', 'information_schema', 'pg_catalog', 'pg_toast', 'pg_temp_4', 'pg_toast_temp_4'); + + -- Execute if command is not null + IF drop_schemas_cmd IS NOT NULL THEN + EXECUTE drop_schemas_cmd; + END IF; + + -- Prepare command to drop all user-created tables in the 'public' schema + SELECT INTO drop_tables_cmd + string_agg('DROP TABLE IF EXISTS public.' || quote_ident(table_name) || ' CASCADE', '; ') + FROM information_schema.tables + WHERE table_schema = 'public' AND table_type = 'BASE TABLE' + AND table_name NOT LIKE 'pg_%'; + + -- Execute if command is not null + IF drop_tables_cmd IS NOT NULL THEN + EXECUTE drop_tables_cmd; + END IF; + + -- Prepare command to drop all user-created views in the 'public' schema + SELECT INTO drop_views_cmd + string_agg('DROP VIEW IF EXISTS public.' || quote_ident(table_name) || ' CASCADE', '; ') + FROM information_schema.views + WHERE table_schema = 'public' AND table_name NOT LIKE 'pg_%'; + + -- Execute if command is not null + IF drop_views_cmd IS NOT NULL THEN + EXECUTE drop_views_cmd; + END IF; +END $$;