Knex Migration Postgres Heroku - 错误:无法获取连接

时间:2017-01-13 11:14:26

标签: node.js heroku database-migration knex.js heroku-postgres

我正在尝试运行我的第一个迁移,它在heroku postgres数据库中创建一个表。

当我尝试运行knex migrate:latest --env development时,收到错误Error: Unable to acquire a connection

我尝试过的事情:

  • ?ssl=true添加到存储在process.env.LISTINGS_DB_URL中的连接字符串的末尾,因为我知道有时需要连接heroku
  • 设置env变量PGSSLMODE=require

我偶然发现this article有人评论说knex不接受基于环境的密钥。但是,我试图跟随this tutorial,这表明它确实如此。我还看到了许多其他引用来强化它。

我还要补充一点,我已经能够从我的应用程序和外部客户端连接到数据库。我在尝试运行knex迁移时遇到了这个错误。

此外,我已经尝试确定如何检查作为连接字符串发送的内容。在查看knex documentation时,我会在“如何调试常见问题部分:”If you pass {debug: true} as one of the options in your initialize settings, you can see all of the query calls being made下看到。有人可以帮我指导我的实际操作吗?或者我已经在我的knexfile.js中成功完成了它?

我的knex.js文件:

var environment = process.env.NODE_ENV || 'development';
var config = require('../knexfile.js')[environment];

module.exports = require('knex')(config);

我的knexfile.js:

module.exports = {

    development: {
        client: 'pg',
        connection: process.env.LISTINGS_DB_URL,
        migrations: {
            directory: __dirname + '/db/migrations'
        },
        seeds: {
            directory: __dirname + '/db/seeds'
        },
        debug: true
    },

    staging: {
        client: 'postgresql',
        connection: {
            database: 'my_db',
            user: 'username',
            password: 'password'
        },
        pool: {
            min: 2,
            max: 10
        },
        migrations: {
            tableName: 'knex_migrations'
        }
    },

    production: {
        client: 'postgresql',
        connection: {
            database: 'my_db',
            user: 'username',
            password: 'password'
        },
        pool: {
            min: 2,
            max: 10
        },
        migrations: {
            tableName: 'knex_migrations'
        }
    }

};

4 个答案:

答案 0 :(得分:5)

正如@hhoburg在下面的评论中所指出的,错误Error: Unable to acquire a connection是一条通用消息,表明某些内容与Knex client configuration不一致。请参阅here

就我而言,Knex没有在knexfile.js中引用process.env.LISTINGS_DB_URL,因为:

  • 该变量已在我的.env文件中设置
  • Knex
  • 未引用/调用dotenv module

knex问题跟踪器here详细说明了设置此功能的正确方法。

答案 1 :(得分:2)

我不确定这是否会有所帮助,但我今天开始在我的本地环境中遇到同样的问题。经过太多搜索后,我发现this is the new error message表示连接配置无效或连接池丢失。在摆弄了太长时间之后,我将连接切换为使用我的.env文件进行配置环境;我一直在我的knex.js文件中使用了一个硬编码的字符串('dev'),但由于某些原因它无效。

您的.env文件是否正常运行?您是否尝试过使用池设置?您是否肯定您的用户名和密码对于登台和生产数据库是否正确?

我希望链接有帮助!

答案 2 :(得分:0)

第1步:

首先安装dotenv:

npm i dotenv --save

在项目的根目录中创建一个.env文件,然后添加:

DATABASE_URL=postgres://...

第2步:

在您的knexfile.js的开头,添加:

require('dotenv').config();

将postgres连接更改为:

{
  client: 'postgresql',
  connection: process.env.DATABASE_URL,
  pool: {
    min: 0,
    max: 15
  },
  migrations: {
    directory: ...
  },
  seeds: {
    directory: ...
  }
}

答案 3 :(得分:0)

在相同情况下,我也收到此错误。原来,我忘了在迁移之前配置数据库,所以没有什么可连接的。

要解决此错误,

运行之前:

heroku run knex migrate:latest

我运行了以下命令:

heroku addons:create heroku-postgresql

效果很好。