From 7c4672541be5e806e1470160f67c600cc8d69980 Mon Sep 17 00:00:00 2001
From: Jelte Fennema <jelte.fennema@microsoft.com>
Date: Thu, 31 Aug 2023 10:57:50 +0200
Subject: [PATCH v1] pg_basebackup: Always return valid temporary slot names

With PgBouncer in the middle PQbackendPID can return negative values
due to it filling all 32 bits of the be_pid with random bits.

When this happens it results in pg_basebackup generating an invalid slot
name (when no specific slot name is passed in) and thus throwing an
error like this:

pg_basebackup: error: could not send replication command "CREATE_REPLICATION_SLOT "pg_basebackup_-1201966863" TEMPORARY PHYSICAL ( RESERVE_WAL)": ERROR:  replication slot name "pg_basebackup_-1201966863" contains invalid character
HINT:  Replication slot names may only contain lower case letters, numbers, and the underscore character.

This patch fixes that problem by formatting the result from PQbackendPID
as an unsigned integer when creating the temporary replication slot
name.
---
 src/bin/pg_basebackup/pg_basebackup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 1dc8efe0cb7..b744a3e96fd 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -651,7 +651,7 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 	 * Create replication slot if requested
 	 */
 	if (temp_replication_slot && !replication_slot)
-		replication_slot = psprintf("pg_basebackup_%d", (int) PQbackendPID(param->bgconn));
+		replication_slot = psprintf("pg_basebackup_%u", (unsigned) PQbackendPID(param->bgconn));
 	if (temp_replication_slot || create_slot)
 	{
 		if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,

base-commit: f94dec76cc7aa1dc1636708e81581f9b84e7e15c
-- 
2.34.1

