Sample Header Ad - 728x90

How to lock an entire Postgres database

1 vote
1 answer
1002 views
I have a process (for backup and replication using binary logs) that works in MySQL that I want to replicate for Postgres databases (using WAL): 1. Lock database (FLUSH TABLES WITH READ LOCK;) 2. Disable binary logging (SET sql_log_bin = 0;) 3. Flush binary logs (FLUSH BINARY LOGS;) 4. Copy binary logs and apply to a remote database for replication purposes 5. Enable binary logging (SET sql_log_bin = 1;) 6. Unlock database (UNLOCK TABLES;) This process works and I'm trying to do the same for Postgres. I was able to find that [CHECKPOINT](https://www.postgresql.org/docs/current/sql-checkpoint.html) is what I need to flush the binary logs for Postgres but locking and unlocking the database isn't as straightforward as I hoped it would be. Here's what I found so far: - [LOCK DATABASE](https://wiki.postgresql.org/wiki/Lock_database) is a database-level locking mechanism but is not implemented - BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE NOWAIT; seems to be able to lock the tables individually but apparently there is no [UNLOCK TABLE](https://www.postgresql.org/docs/current/sql-lock.html) command because locks are always released at transaction end - default_transaction_read_only - I tried to look for the equivalent of FLUSH TABLES WITH READ LOCK; in Postgres and found [this question](https://dba.stackexchange.com/questions/271685/postgresql-9-3-set-database-or-all-to-read-only-mode) I tried the default_transaction_read_only solution and it does prevent new records from being added but I'm a little worried about what the answer in there said: > _This takes effect for new sessions, not for sessions that are already connected._ Also when I tried to revert the read-only mode: BEGIN read write; ALTER DATABASE my_database SET default_transaction_read_only to OFF; it appears to have succeeded but when I try to add a new record, I get the following error: > ERROR: cannot execute INSERT in a read-only transaction Any ideas on how I could perform the same process as I am doing for MySQL but for Postgres?
Asked by dokgu (123 rep)
Feb 12, 2024, 04:42 PM
Last activity: Feb 13, 2024, 07:56 AM