From 2133f5ea986f057486d5d9cab11a19b0d1d099de Mon Sep 17 00:00:00 2001
From: "Chao Li (Evan)" <lic@highgo.com>
Date: Tue, 2 Jun 2026 16:50:44 +0800
Subject: [PATCH v1] libpq: Report correct service file after fallback

When an explicitly specified service file does not contain the requested
service, libpq falls back to the system-wide pg_service.conf file.  If the
service is found there, however, the "servicefile" connection option still
reported the explicitly specified file.

Update the option after a successful fallback so that PQconninfo() and
psql's SERVICEFILE variable report the file that supplied the service.
Add a TAP test for this case.

Author: Chao Li <lic@highgo.com>
---
 src/interfaces/libpq/fe-connect.c     | 5 +++++
 src/interfaces/libpq/t/006_service.pl | 8 ++++++++
 2 files changed, 13 insertions(+)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index 4272d386e64..d6d5ad14c6a 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -6049,6 +6049,11 @@ next_file:
 	status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
 	if (status != 0)
 		return status;
+	/* Update servicefile to the file that actually supplied the service */
+	if (group_found && service_fname != NULL &&
+		conninfo_storeval(options, "servicefile", serviceFile,
+						  errorMessage, false, false) == NULL)
+		return 3;
 
 last_file:
 	if (!group_found)
diff --git a/src/interfaces/libpq/t/006_service.pl b/src/interfaces/libpq/t/006_service.pl
index 7462d21314d..144248b8533 100644
--- a/src/interfaces/libpq/t/006_service.pl
+++ b/src/interfaces/libpq/t/006_service.pl
@@ -143,6 +143,14 @@ local $ENV{PGSERVICEFILE} = "$srvfile_empty";
 		sql => "SELECT 'connect2_3'",
 		expected_stdout => qr/connect2_3/);
 
+	my $srvfile_empty_win_cared = $srvfile_empty;
+	$srvfile_empty_win_cared =~ s/\\/\\\\/g;
+	$dummy_node->connect_ok(
+		q{service=my_srv servicefile='} . $srvfile_empty_win_cared . q{'},
+		'servicefile option is updated when service is found in default pg_service.conf',
+		sql => '\echo :SERVICEFILE',
+		expected_stdout => qr/^\Q$srvfile_default\E$/);
+
 	local $ENV{PGSERVICE} = 'undefined-service';
 	$dummy_node->connect_fails(
 		'',
-- 
2.50.1 (Apple Git-155)

