From e062dc164da02619f0716fa78ff0f9e422490c65 Mon Sep 17 00:00:00 2001
From: Jianghua Yang <yjhjstz@gmail.com>
Date: Fri, 20 Mar 2026 06:30:03 -0700
Subject: [PATCH] initdb: reject empty string for -U/--username option

Previously, passing an empty string to initdb's -U option (e.g.,
initdb -U '') was accepted without complaint, but later caused a
confusing FATAL error during bootstrap SQL execution.

Add an explicit check for an empty superuser name before the existing
pg_ prefix validation, so that the user gets a clear error message
upfront.

Discussion: https://postgr.es/m/10700.1751736853@sss.pgh.pa.us
---
 src/bin/initdb/initdb.c        | 3 +++
 src/bin/initdb/t/001_initdb.pl | 3 +++
 2 files changed, 6 insertions(+)

diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c
index 509f1114ef6..25cd398cc6c 100644
--- a/src/bin/initdb/initdb.c
+++ b/src/bin/initdb/initdb.c
@@ -3500,6 +3500,9 @@ main(int argc, char *argv[])
 	if (!username)
 		username = effective_user;
 
+	if (username[0] == '\0')
+		pg_fatal("superuser name must not be empty");
+
 	if (strncmp(username, "pg_", 3) == 0)
 		pg_fatal("superuser name \"%s\" is disallowed; role names cannot begin with \"pg_\"", username);
 
diff --git a/src/bin/initdb/t/001_initdb.pl b/src/bin/initdb/t/001_initdb.pl
index 081535a22e4..8c54461fe98 100644
--- a/src/bin/initdb/t/001_initdb.pl
+++ b/src/bin/initdb/t/001_initdb.pl
@@ -34,6 +34,9 @@ command_fails(
 	[ 'initdb', '--waldir' => 'pgxlog', $datadir ],
 	'relative xlog directory not allowed');
 
+command_fails_like([ 'initdb', '--username' => '', $datadir ],
+	qr/superuser name must not be empty/,
+	'empty username not allowed');
 command_fails([ 'initdb', '--username' => 'pg_test', $datadir ],
 	'role names cannot begin with "pg_"');
 
-- 
2.50.1 (Apple Git-155)

