Skip to content

Commit

Permalink
pg-connection-string: avoid clobbering port from queryparams (#2833)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
rafiss authored Jul 21, 2023
1 parent 3644730 commit cf24ef2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/pg-connection-string/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions packages/pg-connection-string/test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})

0 comments on commit cf24ef2

Please sign in to comment.