Skip to content

Commit fb69fd1

Browse files
committed
Make CLUSTER lock the old table's toast table before copying data.
We must lock out autovacuuming of the old toast table before computing the OldestXmin horizon we will use. Otherwise, autovacuum could start on the toast table later, compute a later OldestXmin horizon, and remove as DEAD toast tuples that we still need (because we think their parent tuples are only RECENTLY_DEAD). Per further thought about bug #5998.
1 parent 007a6e5 commit fb69fd1

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/backend/commands/cluster.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
#include "commands/vacuum.h"
3838
#include "miscadmin.h"
3939
#include "storage/bufmgr.h"
40+
#include "storage/lmgr.h"
4041
#include "storage/procarray.h"
4142
#include "storage/smgr.h"
4243
#include "utils/acl.h"
@@ -781,6 +782,22 @@ copy_heap_data(Oid OIDNewHeap, Oid OIDOldHeap, Oid OIDOldIndex,
781782
values = (Datum *) palloc(natts * sizeof(Datum));
782783
isnull = (bool *) palloc(natts * sizeof(bool));
783784

785+
/*
786+
* If the OldHeap has a toast table, get lock on the toast table to keep
787+
* it from being vacuumed. This is needed because autovacuum processes
788+
* toast tables independently of their main tables, with no lock on the
789+
* latter. If an autovacuum were to start on the toast table after we
790+
* compute our OldestXmin below, it would use a later OldestXmin, and then
791+
* possibly remove as DEAD toast tuples belonging to main tuples we think
792+
* are only RECENTLY_DEAD. Then we'd fail while trying to copy those
793+
* tuples.
794+
*
795+
* We don't need to open the toast relation here, just lock it. The lock
796+
* will be held till end of transaction.
797+
*/
798+
if (OldHeap->rd_rel->reltoastrelid)
799+
LockRelationOid(OldHeap->rd_rel->reltoastrelid, AccessExclusiveLock);
800+
784801
/*
785802
* We need to log the copied data in WAL iff WAL archiving/streaming is
786803
* enabled AND it's not a temp rel.

0 commit comments

Comments
 (0)