Accessing Lucid's Knex Connection Client

In This Snippet

Ever need to directly access KnexJS, the query builder Lucid wraps around? Here's how you can do it!

Created by
@tomgobich
Published

Under the hood, AdonisJS' ORM Lucid, wraps around KnexJS for a number of its query-building capabilities. Eventually, you may find yourself in a situation, like I did recently, where you specifically need just the KnexJS client. In my case, I needed to use a third-party plugin that specifically required the KnexJS type… but your use-case could really be anything.

Thankfully, this can be done nice and easily!

import db from '@adonisjs/lucid/services/db'

const knex = db.connection().getWriteClient()

const testCourse = await knex('courses').where('name', 'test')
Copied!

Now, note that the db we're importing here is a ready-to-go instance of the Database Query Builder from Lucid. Meaning, in order to use it, our application must be booted and have a database connection setup.

By calling db.connection(), we're getting back Lucid's QueryClient instance, which holds the active connection to our database. That active connection is then what has access to the KnexJS instance we're after, and what we get back by calling getWriteClient().

Hope this helps, and happy coding!

Join the Discussion 0 comments

Create a free account to join in on the discussion
robot comment bubble

Be the first to comment!