From cf24ef28ee2134b63576afba341452f8adfb8a4d Mon Sep 17 00:00:00 2001 From: Rafi Shamim Date: Fri, 21 Jul 2023 12:57:02 -0400 Subject: [PATCH] pg-connection-string: avoid clobbering port from queryparams (#2833) If the connection string is something like: postgresql://demo:password@/postgres?host=localhost&port=26258 Then the port from the query parameters should be used. Previously, the parsing function would end up with a null port, and the default port would end up being used by the connecetion package. --- packages/pg-connection-string/index.js | 5 ++++- packages/pg-connection-string/test/parse.js | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/pg-connection-string/index.js b/packages/pg-connection-string/index.js index fc2052365..c7fc72a36 100644 --- a/packages/pg-connection-string/index.js +++ b/packages/pg-connection-string/index.js @@ -38,7 +38,6 @@ function parse(str) { config.user = config.user || decodeURIComponent(result.username) config.password = config.password || decodeURIComponent(result.password) - config.port = result.port if (result.protocol == 'socket:') { config.host = decodeURI(result.pathname) config.database = result.searchParams.get('db') @@ -53,6 +52,10 @@ function parse(str) { // Only prepend the hostname to the pathname if it is not a URL encoded Unix socket host. result.pathname = hostname + result.pathname } + if (!config.port) { + // Only set the port if there is no equivalent query param. + config.port = result.port + } const pathname = result.pathname.slice(1) || null config.database = pathname ? decodeURI(pathname) : null diff --git a/packages/pg-connection-string/test/parse.js b/packages/pg-connection-string/test/parse.js index 749717d03..375aae4aa 100644 --- a/packages/pg-connection-string/test/parse.js +++ b/packages/pg-connection-string/test/parse.js @@ -318,4 +318,10 @@ describe('parse', function () { var subject = parse(connectionString) subject.keepalives.should.equal('0') }) + + it('use the port specified in the query parameters', function () { + var connectionString = 'postgres:///?host=localhost&port=1234' + var subject = parse(connectionString) + subject.port.should.equal('1234') + }) })