3

How I can Delete All User Defined Views From PostgreSQL using a Query? Like we can delete All functions using query :

SELECT 'DROP FUNCTION ' || ns.nspname || '.' || proname 
       || '(' || oidvectortypes(proargtypes) || ');'
FROM pg_proc INNER JOIN pg_namespace ns ON (pg_proc.pronamespace = ns.oid)
WHERE ns.nspname = 'my_messed_up_schema'  order by proname;
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Satish Sharma
  • 3,284
  • 9
  • 38
  • 51

2 Answers2

6

Script for deleting all views in a certain schema:

SELECT 'DROP VIEW ' || t.oid::regclass || ';' -- CASCADE?
FROM   pg_class t
JOIN   pg_namespace n ON n.oid = t.relnamespace
WHERE  t.relkind = 'v'
AND    n.nspname = 'my_messed_up_schema -- select by schema(s)
ORDER  BY 1;

The cast to regclass (t.oid::regclass) prevents SQLi, because otherwise illegal names are quoted automatically. You could also use quote_ident().

Your example is inherently unsafe.

Do it right away:

DO
$$
DECLARE
   sql text;
BEGIN
   SELECT INTO sql
          string_agg('DROP VIEW ' || t.oid::regclass || ';', ' ')  -- CASCADE?
   FROM   pg_class t
   JOIN   pg_namespace n ON n.oid = t.relnamespace
   WHERE  t.relkind = 'v'
   AND    n.nspname = 'my_messed_up_schema';

   IF sql IS NOT NULL THEN
      -- RAISE NOTICE '%', sql;  -- to debug
      EXECUTE sql;
   ELSE
      RAISE NOTICE 'No views found. Nothing dropped.';
   END IF;
END
$$

DO requires PostgreSQL 9.0 or later.

The IF construct avoids an exception if no views are found.

If you have views referencing other views, you'll have to add the keyword CASCADE or drop views in their hierarchical order from top to bottom.

Always check what you are going to drop before you do it, or you might nuke yourself. If you are unsure, start a transaction, drop the bomb, check if all is good and then either commit or roll back.

BEGIN;
DO$$
  ...
$$;

-- check ..

ROLLBACK; -- if something wrong
COMMIT; -- else

Note that you cannot COMMIT or ROLLBACK inside the plpgsql block. Only outside.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • Works, as long as there are views to drop, but causes an error if there are no views. How can I fix that? What form of `execute` is that which you use? In the manual I only found this in conjunction with `prepare`... – yankee Jul 16 '17 at 18:52
  • @yankee: That's plpgsql code inside the `DO` block, so ***not*** the SQL command to execute prepared statements. I added a version that catches the exception. [Find related questions here.](https://stackoverflow.com/search?q=user%3A939860+%5Bplpgsql%5D+%5Bdynamic-sql%5D+execute) – Erwin Brandstetter Jul 17 '17 at 14:51
0

Use table pg_class.

You need relkind = 'v'

Ihor Romanchenko
  • 26,995
  • 8
  • 48
  • 44