Redshift:特定用户的所有表的总行数

时间:2016-09-01 22:39:34

标签: amazon-redshift

我们使用Periscope(我认为)按照我们允许访问的表格中的总行数收费。

我的问题是:给定用户periscope,如何获取用户periscope有权访问的表中的总行数?

E.g。如果用户periscope只能访问两个表:t1表示计数8,t2表示计数2,则总计数应为10。

我得到了所有带有answer的表(不包括'pg_tables'和'information_schema'),但我不知道下一步该怎么做:

SELECT CAST(schemaname as varchar), CAST(  objectname as varchar)
FROM 
    (
    SELECT 
        schemaname
        ,objectname
        ,usename
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AS sel
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AS ins
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'update') AS upd
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'delete') AS del
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'references') AS ref
    FROM
        (
        SELECT schemaname, 't' AS obj_type, tablename AS objectname, schemaname + '.' + tablename AS fullobj FROM pg_tables
        WHERE schemaname not in ('pg_internal')
        UNION
        SELECT schemaname, 'v' AS obj_type, viewname AS objectname, schemaname + '.' + viewname AS fullobj FROM pg_views
        WHERE schemaname not in ('pg_internal')
        ) AS objs
        ,(SELECT * FROM pg_user) AS usrs
    ORDER BY fullobj
    )
WHERE (sel = true or ins = true or upd = true or del = true or ref = true)
and usename = 'periscope'
and schemaname not in ('information_schema', 'pg_catalog');

如果您有一个优雅的解决方案,请告诉我!

1 个答案:

答案 0 :(得分:2)

这应该可以满足您的需求:

SELECT SUM(b.reltuples)
FROM 
(
    SELECT 
        schemaname
        ,objectname
        ,usename
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'select') AS sel
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'insert') AS ins
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'update') AS upd
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'delete') AS del
        ,HAS_TABLE_PRIVILEGE(usrs.usename, fullobj, 'references') AS ref
    FROM
    (
        SELECT schemaname, 't' AS obj_type, tablename AS objectname, schemaname + '.' + tablename AS fullobj FROM pg_tables
        WHERE schemaname not in ('pg_internal')
        UNION
        SELECT schemaname, 'v' AS obj_type, viewname AS objectname, schemaname + '.' + viewname AS fullobj FROM pg_views
        WHERE schemaname not in ('pg_internal')
        ) AS objs
        ,(SELECT * FROM pg_user) AS usrs
    ORDER BY fullobj
) as a
JOIN 
(
    SELECT 
        nspname AS schemaname,relname,reltuples
    FROM pg_class C
    LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
    ORDER BY reltuples DESC
) as b
ON (a.schemaname = b.schemaname AND a.objectname = b.relname)
WHERE (sel = true or ins = true or upd = true or del = true or ref = true)
and usename = 'periscope'
and a.schemaname not in ('information_schema', 'pg_catalog');