From 31dd380d54e1e05808cc65aeea8707f93e19f01b Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Wed, 31 Jul 2024 18:04:48 +0900
Subject: [PATCH v36 13/17] Add a new version of copy_file to allow overwrites

In subsequent patches, it will be necessary to overwrite the existing
main fork with the init fork. To facilitate this, add a version of the
copy_file function that supports overwriting.
---
 src/backend/storage/file/copydir.c | 16 +++++++++++++++-
 src/include/storage/copydir.h      |  2 ++
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/backend/storage/file/copydir.c b/src/backend/storage/file/copydir.c
index d4fbe542077..30d0ae54ec4 100644
--- a/src/backend/storage/file/copydir.c
+++ b/src/backend/storage/file/copydir.c
@@ -115,6 +115,12 @@ copydir(const char *fromdir, const char *todir, bool recurse)
  */
 void
 copy_file(const char *fromfile, const char *tofile)
+{
+	copy_file_extended(fromfile, tofile, false);
+}
+
+void
+copy_file_extended(const char *fromfile, const char *tofile, bool overwrite)
 {
 	char	   *buffer;
 	int			srcfd;
@@ -122,6 +128,7 @@ copy_file(const char *fromfile, const char *tofile)
 	int			nbytes;
 	off_t		offset;
 	off_t		flush_offset;
+	int			dstflags;
 
 	/* Size of copy buffer (read and write requests) */
 #define COPY_BUF_SIZE (8 * BLCKSZ)
@@ -150,7 +157,11 @@ copy_file(const char *fromfile, const char *tofile)
 				(errcode_for_file_access(),
 				 errmsg("could not open file \"%s\": %m", fromfile)));
 
-	dstfd = OpenTransientFile(tofile, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
+	dstflags = O_RDWR | O_CREAT | PG_BINARY;
+	if (!overwrite)
+		dstflags |= O_EXCL;
+
+	dstfd = OpenTransientFile(tofile, dstflags);
 	if (dstfd < 0)
 		ereport(ERROR,
 				(errcode_for_file_access(),
@@ -159,6 +170,9 @@ copy_file(const char *fromfile, const char *tofile)
 	/*
 	 * Do the data copying.
 	 */
+	if (overwrite)
+		pg_truncate(tofile, 0);
+
 	flush_offset = 0;
 	for (offset = 0;; offset += nbytes)
 	{
diff --git a/src/include/storage/copydir.h b/src/include/storage/copydir.h
index a25e258f479..1a430675428 100644
--- a/src/include/storage/copydir.h
+++ b/src/include/storage/copydir.h
@@ -15,5 +15,7 @@
 
 extern void copydir(const char *fromdir, const char *todir, bool recurse);
 extern void copy_file(const char *fromfile, const char *tofile);
+extern void copy_file_extended(const char *fromfile, const char *tofile,
+							   bool overwrite);
 
 #endif							/* COPYDIR_H */
-- 
2.43.5

