[英]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?如何更改表以添加列而不阻塞 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.
后端主要在表上触发 <10 毫秒的查询。
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. alter.sql 看起来像这样。
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.基本上,这段代码在不阻塞任何查询的情况下不断尝试获取锁,在获取锁后立即运行 alter 命令。
Inspiration: https://www.depesz.com/2019/09/26/how-to-run-short-alter-table-without-long-locking-concurrent-queries/灵感: https : //www.depesz.com/2019/09/26/how-to-run-short-alter-table-without-long-locking-concurrent-queries/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.