How to use the knex/lib/formatter.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 hongymagic / k2 / src / db.js View on Github external
// Automatically convert "camelCase" identifiers to "snake_case". For example:
//   db.table('users').where('userId', '=', 1).update({ firstName: 'Bill' })
//   => UPDATE "users" SET "first_name" = ? WHERE "user_id" = ?
Client.prototype.wrapIdentifier = value => {
  if (value === '*') return value;
  const matched = value.match(/(.*?)(\[[0-9]\])/);
  if (matched)
    return (
      Client.prototype.wrapIdentifier.wrapIdentifier(matched[1]) + matched[2]
    );
  return `"${toSnakeCase(value).replace(/"/g, '""')}"`;
};

// The above should not apply to the "as " identifiers. For example:
// db.table('users').select('user_id as userId') => SELECT "user_id" as "userId" from "users"
Formatter.prototype.wrapAsIdentifier = value =>
  `"${(value || '').replace(/"/g, '""')}"`;

const config: Object = {
  acquireConnectionTimeout: 60000,
  debug: process.env.DATABASE_DEBUG === 'true',
};
const db = knex(
  Object.assign({}, knexConfig, config, {
    client: Client,
  })
);

export default db;
github adonisjs / adonis-lucid / src / Database / index.js View on Github external
/*
 * adonis-lucid
 *
 * (c) Harminder Virk 
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const knex = require('knex')
const _ = require('lodash')

const KnexFormatter = require('knex/lib/formatter')

KnexFormatter.prototype.compileCallback = function (callback, method) {
  /**
   * subQuery is set by Lucid model query builder, since that querybuilder
   * has more methods then a regular query builder.
   */
  const builder = typeof (this.builder.subQuery) === 'function'
    ? this.builder.subQuery()
    : this.client.queryBuilder()

  /**
   * All this code is a copy/paste from Knex
   */
  callback.call(builder, builder)
  const compiler = this.client.queryCompiler(builder)
  compiler.formatter = this

  return compiler.toSQL(method || builder._method || 'select')