From 77326a030fd2ffa4ae012aae28540b3d8f5bd4ef Mon Sep 17 00:00:00 2001
From: Jianghua Yang <yjhjstz@gmail.com>
Date: Wed, 2 Jul 2025 06:48:48 -0700
Subject: [PATCH] initdb: Reject empty string for -U/--username option

Previously, passing an empty string to the -U or --username option
(e.g., `initdb -U ''`) would cause confusing errors during bootstrap,
as initdb attempted to create a role with an empty name.

This patch adds an explicit check for empty usernames and exits
immediately with a clear error message.

A test case is added to verify that initdb fails when -U is given an
empty string.
---
 src/bin/initdb/initdb.c        | 5 +++++
 src/bin/initdb/t/001_initdb.pl | 4 ++++
 2 files changed, 9 insertions(+)

diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 62bbd08d9f6..0fd67ad496f 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -3291,6 +3291,11 @@ main(int argc, char *argv[])
 				pwprompt = true;
 				break;
 			case 'U':
+				if (optarg[0] == '\0')
+				{
+					pg_log_error("superuser name must not be empty");
+					exit(1);
+				}
 				username = pg_strdup(optarg);
 				break;
 			case 'd':
diff --git a/src/bin/initdb/t/001_initdb.pl b/src/bin/initdb/t/001_initdb.pl
index 15dd10ce40a..67eb53064f6 100644
--- a/src/bin/initdb/t/001_initdb.pl
+++ b/src/bin/initdb/t/001_initdb.pl
@@ -37,6 +37,10 @@ command_fails(
 command_fails([ 'initdb', '--username' => 'pg_test', $datadir ],
 	'role names cannot begin with "pg_"');
 
+command_fails(
+	[ 'initdb', '-U', '', $datadir ],
+	'empty username not allowed');
+
 mkdir $datadir;
 
 # make sure we run one successful test without a TZ setting so we test
-- 
2.39.5 (Apple Git-154)

