brianc / node-postgres

PostgreSQL client for node.js.
https://node-postgres.com
MIT License
12.03k stars 1.21k forks source link

host reading as "base" by default instead of localhost #3108

Open jbenjoy2 opened 6 months ago

jbenjoy2 commented 6 months ago

SYSTEM:

when instantiating a new pg.client({}) object, when using pg-connection-string version 2.5.0 or lower, if i supply a connectionString to the config object that is simply the string name of the database (See below for example), it defaults the host of the URI to be localhost (as expected). Now, in newer versions, even if i have a PGHOST env var set, even if i manually add "localhost" to the config as the value for the host property, it is reading the host as "base". There doesn't seem to be a way for me to change that, except to set the connectionString property to be the entire full postgres URI. I dont know if this is desired behavior but it definitely doesn't appear to be working as expected.

In the docs for pg, it says this about connecting: "The default values for the environment variables used are:

PGHOST=localhost PGUSER=process.env.USER PGDATABASE=process.env.USER PGPASSWORD=null PGPORT=5432 "

this doesn't seem to be the case however as it is defaulting to "base".

CODE EXAMPLE

export const db = new Client({
  connectionString: getDatabaseUri("workout_tracker"),
});

db.connect();

export const getDatabaseUri = (dbName: string) => {
 return process.env.NODE_ENV === "test"
    ? `${dbName}_test`
    : process.env.DATABASE_URL || `${dbName}`;
};

The above resulting code returns the connectionString object to be, if passed a database name of "fooBar", to just be "fooBar" if there is no env var set, and if it is not a test environment.

Again, in previous versions, before pg-connection-string version 2.6.2, this worked as expected. Please also note that adding to my .env the following: PGHOST='localhost'

this does not fix the issue, nor does changing the client config to look like the folowing:


export const db = new Client({
  connectionString: getDatabaseUri("workout_tracker"),
  host: 'localhost'
});

Please advise on how to get the expected behavior from early versions. I can show the resulting errors upon request
charmander commented 6 months ago

This is caused by f305419676afe79a91dc7863289f7f97ac6db3d5 from #2971.

The above resulting code returns the connectionString object to be, if passed a database name of "fooBar", to just be "fooBar" if there is no env var set, and if it is not a test environment.

That’s not a connection string, so you shouldn’t pass it as the connectionString property.

`postgres:///${dbName}_test`