node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

feat: allow all config options when using connection string and object

Open satire-foxfire opened this issue 1 year ago • 1 comments

I don't believe there is a way to do this currently, so I believe this would fall more into a feature request than a question, but let me know if there is a way to do this with the current functionality.

Currently you can use both a connection string while still specifying some options like ssl, but other options like user or password don't appear to get merged (they're ignored) unless they're explicitly part of the connection string.

Works:

const connectionString = 'postgres://user:password@hostname:port/database';
const client = new pg.Client({
  connectionString,
  ssl: true,
});

Doesn't work:

const connectionString = 'postgres://hostname:port/database';
const client = new pg.Client({
  connectionString,
  user: 'user',
  password: 'password',
  ssl: true,
});

The alternative I have right now is preparsing the connection string into an instance of URL first, then manually setting url.user = 'user' and url.password = 'password', and then stringifying it before passing it into the client:

const connectionString = 'postgres://hostname:port/database';
const url = new URL(connectionString);

url.user = 'user';
url.password = 'password';

const client = new pg.Client({
  connectionString: String(connectionString),
  ssl: true,
});

It'd be really nice for all the properties to "just work", while keeping the same behavior that anything defined in the connection string directly will take precedence.

satire-foxfire avatar Oct 09 '24 02:10 satire-foxfire

We would have to define what happens if you specified the password in the connection string and the object. I imagine that gets complicated.

Two suggestions:

  1. Use query params

If you have postgres://hostname:port/database then you can specify the user and password like this

postgres://@hostname:port/database?user=my_user&password=my_password

For complete safety, this would require us to parse the string into a URL, add the query params and then convert to a string. If you were not concerned with safety then

connectionString + '?user=my_user&password=my_password' is fairly terse.

  1. Parse ahead of time
import { parse } from 'pg-connection-string';

const connectionString = 'postgres://hostname:port/database';
const config = parse(connectionString);
config.user = 'my_user';
config.password = 'my_password';

const client = new pg.Client(config);

hjr3 avatar Nov 16 '24 12:11 hjr3