简体   繁体   中英

How to do alter table add column without blocking the statement in Postgresql?

How to alter the table to add a column without blocking the statement in Postgresql?

The below statement at the time of execution is getting stuck forever.

ALTER TABLE test_table ADD COLUMN test_column integer;

I tried killing all long-running queries but it didn't help. This table is in active use by the backend. Backend fires mostly <10 ms queries on the table.

Run below script:

while true
do
    date
    export PGPASSWORD='YOUR_DB_PASSWORD';
    psql -h DB_HOST_NAME -U USER_NAME DB_NAME -qX -v ON_ERROR_STOP=1 -f alter.sql && break
done

alter.sql looks like this.

begin;
    -- Try to acquire a lock on the table without blocking.
    lock table only test in ACCESS EXCLUSIVE MODE NOWAIT;
    -- Change timeout to higher unlimited so that migration can be complete.
    set statement_timeout = 0;
    ALTER TABLE test ADD COLUMN column_to_add INTEGER;     
commit;

Basically, this code continuously tries to acquire the lock without blocking any queries, run the alter command as soon as the lock is acquired.

Inspiration: https://www.depesz.com/2019/09/26/how-to-run-short-alter-table-without-long-locking-concurrent-queries/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM