盗用德哥的图;来诠释下逻辑结构;PostgreSQL逻辑结构有4层:实例->数据库->schema->数据库对象
可以看出用户不在PostgreSQL里面;是独立之外的object
# 创建用户lottu1 postgres=# create user lottu1; CREATE ROLE # 创建用户lottu2 postgres=# create user lottu2; CREATE ROLE # 创建数据库db1;属于lottu1 postgres=# create database db1 owner lottu1; CREATE DATABASE # 创建schema、table、并插入记录 postgres=# \c db1 lottu1; You are now connected to database "db1" as user "lottu1". db1=> create schema lottu1; CREATE SCHEMA db1=> create table tbl_lottu_01(id int, info text, reg_time timestamp); CREATE TABLE db1=> insert into tbl_lottu_01 select 1,‘lottu‘,now(); INSERT 0 1
新建的数据库对所有的用户都有连接权限;不管是不是超级用户、属主用户
db1=> \c db1 lottu2 You are now connected to database "db1" as user "lottu2".
针对这种情况;这样是不是很不安全;非主用户为啥可以连数据库;虽然它不可以做任何操作。但是觉得还是没有完全隔离。要实现隔离;我们可以回收数据库权限;只有超级用户、属主用户可以连。
db1=> \c db1 postgres You are now connected to database "db1" as user "postgres". db1=# revoke CONNECT ON DATABASE db1 from public; REVOKE db1=# \c db1 postgres You are now connected to database "db1" as user "postgres". db1=# \c db1 lottu1; You are now connected to database "db1" as user "lottu1". db1=> \c db1 lottu2; FATAL: permission denied for database "db1" DETAIL: User does not have CONNECT privilege. Previous connection kept
现在实现用户lottu2不能连接数据库db1。现在需求tbl_lottu_01给db2查询。而表tbl_lottu_01属于数据库db1下面schema-lottu1的。
db1=> grant CONNECT ON DATABASE db1 to lottu2; GRANT db1=> grant USAGE ON SCHEMA lottu1 to lottu2; GRANT db1=> grant select on TABLE tbl_lottu_01 to lottu2; GRANT db1=> \c db1 lottu2; You are now connected to database "db1" as user "lottu2". db1=> select * from lottu1.tbl_lottu_01; id | info | reg_time ----+-------+---------------------------- 1 | lottu | 2020-05-19 10:50:15.206569 (1 row)
经过一层层的赋权;用户lottu2可以select表tbl_lottu_01。若需求将schema-lottu1下所有的表都赋于给lottu2。将上面的修改下即可
grant select on ALL TABLES IN SCHEMA lottu1 to lottu2;