Accessing Lucid's Knex Connection Client

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

Published
Sep 15

Developer, dog lover, and burrito eater. Currently teaching AdonisJS, a fully featured NodeJS framework, and running Adocasts where I post new lessons weekly. Professionally, I work with JavaScript, .Net C#, and SQL Server.

Adocasts

Burlington, KY

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)

Please sign in or sign up for free to join in on the dicussion.

robot comment bubble

Be the first to Comment!