一.说明:
让数据库变成只读模式,目前Postgresql没有严格意义上的只读模式(如临时表在只读事务中还是可以使用的)。通过调整参数或设置事务模式可以将后续登录的SESSION或者当前事务设置为只读模式。
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.
上述描述引用地址:
http://blog.163.com/digoal@126/blog/static/163877040201111821118906/
[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
[postgres@cacti ~]$ psql -Uuser001 -dtestdb01 -p19086 -h127.0.0.1
Password for user user001:
psql.bin (9.5.9)
Type "help" for help.
testdb01=> show default_transaction_read_only;
default_transaction_read_only
-------------------------------
on
(1 row)
testdb01=> create database test001;
ERROR: cannot execute CREATE DATABASE in a read-only transaction
2.设置关闭session级别的只读模式(当然在退出数据库sql交互窗口的时候设置的模式会失效):
testdb01=> set session default_transaction_read_only=off;
SET
testdb01=> show default_transaction_read_only;
default_transaction_read_only
-------------------------------
off
(1 row)
testdb01=> create database test001;
ERROR: permission denied to create database
testdb01=>
设置开启session级别的只读模式(当然在退出数据库sql交互窗口的时候设置的模式会失效)如果重启数据库,则以postgresql.conf文件的配置参数default_transaction_read_only = 为准;
默认配置文件中此参数是关闭的#default_transaction_read_only = off
testdb01=> set session default_transaction_read_only=on;
SET
testdb01=>
testdb01=> show default_transaction_read_only;
default_transaction_read_only
-------------------------------
on
(1 row)
testdb01=> create database test001;
ERROR: permission denied to create database
3.不需要修改postgresql.conf配置文件参数,巧妙的解决登陆psql设置的登陆用户的只读模式。
testdb01=> alter user user001 set default_transaction_read_only=on;
ALTER ROLE
testdb01=> show default_transaction_read_only;
default_transaction_read_only
-------------------------------
on
(1 row)
testdb01=> create database test001;
ERROR: cannot execute CREATE DATABASE in a read-only transaction
在此处可以设置session级别的读写模式,
关闭session级别的只读模式(只是临时关闭只读模式。退出psql交互窗口,刚才的设置便失效)
testdb01=> set session default_transaction_read_only=off;
testdb01=> alter user user001 set default_transaction_read_only=off;
永久关闭只读模式,这样即使是退出pgsql数据库的交互窗口,只读模式也是可以关闭的,除非修改配置文件参数为default_transaction_read_only =on来重启postgresql服务才是只读模式;