Skip to content

Instantly share code, notes, and snippets.

@rherrick
Created January 24, 2017 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rherrick/efa7736f219ffec77efb6eea2124d3b4 to your computer and use it in GitHub Desktop.
Save rherrick/efa7736f219ffec77efb6eea2124d3b4 to your computer and use it in GitHub Desktop.
Find and Drop XNAT views
-- Change 'xnat' to the database user that owns the XNAT tables.
-- You need to stop Tomcat before running this query.
SELECT drop_user_views('xnat');
CREATE OR REPLACE FUNCTION find_user_views(username TEXT)
RETURNS TABLE(table_schema NAME, view_name NAME) AS $$
BEGIN
RETURN QUERY
SELECT
n.nspname AS table_schema,
c.relname AS view_name
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n
ON (n.oid = c.relnamespace)
WHERE c.relkind = 'v'
AND c.relowner = (SELECT usesysid
FROM pg_catalog.pg_user
WHERE usename = $1);
END$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION drop_user_views(username TEXT)
RETURNS INTEGER AS $$
DECLARE
r RECORD;
s TEXT;
c INTEGER := 0;
BEGIN
RAISE NOTICE 'Dropping views for user %', $1;
FOR r IN
SELECT * FROM find_user_views($1)
LOOP
S := 'DROP VIEW IF EXISTS ' || quote_ident(r.table_schema) || '.' || quote_ident(r.view_name) || ' CASCADE;';
EXECUTE s;
c := c + 1;
RAISE NOTICE 's = % ', S;
END LOOP;
RETURN c;
END$$ LANGUAGE plpgsql;
-- Change 'xnat' to the database user that owns the XNAT tables.
SELECT * FROM find_user_views('xnat');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment