From e038b7756df8a7487366d4e678c1e0d0d1ba5bbe Mon Sep 17 00:00:00 2001
From: Noah Misch <noah@leadboat.com>
Date: Thu, 27 Jun 2024 19:21:05 -0700
Subject: [PATCH] AccessExclusiveLock new relations just after assigning the
 OID.

This has no user-visible, important consequences, since other sessions'
catalog scans can't find the relation until we commit.  However, this
unblocks introducing a rule about locks required to heap_update() a
pg_class row.  CREATE TABLE has been acquiring this lock eventually, but
it can heap_update() pg_class.relchecks earlier.  create_toast_table()
has been acquiring only ShareLock.  Back-patch to v12 (all supported
versions), the plan for the commit relying on the new rule.

Reviewed (in an earlier version) by Robert Haas.

Discussion: https://postgr.es/m/20240611024525.9f.nmisch@google.com
---
 src/backend/catalog/heap.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index ac772069cf7..0bf9625cc9d 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -1264,6 +1264,13 @@ heap_create_with_catalog(const char *relname,
 									  relpersistence);
 	}
 
+	/*
+	 * Other sessions' catalog scans can't find this until we commit.  Hence,
+	 * it doesn't hurt to hold AccessExclusiveLock.  Do it here so callers
+	 * can't accidentally vary in their lock mode or acquisition timing.
+	 */
+	LockRelationOid(relid, AccessExclusiveLock);
+
 	/*
 	 * Determine the relation's initial permissions.
 	 */
-- 
2.39.5