PostgreSQL數據庫創建只讀用戶總結


 

好久沒有弄,有點忘了,今天有客戶問這個問題,發現幾個SQL還解決不了,於是總結一下:

 

--以超級用戶登錄數據庫,創建用戶:

postgres=# create user test_read_only password 'test_read_only';

CREATE ROLE

 

--設置為只讀的transaction:

postgres=# alter user test_read_only set default_transaction_read_only=on;

ALTER ROLE

 

--默認在postgres數據庫的public模式下的對象是可以訪問的:

--如果要訪問別的schema的表,則需要兩步:

 

--首先要有使用schema的權限:

postgres=# grant usage on schema test to test_read_only;

 

--然后加所有表的只讀權限:

postgres=# grant select on all tables in schema public to test_read_only;

GRANT

 

--如果不想給所有表的查詢權限,則單獨給某個表的查詢權限:

postgres=# grant select on table test to test_read_only;

GRANT

 

--如果要在別的數據庫訪問,則先要用postgres(超級用戶登錄),然后\c到對應的數據庫,執行下面的命令,將對應的schema的表查詢權限給這個用戶:

postgres=# \c test

You are now connected to database "test" as user "postgres".

 

--test數據庫的public模式的usage權限是默認就有的,只需要添加表的只讀權限即可:

test=# grant select on all tables in schema public to test_read_only;

GRANT

 

--如果是將某個模式下的所有表的只讀權限都給了某個用戶,當新建表的時候,該用戶仍然沒有任何權限,這時,需要手動添加,或者修改模式的屬性:

test=# alter default privileges in schema public grant select on tables to test_read_only;

ALTER DEFAULT PRIVILEGES

 

--這樣即使是該模式中新加的表,test_read_only用戶都有只讀權限。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM