How do I GRANT ALL PRIVILEGES on ALL VIEWS in one statement?

一个人想着一个人 提交于 2019-12-20 04:26:04

问题


In PostgreSQL 9+, is there a way to
GRANT ALL PRIVILEGES on ALL VIEWS in schema schema_name TO role_name
in a single statement?


回答1:


The only way to do this in a single statement (kind of) is to create a function, otherwise you are either specifically listing all views or you are granting to all tables, then revoking non-views.

I wrote this quickly, but tested it. You may need to tweak as needed:

CREATE OR REPLACE FUNCTION fn_grant_all_views(schema_name TEXT, role_name TEXT)
RETURNS VOID AS $func$

DECLARE view_name TEXT;

BEGIN

  FOR view_name IN
    SELECT viewname FROM pg_views WHERE schemaname = schema_name
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || schema_name || '.' || view_name || ' TO ' || role_name || ';';
  END LOOP;

END; $func$ LANGUAGE PLPGSQL

Usage:

SELECT fn_grant_all_views('my_schema','my_role');



回答2:


You can also do this from the command line:

  1. Login as postgres:

    sudo -i -u postgres

  2. Run this command:

    psql -At -d [dbname] -c "SELECT 'GRANT ALL ON '||viewname||' TO [username];' FROM pg_views WHERE schemaname='public';" | psql -d [dbname]



来源:https://stackoverflow.com/questions/38920916/how-do-i-grant-all-privileges-on-all-views-in-one-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!