Skip to content

Commit 4f8d3c5

Browse files
committed
Lock table in DROP STATISTICS
The DROP STATISTICS code failed to properly lock the table, leading to ERROR: tuple concurrently deleted when executed concurrently with ANALYZE. Fixed by modifying RemoveStatisticsById() to acquire the same lock as ANALYZE. This function is called only by DROP STATISTICS, as ANALYZE calls RemoveStatisticsDataById() directly. Reported by Justin Pryzby, fix by me. Backpatch through 12. The code was like this since it was introduced in 10, but older releases are EOL. Reported-by: Justin Pryzby Reviewed-by: Tom Lane Backpatch-through: 12 Discussion: https://postgr.es/m/ZUuk-8CfbYeq6g_u@pryzbyj2023
1 parent 0ef893b commit 4f8d3c5

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

src/backend/commands/statscmds.c

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -428,18 +428,12 @@ CreateStatistics(CreateStatsStmt *stmt)
428428
/*
429429
* Guts of statistics object deletion.
430430
*/
431-
void
432-
RemoveStatisticsById(Oid statsOid)
431+
static void
432+
RemoveStatisticsDataById(Oid statsOid)
433433
{
434434
Relation relation;
435435
HeapTuple tup;
436-
Form_pg_statistic_ext statext;
437-
Oid relid;
438436

439-
/*
440-
* First delete the pg_statistic_ext_data tuple holding the actual
441-
* statistical data.
442-
*/
443437
relation = table_open(StatisticExtDataRelationId, RowExclusiveLock);
444438

445439
tup = SearchSysCache1(STATEXTDATASTXOID, ObjectIdGetDatum(statsOid));
@@ -452,6 +446,19 @@ RemoveStatisticsById(Oid statsOid)
452446
ReleaseSysCache(tup);
453447

454448
table_close(relation, RowExclusiveLock);
449+
}
450+
451+
/*
452+
* Guts of statistics object deletion.
453+
*/
454+
void
455+
RemoveStatisticsById(Oid statsOid)
456+
{
457+
Relation relation;
458+
Relation rel;
459+
HeapTuple tup;
460+
Form_pg_statistic_ext statext;
461+
Oid relid;
455462

456463
/*
457464
* Delete the pg_statistic_ext tuple. Also send out a cache inval on the
@@ -467,12 +474,24 @@ RemoveStatisticsById(Oid statsOid)
467474
statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
468475
relid = statext->stxrelid;
469476

477+
/*
478+
* Delete the pg_statistic_ext_data tuple holding the actual statistical
479+
* data. Lock the user table first, to prevent other processes (e.g. DROP
480+
* STATISTICS) from removing the row concurrently.
481+
*/
482+
rel = table_open(relid, ShareUpdateExclusiveLock);
483+
484+
RemoveStatisticsDataById(statsOid);
485+
470486
CacheInvalidateRelcacheByRelid(relid);
471487

472488
CatalogTupleDelete(relation, &tup->t_self);
473489

474490
ReleaseSysCache(tup);
475491

492+
/* Keep lock until the end of the transaction. */
493+
table_close(rel, NoLock);
494+
476495
table_close(relation, RowExclusiveLock);
477496
}
478497

0 commit comments

Comments
 (0)