From b43ae117fe3809b82abb5bc89fc62d45a5707ff6 Mon Sep 17 00:00:00 2001
From: Mahendra Singh Thalor <mahi6run@gmail.com>
Date: Sat, 29 Mar 2025 10:14:18 +0530
Subject: [PATCH] pg_dumpall - dump as .tar and .dmp file for tar and custom
 format

---
 src/bin/pg_dump/pg_dumpall.c |  7 ++++++-
 src/bin/pg_dump/pg_restore.c | 22 +++++++++++++++++++++-
 2 files changed, 27 insertions(+), 2 deletions(-)

diff --git a/src/bin/pg_dump/pg_dumpall.c b/src/bin/pg_dump/pg_dumpall.c
index 6aab1bfe831..12983d973be 100644
--- a/src/bin/pg_dump/pg_dumpall.c
+++ b/src/bin/pg_dump/pg_dumpall.c
@@ -1685,7 +1685,12 @@ dumpDatabases(PGconn *conn, ArchiveFormat archDumpFormat)
 		 */
 		if (archDumpFormat != archNull)
 		{
-			snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\"", db_subdir, oid);
+			if (archDumpFormat == archCustom)
+				snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".dmp", db_subdir, oid);
+			else if (archDumpFormat == archTar)
+				snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\".tar", db_subdir, oid);
+			else
+				snprintf(dbfilepath, MAXPGPATH, "\"%s\"/\"%s\"", db_subdir, oid);
 
 			/* Put one line entry for dboid and dbname in map file. */
 			fprintf(map_file, "%s %s\n", oid, dbname);
diff --git a/src/bin/pg_dump/pg_restore.c b/src/bin/pg_dump/pg_restore.c
index 44a24791a6e..31cd9c84c5a 100644
--- a/src/bin/pg_dump/pg_restore.c
+++ b/src/bin/pg_dump/pg_restore.c
@@ -1164,6 +1164,8 @@ restoreAllDatabases(PGconn *conn, const char *dumpdirpath,
 		 db_cell; db_cell = db_cell->next)
 	{
 		char		subdirpath[MAXPGPATH];
+		char		subdirdbpath[MAXPGPATH];
+		char		dbfilename[MAXPGPATH];
 		int			n_errors;
 
 		/* ignore dbs marked for skipping */
@@ -1180,7 +1182,25 @@ restoreAllDatabases(PGconn *conn, const char *dumpdirpath,
 			opts->cparams.override_dbname = NULL;
 		}
 
-		snprintf(subdirpath, MAXPGPATH, "%s/databases/%u", dumpdirpath, db_cell->oid);
+		snprintf(subdirdbpath, MAXPGPATH, "%s/databases", dumpdirpath);
+
+		/*
+		 * Validate database dump file.  If there is .tar or .dmp file exist
+		 * then consider particular file, otherwise just append dboid to the
+		 * databases folder.
+		 */
+		snprintf(dbfilename, MAXPGPATH, "%u.tar", db_cell->oid);
+		if (file_exists_in_directory(subdirdbpath, dbfilename))
+			snprintf(subdirpath, MAXPGPATH, "%s/databases/%u.tar", dumpdirpath, db_cell->oid);
+		else
+		{
+			snprintf(dbfilename, MAXPGPATH, "%u.dmp", db_cell->oid);
+
+			if (file_exists_in_directory(subdirdbpath, dbfilename))
+				snprintf(subdirpath, MAXPGPATH, "%s/databases/%u.dmp", dumpdirpath, db_cell->oid);
+			else
+				snprintf(subdirpath, MAXPGPATH, "%s/databases/%u", dumpdirpath, db_cell->oid);
+		}
 
 		pg_log_info("restoring database \"%s\"", db_cell->str);
 
-- 
2.39.3

