繁体   English   中英

将 Knex 与自己的 pg 连接池一起使用

[英]Using Knex with own pg connection pool

我想使用 knex 作为查询构建器,但我的项目已经处理了自己的连接池。

我希望我可以做这样的事情:

const { Client } = require('pg')

const client = new Client()
await client.connect()

const knex = require('knex')({
    client: 'pg',
    connection: client,
})

有没有办法为 knex 提供 pg 客户端对象,而不是让它管理自己的连接池?

解决方法

我认为有一种方法可以做到这一点,但只能通过特定查询来完成。 为此,您可以使用接受连接池实例作为参数的connection(pool)方法。

在我的情况下,我需要 knex 而不传递连接参数,然后在建立连接时我将连接实例保存在我的对象中。 然后当我必须使用 knex 作为客户端时,我在查询构建中传递了连接实例。

代码示例

这是一个代码示例:

const knex = require('knex')({
   client: 'pg' // postgreSQL or whatever
});

const poolConnection = await new Client().connect(); // or any other method to create your connection here

// when you have to query your db
const results = await knex('users')
                .connection(poolConnection) // here pass the connection
                .where({
                    email: 'test@tester.com'
                })
                .select('id', 'email', 'createdAt')
                .offset(0)
                .limit(1)
                .first();

使用分子的用例

例如,我将它与提供数据库适配器的分子一起使用,该数据库适配器本身已经使用了 SQL 客户端,因此 knex 将建立到我的数据库的额外连接。 在我的微服务中检索连接后,我以与上述相同的方式在 knex 内部使用了该连接。

"use strict";
const DbService = require("moleculer-db");
const SQLAdapter = require("moleculer-db-adapter-sequelize");
const Sequelize = require("sequelize");

// here requiring knex without an actual connection
const knex = require("knex")({
    client: "pg"
});


module.exports = {
    name: "users",
    // implementing moleculer ORM
    mixins: [DbService],
    adapter: new SQLAdapter(process.env.POSTGRECONNECTIONSTRING),
    model: {
        name: "user",
        define: {
            id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true
            },
            email: Sequelize.STRING,
            password: Sequelize.STRING,
        }
    },
    actions: {
        findByIdRaw: {
            params: {
                id: "number"
            },
            handler(ctx) {
                const { id } = ctx.params;
                // use the connection pool instance
                return knex("users")
                    .connection(this.connection)
                    .where({
                        id
                    })
                    .select("id", "email", "createdAt")
                    .offset(0)
                    .limit(1)
                    .first();
            }
        }
    },
    started() {
        // getting the connection from the adapter
        return this.adapter.db.connectionManager.getConnection()
            .then((connection) => {
                // saving connection
                this.connection = connection;
                return Promise.resolve();
            });
    }
};

相关文档

相关链接

否。除非您编写自己的自定义方言并覆盖连接获取功能。 此处描述了编写自定义方言https://github.com/tgriesser/knex/blob/master/CONTRIBUTING.md#i-would-like-to-add-support-for-new-dialect-to-knex-is-可能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM