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

时间:2018-10-29 09:19:46

标签: node.js postgresql knex.js node-postgres

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

我希望我可以做类似的事情:

const { Client } = require('pg')

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

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

有什么方法可以为knex提供pg客户端对象,而不是让它管理自己的连接池吗?

2 个答案:

答案 0 :(得分:2)

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

此处描述了编写自定义方言的过程

答案 1 :(得分:1)

解决方法

我认为有办法做到这一点,但只能通过特定的查询来完成。为此,您可以使用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();

moleculer一起使用的情况

作为示例,我将其与提供数据库适配器的moleculer一起使用,该数据库适配器本身已经使用了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();
            });
    }
};

相关文档

相关链接