From 6b14ef841bf0e15e0fffbf1381bae186e1913258 Mon Sep 17 00:00:00 2001
From: Ryo Kanbayashi <ryo.contact@gmail.com>
Date: Fri, 27 Jun 2025 21:16:02 +0900
Subject: [PATCH v11 3/3] psql enhancement related servicefile option on
 connection string

---
 doc/src/sgml/ref/psql-ref.sgml    |  9 +++++++++
 src/bin/psql/command.c            |  2 ++
 src/interfaces/libpq/fe-connect.c | 22 ++++++++++++++++++++++
 3 files changed, 33 insertions(+)

diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml
index 95f4cac2467..4f7b11175c6 100644
--- a/doc/src/sgml/ref/psql-ref.sgml
+++ b/doc/src/sgml/ref/psql-ref.sgml
@@ -4623,6 +4623,15 @@ bar
         </listitem>
       </varlistentry>
 
+      <varlistentry id="app-psql-variables-servicefile">
+        <term><varname>SERVICEFILE</varname></term>
+        <listitem>
+        <para>
+        The service file name, if applicable.
+        </para>
+        </listitem>
+      </varlistentry>
+
       <varlistentry id="app-psql-variables-shell-error">
        <term><varname>SHELL_ERROR</varname></term>
        <listitem>
diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c
index 9fcd2db8326..b65c5633e5a 100644
--- a/src/bin/psql/command.c
+++ b/src/bin/psql/command.c
@@ -4490,6 +4490,7 @@ SyncVariables(void)
 
 	SetVariable(pset.vars, "DBNAME", PQdb(pset.db));
 	SetVariable(pset.vars, "SERVICE", PQservice(pset.db));
+	SetVariable(pset.vars, "SERVICEFILE", PQserviceFile(pset.db));
 	SetVariable(pset.vars, "USER", PQuser(pset.db));
 	SetVariable(pset.vars, "HOST", PQhost(pset.db));
 	SetVariable(pset.vars, "PORT", PQport(pset.db));
@@ -4524,6 +4525,7 @@ UnsyncVariables(void)
 {
 	SetVariable(pset.vars, "DBNAME", NULL);
 	SetVariable(pset.vars, "SERVICE", NULL);
+	SetVariable(pset.vars, "SERVICEFILE", NULL);
 	SetVariable(pset.vars, "USER", NULL);
 	SetVariable(pset.vars, "HOST", NULL);
 	SetVariable(pset.vars, "PORT", NULL);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index b94c6ce94bc..7ea3c673696 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -6158,6 +6158,28 @@ parseServiceFile(const char *serviceFile,
 	}
 
 exit:
+
+	/* If service was found successfully, set servicefile option if not already set */
+	if (*group_found && result == 0)
+	{
+		for (i = 0; options[i].keyword; i++)
+		{
+			if (strcmp(options[i].keyword, "servicefile") == 0)
+			{
+				if (options[i].val == NULL)
+				{
+					options[i].val = strdup(serviceFile);
+					if (!options[i].val)
+					{
+						libpq_append_error(errorMessage, "out of memory");
+						return 3;
+					}
+				}
+				break;
+			}
+		}
+	}
+
 	fclose(f);
 
 	return result;
-- 
2.34.1

