【问题标题】:Get the PostgreSQL server version from connection?从连接中获取 PostgreSQL 服务器版本?
【发布时间】:2021-06-10 04:46:14
【问题描述】:

现代 PostgreSQL 连接协议中是否有任何指示服务器版本的内容?

如果没有,端点是否可以针对打开的连接执行特殊的低级请求,以提取包含版本的服务器详细信息?

我正在寻找node-postgres 的可能扩展,它将在每次新连接时自动提供服务器版本。我想知道这是否可能。

必须在每个新连接上执行SELECT version() 然后解析它对于管理连接的基本驱动程序来说太高级了。它应该在协议级别完成。

【问题讨论】:

  • 您实际上不需要解析来自version() 的输出。您可以使用show server_version_numshow server_version 获得更“友好”的号码。底层的 Postgres 协议确实提供了服务器版本,并且连接对象可以在没有查询的情况下返回它:postgresql.org/docs/current/… 但我不知道这是否可以从 Node.js 中获得
  • 只是建议elsewhere start-up message 可能包含版本。
  • 那么另一方面,在建立连接后运行show server_version,实际上并没有那么大的开销。
  • @a_horse_with_no_name 我们应该不需要执行任何查询,服务器应该会自动提供版本,我相信它会提供,只需要弄清楚到底如何。
  • @a_horse_with_no_name I have found out that it already does :)

标签: postgresql node-postgres


【解决方案1】:

经过一番研究,我发现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

更新

pg-promise 已更新以支持 TypeScript 中的相同功能。你可以在this ticket找到一个完整的例子。

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2019-10-08
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多