我是作者pg-承诺 https://github.com/vitaly-t/pg-promise;) 这不是第一次被问到这个问题,所以我在这里给出详细的解释。
当您像这样实例化一个新的数据库对象时:
const db = pgp(connection);
...它所做的一切 - 创建对象,但它不会尝试连接。该库构建在连接池之上,只有实际的查询方法才从池中请求连接。
来自官方文档 http://vitaly-t.github.io/pg-promise/index.html:
Object db
代表数据库协议,具有惰性数据库连接,即只有实际的查询方法获取和释放连接。因此,您应该只创建一个全局/共享db
每个连接的对象详细信息。
但是,您可以通过调用方法强制连接connect http://vitaly-t.github.io/pg-promise/Database.html#connect,如进一步所示。虽然这种方法不是链接查询的推荐方法(Tasks https://github.com/vitaly-t/pg-promise/wiki/Learn-by-Example#tasks应该用于此目的),它通常可以方便地检查连接。
我从我自己的帖子中复制了示例:https://github.com/vitaly-t/pg-promise/issues/81 https://github.com/vitaly-t/pg-promise/issues/81
下面是同时使用两种方法的示例,因此您可以选择您更喜欢的方法。
const initOptions = {
// global event notification;
error(error, e) {
if (e.cn) {
// A connection-related error;
//
// Connections are reported back with the password hashed,
// for safe errors logging, without exposing passwords.
console.log('CN:', e.cn);
console.log('EVENT:', error.message || error);
}
}
};
const pgp = require('pg-promise')(initOptions);
// using an invalid connection string:
const db = pgp('postgresql://userName:password@host:port/database');
db.connect()
.then(obj => {
// Can check the server version here (pg-promise v10.1.0+):
const serverVersion = obj.client.serverVersion;
obj.done(); // success, release the connection;
})
.catch(error => {
console.log('ERROR:', error.message || error);
});
Outputs:
CN: postgresql://userName:########@host:port/database EVENT: getaddrinfo ENOTFOUND host host:5432 ERROR: getaddrinfo ENOTFOUND host host:5432
库中的每个错误都会首先通过全局报告error http://vitaly-t.github.io/pg-promise/global.html#event:error事件处理程序,然后才会在相应的事件处理程序中报告错误.catch
处理程序。
Update
一步测试连接+获取服务器版本的现代方法:
// tests connection and returns Postgres server version,
// if successful; or else rejects with connection error:
async function testConnection() {
const c = await db.connect(); // try to connect
c.done(); // success, release connection
return c.client.serverVersion; // return server version
}
Links
- Method connect http://vitaly-t.github.io/pg-promise/Database.html#connect
- Event error http://vitaly-t.github.io/pg-promise/global.html#event:error