本文我们解释如何查看PostgreSQL 表结构以及权限列表,即哪些用户对表拥有哪些权限。

查看表结构

使用命令查看

\d+ table_name;

示例:

test=# \d+ books
                                          数据表 "public.books"
  栏位  |  类型   | Collation | Nullable |              Default              |   存储   | 统计目标 | 描述
--------+---------+-----------+----------+-----------------------------------+----------+----------+------
 id     | integer |           | not null | nextval('books_id_seq'::regclass) | plain    |          |
 client | text    |           | not null |                                   | extended |          |
 data   | jsonb   |           | not null |                                   | extended |          |
索引:
    "books_pkey" PRIMARY KEY, btree (id)

使用SQL查看

首先通过PostgreSQL的元数据查看,另外也可以直接查看数据表。

  1. 通过元数据 information_schema.columns

示例:

SELECT *
FROM information_schema.columns
where table_name ='books'
table_catalogtable_schematable_namecolumn_nameordinal_positioncolumn_defaultis_nullabledata_typecharacter_maximum_lengthcharacter_octet_lengthnumeric_precisionnumeric_precision_radixnumeric_scaledatetime_precisioninterval_typeinterval_precisioncharacter_set_catalogcharacter_set_schemacharacter_set_namecollation_catalogcollation_schemacollation_namedomain_catalogdomain_schemadomain_nameudt_catalogudt_schemaudt_namescope_catalogscope_schemascope_namemaximum_cardinalitydtd_identifieris_self_referencingis_identityidentity_generationidentity_startidentity_incrementidentity_maximumidentity_minimumidentity_cycleis_generatedgeneration_expressionis_updatable
testpublicbooksid1nextval(‘books_id_seq’::regclass)NOinteger3220testpg_catalogint41NONONONEVERYES
testpublicbooksclient2NOtext1073741824testpg_catalogtext2NONONONEVERYES
testpublicbooksdata3NOjsonbtestpg_catalogjsonb3NONONONEVERYES
  1. 直接查表,传输条件为false
test=# select * from books where 1=2;
 id | client | data
----+--------+------
(0 行记录)

上面介绍了几种方法查看表结构,下面我们查看哪些用户拥有表的权限列表。

查看表权限

使用命令查看

使用 \z 命令,后面跟上需要查看的表名称:

test=# \z books
                               存取权限
 架构模式 | 名称  |  类型  |         存取权限          | 列特权 | 策略
----------+-------+--------+---------------------------+--------+------
 public   | books | 数据表 | postgres=arwdDxt/postgres+|        |
          |       |        | alice=rw/postgres         |        |
(1 行记录)

列出两个用户的权限情况。

使用SQL查看

我们通过元数据视图 information_schema.role_table_grants查看,同时使用 string_agg 函数对用户进行分组:

SELECT grantee, string_agg( privilege_type,', ' ) as privilege_type
FROM information_schema.role_table_grants 
WHERE table_name='books'
group by grantee

返回结果:

granteeprivilege_type
aliceSELECT, UPDATE
postgresUPDATE, DELETE, INSERT, REFERENCES, TRIGGER, TRUNCATE, SELECT

列存两个用户不同的权限列表。

总结

本文介绍使用命令方式和SQL方式查看PostgreSQL表结构和权限。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐