How to use the knex/lib/query/builder.prototype function in knex

To help you get started, we’ve selected a few knex examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github why2pac / dp-node / lib / model / engine.js View on Github external
/* eslint-disable prefer-rest-params */

const Promise = require('bluebird');
const knexQb = require('knex/lib/query/builder');
const knexRaw = require('knex/lib/raw');

// Override
const { getPrototypeOf } = Object;

// Override - select
const AS_RE = /\bas\s*[\s`'"]/i;
const symSelectGroups = Symbol('dp-node.selectGroups');
knexQb.prototype.select = Object.setPrototypeOf(function select() {
  if (arguments.length === 2 && typeof arguments[0] === 'object' && arguments[1]) {
    const p = `${arguments[1]}`;
    (this[symSelectGroups] || (this[symSelectGroups] = [])).push(p);
    const replacement = `$&${p.replace('$', '$$$$')}_`;
    arguments[0] = arguments[0].map((e) => e.replace(AS_RE, replacement));
  }

  return getPrototypeOf(select).apply(this, arguments);
}, knexQb.prototype.select);

const prepareParam = (data) => {
  if (data && typeof data === 'object') {
    const ignorable = (false
      || data instanceof knexRaw
      || data instanceof Date
      || data instanceof Buffer
github why2pac / dp-node / lib / model / engine.js View on Github external
value, writable: true, enumerable: true, configurable: true,
      });
    });
    return obj;
  }

  return data;
};

// Override - insert
knexQb.prototype.insert = Object.setPrototypeOf(function insert(_values, _returning) {
  if (arguments.length > 0) {
    arguments[0] = prepareParams(this.client.config, arguments[0]);
  }
  return getPrototypeOf(insert).apply(this, arguments);
}, knexQb.prototype.insert);

// Override - update
knexQb.prototype.update = Object.setPrototypeOf(function update(_values, _returning) {
  if (arguments.length > 0) {
    arguments[0] = prepareParams(this.client.config, arguments[0]);
  }
  return getPrototypeOf(update).apply(this, arguments);
}, knexQb.prototype.update);

const overridableKnexMethods = [
  'where',
  'orWhere',
  'andWhere',
  'whereIn',
  'orWhereIn',
  'whereNotIn',
github why2pac / dp-node / lib / model / engine.js View on Github external
return obj;
  }

  return data;
};

// Override - insert
knexQb.prototype.insert = Object.setPrototypeOf(function insert(_values, _returning) {
  if (arguments.length > 0) {
    arguments[0] = prepareParams(this.client.config, arguments[0]);
  }
  return getPrototypeOf(insert).apply(this, arguments);
}, knexQb.prototype.insert);

// Override - update
knexQb.prototype.update = Object.setPrototypeOf(function update(_values, _returning) {
  if (arguments.length > 0) {
    arguments[0] = prepareParams(this.client.config, arguments[0]);
  }
  return getPrototypeOf(update).apply(this, arguments);
}, knexQb.prototype.update);

const overridableKnexMethods = [
  'where',
  'orWhere',
  'andWhere',
  'whereIn',
  'orWhereIn',
  'whereNotIn',
  'orWhereNotIn',
];
github why2pac / dp-node / lib / model / engine.js View on Github external
// Override
const { getPrototypeOf } = Object;

// Override - select
const AS_RE = /\bas\s*[\s`'"]/i;
const symSelectGroups = Symbol('dp-node.selectGroups');
knexQb.prototype.select = Object.setPrototypeOf(function select() {
  if (arguments.length === 2 && typeof arguments[0] === 'object' && arguments[1]) {
    const p = `${arguments[1]}`;
    (this[symSelectGroups] || (this[symSelectGroups] = [])).push(p);
    const replacement = `$&${p.replace('$', '$$$$')}_`;
    arguments[0] = arguments[0].map((e) => e.replace(AS_RE, replacement));
  }

  return getPrototypeOf(select).apply(this, arguments);
}, knexQb.prototype.select);

const prepareParam = (data) => {
  if (data && typeof data === 'object') {
    const ignorable = (false
      || data instanceof knexRaw
      || data instanceof Date
      || data instanceof Buffer
    );

    if (!ignorable) {
      return String(data);
    }
  }

  return data;
};
github adonisjs / adonis-lucid / src / Database / MonkeyPatch.js View on Github external
}

/**
 * Add `offset` and `limit` based upon the current
 * and per page params.
 *
 * @method forPage
 *
 * @for Database
 *
 * @param  {Number} [page = 1]
 * @param  {Number} [perPage = 20]
 *
 * @chainable
 */
KnexQueryBuilder.prototype.forPage = function (page = 1, perPage = 20) {
  const offset = page === 1 ? 0 : perPage * (page - 1)
  return this.offset(offset).limit(perPage)
}

/**
 * Paginate results from database. This method is same as
 * @ref('Database.forPage') but instead returns pagination
 * meta data as well.
 *
 * @method paginate
 *
 * @for Database
 *
 * @param  {Number} page
 * @param  {Number} perPage
 *
github adonisjs / adonis-lucid / src / Database / MonkeyPatch.js View on Github external
* @method table
 *
 * @for Database
 */
KnexQueryBuilder.prototype.table = function (...args) {
  return this.from(...args)
}

/**
 * Alias for @ref('Database.from')
 *
 * @method table
 *
 * @for Database
 */
KnexQueryBuilder.prototype.into = function (...args) {
  return this.from(...args)
}

/**
 * Instruct query builder to ignore prefix when
 * selecting table
 *
 * @method withOutPrefix
 *
 * @for Database
 *
 * @chainable
 */
KnexQueryBuilder.prototype.withOutPrefix = function () {
  this._ignorePrefix = true
  return this
github bravi-software / knextancy / src / knex-tenant-support.js View on Github external
export function install () {
  Object.defineProperty(knex.Client.prototype, 'tenantId', {
    get: function() {
      return this.config.tenantId;
    },
  });

  override(QueryBuilder.prototype, 'toSQL', after(function(sql) {
    debug('knex.Client.prototype.QueryBuilder.prototype.toSQL', arguments);
    sql.sql = applyTenant(sql.sql, this.client.tenantId);
    return sql;
  }));

  override(Raw.prototype, 'set', before(function(sql, bindings) {
    debug('knex.Client.prototype.Raw.prototype.set', arguments);
    const tenantSQL = applyTenant(sql, this.client.tenantId);
    return [tenantSQL, bindings];
  }));

  override(SchemaBuilder.prototype, 'toSQL', after(function(sql) {
    debug('knex.Client.prototype.SchemaBuilder.prototype.toSQL', arguments);
    return sql.map(q => {
      q.sql = applyTenant(q.sql, this.client.tenantId);
      return q;
github adonisjs / adonis-lucid / src / Database / MonkeyPatch.js View on Github external
/**
 * Paginate results from database. This method is same as
 * @ref('Database.forPage') but instead returns pagination
 * meta data as well.
 *
 * @method paginate
 *
 * @for Database
 *
 * @param  {Number} page
 * @param  {Number} perPage
 *
 * @return {Object} @multiple([data=Array, page=Number, perPage=Number, total=Number, lastPage=Number])
 */
KnexQueryBuilder.prototype.paginate = async function (page = 1, perPage = 20) {
  const countByQuery = this.clone()

  /**
   * Copy the subQuery fn to the clone query. This will make sure
   * that build uses the extended query builder methods on the
   * cloned query too
   */
  countByQuery.subQuery = this.subQuery

  /**
   * Force cast page and perPage to numbers
   */
  page = Number(page)
  perPage = Number(perPage)

  /**
github adonisjs / adonis-lucid / src / Database / MonkeyPatch.js View on Github external
* @return {Number} The average of distinct values of columnName
 */
generateAggregate('avgDistinct')

/**
 * Returns the latest row from the database.
 *
 * @method last
 *
 * @for Database
 *
 * @param  {string} [field = 'id']
 *
 * @chainable
 */
KnexQueryBuilder.prototype.last = async function (field = 'id') {
  return this.orderBy(field, 'desc').first()
}
github adonisjs / adonis-lucid / src / Database / MonkeyPatch.js View on Github external
* For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

/**
 * Here we monkey patch/extend knex query builder
 * prototype.
 */

const _ = require('lodash')
const KnexQueryBuilder = require('knex/lib/query/builder')
const excludeAttrFromCount = ['order', 'columns', 'limit', 'offset']
const util = require('../../lib/util')

const _from = KnexQueryBuilder.prototype.from
const _returning = KnexQueryBuilder.prototype.returning

/**
 * Override knex actual returning method and call the actual
 * `returning` when client supports `returning`
 *
 * @method returning
 *
 * @param  {...Spread} args
 *
 * @chainable
 */
KnexQueryBuilder.prototype.returning = function (...args) {
  if (util.supportsReturning(this.client.config.client)) {
    return _returning.bind(this)(...args)
  }
  return this