Skip to content

Instantly share code, notes, and snippets.

@jeremija
Last active September 26, 2017 01:59
Show Gist options
  • Save jeremija/c2603b94aeb0710cdc2c2f24bdf2fe89 to your computer and use it in GitHub Desktop.
Save jeremija/c2603b94aeb0710cdc2c2f24bdf2fe89 to your computer and use it in GitHub Desktop.
knex raw query with where (example)
'use strict'
const knex = require('knex')
const { expect } = require('chai')
const db = knex({
client: 'sqlite3',
connection: ':memory:',
useNullAsDefault: true
})
describe('raw', () => {
it('test', () => {
expect(db.select().toString()).to.equal('select *')
})
it('works with raw queries', () => {
const q = db.raw('select * from test where a = :a', { a: 1 })
expect(q.toString()).to.equal('select * from test where a = 1')
})
function raw (query) {
query = query.replace(/^ *?select +/i, '')
return db.select(
db.raw(query)
).where({ a: 2 })
}
it('appends where clause to raw query', () => {
const p = raw(' select * from test')
expect(p.toString()).to.equal('select * from test where "a" = 2')
})
})
{
"dependencies": {
"chai": "^4.1.2",
"knex": "^0.13.0",
"mocha": "^3.5.3",
"sqlite3": "^3.1.12"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment