目錄
文章目錄
- 目錄
- PostgreSQL 資料庫實體只讀鎖定
- 硬鎖定
- 硬解鎖
- 軟鎖定
- 軟解鎖
PostgreSQL 資料庫實體只讀鎖定
在一些場景中,可能要將資料庫設定為只讀模式,例如:需要對資料庫進行遷移,準備割接時,首先要將主庫切換到只讀(鎖定),確保絕對不會有新的事務寫入,導致資料不一致的情況,
但實際上,目前 PostgreSQL 沒有嚴格意義上的只讀模式,不過 PostgreSQL 提供了 2 種只讀鎖定的方法:
通過或可以
- 硬鎖定(調整引數):直接將資料庫切換到恢復模式(Recovery Mode),不允許寫操作,
- 軟鎖定(設定事務模式):設定 system config default_transaction_read_only = on,將后續登錄的會話或者當前事務設定為只讀模式,允許被破解,
在只讀模式下,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.
硬鎖定
- 配置 recovery.conf,
recovery_target_timeline = 'latest'
standby_mode = on
注:PostgreSQL 12: Recovery.conf 檔案引數合并到了 postgresql.conf,recovery.conf 不再使用,
- 重啟資料庫,
pg_ctl restart -m fast
- 硬鎖定是不可被破解的,
postgres=# select pg_is_in_recovery();
pg_is_in_recovery
-------------------
t
(1 row)
postgres=# insert into t1 values (1);
ERROR: cannot execute INSERT in a read-only transaction
postgres=# begin transaction read write;
ERROR: cannot set transaction read-write mode during recovery
硬解鎖
- 重命名 recovery.conf 為 recovery.done,
cd $PGDATA
mv recovery.conf recovery.done
注:PostgreSQL 12: Recovery.conf 檔案引數合并到了 postgresql.conf,recovery.conf 不再使用,
- 重啟資料庫,
pg_ctl restart -m fast
軟鎖定
- 設定 default_transaction_read_only,
# 設定系統級別的只讀模式,資料庫不需要重啟也永久生效,
postgres=# alter system set default_transaction_read_only=on;
# 設定 Session 級別的只讀模式,退出 SQL 互動視窗后失效,
set session default_transaction_read_only=off;
# 設定指定登陸資料庫的用戶為只讀模式,資料庫不需要重啟也永久生效,
alter user user001 set default_transaction_read_only=on;
- 多載配置,
postgres=# select pg_reload_conf();
pg_reload_conf
----------------
t
(1 row)
postgres=# show default_transaction_read_only ;
default_transaction_read_only
-------------------------------
on
(1 row)
- 所有會話自動進入 read-only 的默認事務模式,
postgres=# insert into t1 values (1);
ERROR: cannot execute INSERT in a read-only transaction
軟解鎖
- 設定 default_transaction_read_only,
postgres=# alter system set default_transaction_read_only=off;
- 多載配置,
postgres=# select pg_reload_conf();
pg_reload_conf
----------------
t
(1 row)
postgres=# show default_transaction_read_only ;
default_transaction_read_only
-------------------------------
off
(1 row)
注:軟鎖定是可以被破解的,無需重新配置,執行指令:
psql -U <username> -d postgres
begin;
set transaction read write;
alter database exercises set default_transaction_read_only = off;
commit;
\q
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/159604.html
標籤:其他
