Alexander Ho
Alexander Ho

Reputation: 533

Knex is not reading connection string from knexfile

I have been given a knexfile like this:

require('dotenv').config()

module.exports = {
  client: 'pg',
  connection: process.env.DB_CONNECTION,
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    tableName: 'knex_migrations'
  }
};

The connection string I supply is:

Host=localhost;Database=heypay;Username=postgres;Password=1234

However, Knex keeps issuing the error:

 password authentication failed for user "user"

Apparently, the username I have given is not user. Moreover, I have tried to hardcore the connection string into the connection filed under module.exports. This still ended up in vain.

Upvotes: 3

Views: 6512

Answers (2)

Rich Churcher
Rich Churcher

Reputation: 7654

The trick is, the connection property can either be a string or an object. That's why you were able to supply an environment variable (it's a string).

The reason your original string was failing is not a Knex problem: Postgres connection strings have a slightly different format. You can use a similar approach as your first attempt, but pay attention to the key names:

host=localhost port=5432 dbname=mydb connect_timeout=10

Also note spaces, not semicolons. However in my experience most people use a Postgres URI:

postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]

So in your example, you'd use:

module.exports = {
  client: 'pg',
  connection: 'postgresql://your_database_user:password@localhost/myapp_test',
  pool: {
    min: 2,
    max: 10
  },
  migrations: {
    tableName: 'knex_migrations'
  }
};

Upvotes: 2

Alexander Ho
Alexander Ho

Reputation: 533

I was using a .NET style connection string, the correct one would be in the following format:

{
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
}

Upvotes: 0

Related Questions