现代 PostgreSQL 连接协议(protocol)中是否有任何内容可以指示服务器版本?
如果没有,是否有端点可以针对打开的连接执行的特殊低级请求,以提取包含该版本的服务器详细信息?
我正在寻找 node-postgres 的可能扩展这将在每次新连接时自动提供服务器版本。我想知道这是否可能。
必须在每个新连接上执行 SELECT version()
然后解析它对于管理连接的基本驱动程序来说太高级了。它应该在协议(protocol)级别完成。
最佳答案
经过一些研究,我发现 PostgreSQL 在连接期间确实提供服务器版本,在 start-up message 内.
特别是在 node-postgres 内司机,我们可以做Pool提供定制Client处理连接上的事件 parameterStatus
,并公开服务器版本:
const {Client, Pool} = require('pg');
class MyClient extends Client {
constructor(config) {
super(config);
this.connection.on('parameterStatus', msg => {
if (msg.parameterName === 'server_version') {
this.version = msg.parameterValue;
}
});
}
}
const cn = {
database: 'my-db',
user: 'postgres',
password: 'bla-bla',
Client: MyClient // here's our custom Client type
};
const pool = new Pool(cn);
pool.connect()
.then(client => {
console.log('Server Version:', client.version);
client.release(true);
})
.catch(console.error);
在我的测试 PC 上,我使用 PostgreSQL v11.2,所以这个测试输出:
Server Version: 11.2
更新 - 1
图书馆 pg-promise已更新以支持 TypeScript 中的相同功能。您可以在 this ticket 中找到完整示例.
更新 - 2
// 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
}
关于postgresql - 从连接中获取 PostgreSQL 服务器版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58725659/