一.說明:
讓資料庫變成隻讀模式,目前PostgreSQL沒有嚴格意義上的隻讀模式(如臨時表在隻讀事務中還是可以使用的)。通過調整參數或設定事務模式可以将後續登入的SESSION或者目前事務設定為隻讀模式。
在隻讀模式下,PostgreSQL不允許如下SQL:
When a transaction is read-only, the following SQL commands are disallowed: INSERT, UPDATE, DELETE, and COPY FROM if the table they would write to is not a temporary table; all CREATE, ALTER, and DROP commands; COMMENT, GRANT, REVOKE, TRUNCATE; and EXPLAIN ANALYZE and EXECUTE if the command they would execute is among those listed. This is a high-level notion of read-only that does not prevent all writes to disk.
上述描述引用位址:
<a href="http://blog.163.com/digoal@126/blog/static/163877040201111821118906/" target="_blank">http://blog.163.com/digoal@126/blog/static/163877040201111821118906/</a>
二.給postgresql的登陸使用者設定隻讀模式:
1.設定登陸資料庫的使用者為隻讀模式:
[postgres@cacti ~]$ psql -Uuser001 -dtestdb01 -p19086 -h127.0.0.1
Password for user user001:
psql.bin (9.5.9)
Type "help" for help.
testdb01=>
testdb01=> alter user user001 set default_transaction_read_only=on;(資料庫不需要重新開機也永久生效)
ALTER ROLE
testdb01=> create database test001;
ERROR: permission denied to create database
testdb01=> show default_transaction_read_only;
default_transaction_read_only
-------------------------------
off
(1 row)
上述的參數設定,即使是重新開機資料庫剛才設定的隻讀模式也是生效的:
pg_ctl -D /data/postgresql/data -l /data/postgresql/log/postgres.log stop
pg_ctl -D /data/postgresql/data -l /data/postgresql/log/postgres.log start
on
ERROR: cannot execute CREATE DATABASE in a read-only transaction
2.設定關閉session級别的隻讀模式(當然在退出資料庫sql互動視窗的時候設定的模式會失效):
testdb01=> set session default_transaction_read_only=off;
SET
設定開啟session級别的隻讀模式(當然在退出資料庫sql互動視窗的時候設定的模式會失效)如果重新開機資料庫,則以postgresql.conf檔案的配置參數default_transaction_read_only = 為準;
預設配置檔案中此參數是關閉的#default_transaction_read_only = off
testdb01=> set session default_transaction_read_only=on;
testdb01=>
3.不需要修改postgresql.conf配置檔案參數,巧妙的解決登陸psql設定的登陸使用者的隻讀模式。
testdb01=> alter user user001 set default_transaction_read_only=on;
在此處可以設定session級别的讀寫模式,
關閉session級别的隻讀模式(隻是臨時關閉隻讀模式。退出psql互動視窗,剛才的設定便失效)
testdb01=> alter user user001 set default_transaction_read_only=off;
永久關閉隻讀模式,這樣即使是退出pgsql資料庫的互動視窗,隻讀模式也是可以關閉的,除非修改配置檔案參數為default_transaction_read_only =on來重新開機postgresql服務才是隻讀模式;
本文轉自 wjw555 51CTO部落格,原文連結:http://blog.51cto.com/wujianwei/1976446