让数据库变成只读模式,目前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.
在SQL模式下进入只读事务的方法:
digoal=> begin;
BEGIN
digoal=> set transaction read only;
SET
参数配置 :
default_transaction_read_only = on
配置完后pg_ctl reload -D $PGDATA
配置完参数后,不影响已经连接的SESSION,仅仅对后续连接上来的SESSION生效。新建的SESSION进来后事务就是read only模式。
digoal=> show default_transaction_read_only
digoal-> ;
default_transaction_read_only
-------------------------------
on
digoal=> delete from tbl_test;
ERROR: cannot execute DELETE in a read-only transaction
# 可以设置事务级WRITE覆盖这个默认值
digoal=> begin;
BEGIN
digoal=> set transaction read write;
SET
digoal=> delete from tbl_test;
DELETE 1008
# 或者设置SESSION级参数,覆盖之
digoal=> set session default_transaction_read_only=off;
SET
digoal=> delete from tbl_test;
DELETE 1008
PostgreSQL's read only transaction mode
最新推荐文章于 2024-06-19 13:47:47 发布