简体   繁体   中英

Using Knex with own pg connection pool

I would like to use knex as a query builder, but my project already handles its own connection pool.

I wish I could to do something like:

const { Client } = require('pg')

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

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

Is there any way to provide knex with the pg client object, instead of letting it to manage its own connection pool?

Workaround

I think there is a way to do that, but it can be done only with a specific query. To do that you can use the connection(pool) method that accept a connection pool instance as argument.

In my case I have required knex without passing a connection argument and then when the connection was established I saved the connection instance in my object. Then when I have to use knex as client I passed the connection instance in the query building.

Code example

Here a code example:

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();

Use case with moleculer

As an example, I have used that with moleculer that provides a Database Adapter that use already itself a SQL client, so knex would build an additional connection to my db. After I retrieved the connection in my microservice I've used that inside knex in the same way described above.

"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();
            });
    }
};

Related documentation

Related links

No. Unless you write your own custom dialect and override connection fetching functionality. Writing custom dialect is described here https://github.com/tgriesser/knex/blob/master/CONTRIBUTING.md#i-would-like-to-add-support-for-new-dialect-to-knex-is-it-possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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