From 817cfd196dc055b663412a149a6e3554b21c0a90 Mon Sep 17 00:00:00 2001
From: Paul Guo <paulguo@gmail.com>
Date: Thu, 17 May 2018 11:24:37 +0800
Subject: [PATCH] Use access() to check file existence in GetNewRelFileNode().

Previous code use BasicOpenFile() + close().

access() should be faster than BasicOpenFile()+close() and access()
should be more correct since BasicOpenFile() could fail for various
cases (e.g. due to file permission, etc) even the file exists.
---
 src/backend/catalog/catalog.c | 13 +++----------
 1 file changed, 3 insertions(+), 10 deletions(-)

diff --git a/src/backend/catalog/catalog.c b/src/backend/catalog/catalog.c
index 2292deb703..9f119a031f 100644
--- a/src/backend/catalog/catalog.c
+++ b/src/backend/catalog/catalog.c
@@ -397,7 +397,6 @@ GetNewRelFileNode(Oid reltablespace, Relation pg_class, char relpersistence)
 {
 	RelFileNodeBackend rnode;
 	char	   *rpath;
-	int			fd;
 	bool		collides;
 	BackendId	backend;
 
@@ -445,24 +444,18 @@ GetNewRelFileNode(Oid reltablespace, Relation pg_class, char relpersistence)
 
 		/* Check for existing file of same name */
 		rpath = relpath(rnode, MAIN_FORKNUM);
-		fd = BasicOpenFile(rpath, O_RDONLY | PG_BINARY);
 
-		if (fd >= 0)
+		if (access(rpath, F_OK) == 0)
 		{
 			/* definite collision */
-			close(fd);
 			collides = true;
 		}
 		else
 		{
 			/*
 			 * Here we have a little bit of a dilemma: if errno is something
-			 * other than ENOENT, should we declare a collision and loop? In
-			 * particular one might think this advisable for, say, EPERM.
-			 * However there really shouldn't be any unreadable files in a
-			 * tablespace directory, and if the EPERM is actually complaining
-			 * that we can't read the directory itself, we'd be in an infinite
-			 * loop.  In practice it seems best to go ahead regardless of the
+			 * other than ENOENT, should we declare a collision and loop?
+			 * In practice it seems best to go ahead regardless of the
 			 * errno.  If there is a colliding file we will get an smgr
 			 * failure when we attempt to create the new relation file.
 			 */
-- 
2.15.1 (Apple Git-101)

