Knex: What is the correct way to return a single value from select query?

Created on 18 Apr 2016  ·  4Comments  ·  Source: knex/knex

The simple way to do select query in knex is like this:

db('table_name').where({ id: 1 }).select();

But, it return an array. Since id is a unique field, it's clear that I
expect a single result. And then, I have to do something like this:

db('table_name').where({ id: 1 }).select().then(result => result[0]);

Is there any _official_ way to return a single value?

question

Most helpful comment

db('table_name').where({id: 1}).first().then((row) => row)

Should work

All 4 comments

db('table_name').where({id: 1}).first().then((row) => row)

Should work

Oh, it's actually first and I keep looking for one, selectOne, etc. Thanks

db('table_name').where({id: 1}).first(); this would work the same. no?

@arch-mage If there should be only single matching result, then it's a best practice to ensure it, common single implementations do it using limit 2. Here's how to add it to Knex.

import Knex from 'knex'

declare module 'knex' {
  interface QueryInterface {
    _method: string
    _isSelectQuery: () => boolean
    single: (columns?: string | string[], notFoundMessage?: string, notSingleMessage?: string) => Promise<any>
  }
}

Knex.QueryBuilder.extend('single', function single(
  this: Knex.QueryBuilder,
  columns: string | string[] = '*',
  notFoundMessage?: string,
  notSingleMessage?: string,
): any {
  // eslint-disable-next-line no-underscore-dangle
  if (!this._isSelectQuery() || this._method === 'first')
    // eslint-disable-next-line no-underscore-dangle
    throw new Error(`Cannot chain .single() on "${this._method}" query!`)
  // eslint-disable-next-line no-param-reassign
  if (typeof columns === 'string') columns = [columns]
  const allColumns = columns.includes('*')
  const singleColumn = !allColumns && columns.length === 1 ? columns[0] : false
  if (!allColumns) this.select(...columns)
  this.limit(2)
  return this.then((results: any[]) =>
    results.length === 1
      ? singleColumn
        ? results[0][singleColumn]
        : results[0]
      : results.length
      ? Promise.reject(notSingleMessage || `Query has more than one result: "${this.toSQL().sql}"`)
      : Promise.reject(notFoundMessage || `Query has no results: "${this.toSQL().sql}"`),
  )
} as any)

@wubzz would you be interested in a PR adding the single method to QueryInterface?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mishitpatel picture mishitpatel  ·  3Comments

rarkins picture rarkins  ·  3Comments

mattgrande picture mattgrande  ·  3Comments

nklhrstv picture nklhrstv  ·  3Comments

npow picture npow  ·  3Comments