Remove callbacks and getArgs from QueryBuilder

This commit is contained in:
Timothy Warren 2016-11-14 21:10:37 -05:00
parent 17dfebad4e
commit c90b1b1ba0
2 changed files with 48 additions and 83 deletions

View File

@ -1,6 +1,5 @@
'use strict'; 'use strict';
const getArgs = require('getargs');
const helpers = require('./helpers'); const helpers = require('./helpers');
const QueryBuilderBase = require('./QueryBuilderBase'); const QueryBuilderBase = require('./QueryBuilderBase');
@ -24,7 +23,8 @@ class QueryBuilder extends QueryBuilderBase {
* @return {Promise} - Promise with result of query * @return {Promise} - Promise with result of query
*/ */
query (sql, params) { query (sql, params) {
return this.adapter.execute(sql, params); return this.adapter.execute(sql, params)
.catch(e => console.error(e));
} }
/** /**
@ -50,15 +50,10 @@ class QueryBuilder extends QueryBuilderBase {
* Empties the selected database table * Empties the selected database table
* *
* @param {string} table - the name of the table to truncate * @param {string} table - the name of the table to truncate
* @param {function} [callback] - Optional callback
* @return {void|Promise} - Returns a promise if no callback is supplied * @return {void|Promise} - Returns a promise if no callback is supplied
*/ */
truncate (/* table:string, [callback]:function */) { truncate (table) {
getArgs('table:string, [callback]:function', arguments); return this.query(this.driver.truncate(table));
let args = [].slice.apply(arguments);
let sql = this.driver.truncate(args.shift());
args.unshift(sql);
return this.query.apply(this, args);
} }
/** /**
@ -90,7 +85,7 @@ class QueryBuilder extends QueryBuilderBase {
// Split on 'As' // Split on 'As'
fields.forEach((field, index) => { fields.forEach((field, index) => {
if (field.match(/as/i)) { if (/as/i.test(field)) {
fields[index] = field.split(/ as /i).map(helpers.stringTrim); fields[index] = field.split(/ as /i).map(helpers.stringTrim);
} }
}); });
@ -190,10 +185,8 @@ class QueryBuilder extends QueryBuilderBase {
* @param {String|Number} [val] - The value to compare if the value of key is a string * @param {String|Number} [val] - The value to compare if the value of key is a string
* @return {QueryBuilder} - The Query Builder object, for chaining * @return {QueryBuilder} - The Query Builder object, for chaining
*/ */
having (/* key, [val] */) { having (key, val = null) {
let args = getArgs('key:string|object, [val]:string|number', arguments); this._having(key, val, 'AND');
this._having(args.key, args.val, 'AND');
return this; return this;
} }
@ -204,10 +197,8 @@ class QueryBuilder extends QueryBuilderBase {
* @param {String|Number} [val] - The value to compare if the value of key is a string * @param {String|Number} [val] - The value to compare if the value of key is a string
* @return {QueryBuilder} - The Query Builder object, for chaining * @return {QueryBuilder} - The Query Builder object, for chaining
*/ */
orHaving (/* key, [val] */) { orHaving (key, val = null) {
let args = getArgs('key:string|object, [val]:string|number', arguments); this._having(key, val, 'OR');
this._having(args.key, args.val, 'OR');
return this; return this;
} }
@ -336,12 +327,10 @@ class QueryBuilder extends QueryBuilderBase {
* @example query.set({foo:'bar'}); // Set with an object * @example query.set({foo:'bar'}); // Set with an object
* @return {QueryBuilder} - The Query Builder object, for chaining * @return {QueryBuilder} - The Query Builder object, for chaining
*/ */
set (/* $key, [$val] */) { set (key, val) {
let args = getArgs('$key, [$val]', arguments);
// Set the appropriate state variables // Set the appropriate state variables
this._mixedSet('setArrayKeys', 'key', args.$key, args.$val); this._mixedSet('setArrayKeys', 'key', key, val);
this._mixedSet('values', 'value', args.$key, args.$val); this._mixedSet('values', 'value', key, val);
// Use the keys of the array to make the insert/update string // Use the keys of the array to make the insert/update string
// and escape the field names // and escape the field names
@ -499,26 +488,22 @@ class QueryBuilder extends QueryBuilderBase {
* @param {String} [table] - The table to select from * @param {String} [table] - The table to select from
* @param {Number} [limit] - A limit for the query * @param {Number} [limit] - A limit for the query
* @param {Number} [offset] - An offset for the query * @param {Number} [offset] - An offset for the query
* @param {Function} [callback] - A callback for receiving the result
* @example query.get('table_name').then(promiseCallback); // Get all the rows in the table * @example query.get('table_name').then(promiseCallback); // Get all the rows in the table
* @example query.get('table_name', 5, callback); // Get 5 rows from the table * @example query.get('table_name', 5); // Get 5 rows from the table
* @example query.get(callback); // Get the results of a query generated with other methods * @example query.get(); // Get the results of a query generated with other methods
* @return {void|Promise} - If no callback is passed, a promise is returned * @return {void|Promise} - If no callback is passed, a promise is returned
*/ */
get (/* [table], [limit], [offset], [callback] */) { get (table, limit, offset) {
const argPattern = '[table]:string, [limit]:number, [offset]:number, [callback]:function'; if (table) {
let args = getArgs(argPattern, arguments); this.from(table);
if (args.table) {
this.from(args.table);
} }
if (args.limit) { if (limit) {
this.limit(args.limit, args.offset); this.limit(limit, offset);
} }
// Run the query // Run the query
return this._run('get', args.table, args.callback); return this._run('get', table);
} }
/** /**
@ -526,18 +511,15 @@ class QueryBuilder extends QueryBuilderBase {
* *
* @param {String} table - The table to insert into * @param {String} table - The table to insert into
* @param {Object} [data] - Data to insert, if not already added with the 'set' method * @param {Object} [data] - Data to insert, if not already added with the 'set' method
* @param {Function} [callback] - Callback for handling response from the database * @return {Promise} - If no callback is passed, a promise is returned
* @return {void|Promise} - If no callback is passed, a promise is returned
*/ */
insert (/* table, data, callback */) { insert (table, data) {
let args = getArgs('table:string, [data]:object, [callback]:function', arguments); if (data) {
this.set(data);
if (args.data) {
this.set(args.data);
} }
// Run the query // Run the query
return this._run('insert', this.driver.quoteTable(args.table), args.callback); return this._run('insert', this.driver.quoteTable(table));
} }
/** /**
@ -545,18 +527,15 @@ class QueryBuilder extends QueryBuilderBase {
* *
* @param {String} table - The table to insert into * @param {String} table - The table to insert into
* @param {Array} data - The array of objects containing data rows to insert * @param {Array} data - The array of objects containing data rows to insert
* @param {Function} [callback] - Callback for handling database response
* @example query.insertBatch('foo',[{id:1,val:'bar'},{id:2,val:'baz'}], callbackFunction);
* @example query.insertBatch('foo',[{id:1,val:'bar'},{id:2,val:'baz'}]) * @example query.insertBatch('foo',[{id:1,val:'bar'},{id:2,val:'baz'}])
*.then(promiseCallback); *.then(promiseCallback);
* @return {void|Promise} - If no callback is passed, a promise is returned * @return {Promise} - If no callback is passed, a promise is returned
*/ */
insertBatch (/* table, data, callback */) { insertBatch (table, data) {
let args = getArgs('table:string, data:array, [callback]:function', arguments); let batch = this.driver.insertBatch(table, data);
let batch = this.driver.insertBatch(args.table, args.data);
// Run the query // Run the query
return this._run('', '', args.callback, batch.sql, batch.values); return this.query(batch.sql, batch.values);
} }
/** /**
@ -564,18 +543,16 @@ class QueryBuilder extends QueryBuilderBase {
* *
* @param {String} table - The table to insert into * @param {String} table - The table to insert into
* @param {Object} [data] - Data to insert, if not already added with the 'set' method * @param {Object} [data] - Data to insert, if not already added with the 'set' method
* @param {Function} [callback] - Callback for handling response from the database * @return {Promise} - If no callback is passed, a promise is returned
* @return {void|Promise} - If no callback is passed, a promise is returned
*/ */
update (/* table, data, callback */) { update (table, data) {
let args = getArgs('table:string, [data]:object, [callback]:function', arguments);
if (args.data) { if (data) {
this.set(args.data); this.set(data);
} }
// Run the query // Run the query
return this._run('update', this.driver.quoteTable(args.table), args.callback); return this._run('update', this.driver.quoteTable(table));
} }
/** /**
@ -583,18 +560,15 @@ class QueryBuilder extends QueryBuilderBase {
* *
* @param {String} table - The table to insert into * @param {String} table - The table to insert into
* @param {Object} [where] - Where clause for delete statement * @param {Object} [where] - Where clause for delete statement
* @param {Function} [callback] - Callback for handling response from the database * @return {Promise} - If no callback is passed, a promise is returned
* @return {void|Promise} - If no callback is passed, a promise is returned
*/ */
delete (/* table, [where], [callback] */) { delete (table, where) {
let args = getArgs('table:string, [where]:object, [callback]:function', arguments); if (where) {
this.where(where);
if (args.where) {
this.where(args.where);
} }
// Run the query // Run the query
return this._run('delete', this.driver.quoteTable(args.table), args.callback); return this._run('delete', this.driver.quoteTable(table));
} }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -608,13 +582,12 @@ class QueryBuilder extends QueryBuilderBase {
* @param {Boolean} [reset=true] - Whether to reset the query builder so another query can be built * @param {Boolean} [reset=true] - Whether to reset the query builder so another query can be built
* @return {String} - The compiled sql statement * @return {String} - The compiled sql statement
*/ */
getCompiledSelect (/* table, reset */) { getCompiledSelect (table, reset = true) {
let args = getArgs('[table]:string, [reset]:boolean', arguments); if (table) {
if (args.table) { this.from(table);
this.from(args.table);
} }
return this._getCompile('get', args.table, args.reset); return this._getCompile('get', table, reset);
} }
/** /**

View File

@ -207,13 +207,9 @@ class QueryBuilderBase {
this._appendMap(this._fixConjunction(conj), item, 'whereNull'); this._appendMap(this._fixConjunction(conj), item, 'whereNull');
} }
_having (/* key, val, conj */) { _having (key, val = null, conj = 'AND') {
let args = getArgs('key:string|object, [val]:string|number, [conj]:string', arguments);
args.conj = args.conj || 'AND';
args.val = args.val || null;
// Normalize key/val and put in state.whereMap // Normalize key/val and put in state.whereMap
this._whereMixedSet(args.key, args.val); this._whereMixedSet(key, val);
// Parse the having condition to account for operators, // Parse the having condition to account for operators,
// functions, identifiers, and literal values // functions, identifiers, and literal values
@ -222,7 +218,7 @@ class QueryBuilderBase {
this.state.whereMap.forEach(clause => { this.state.whereMap.forEach(clause => {
// Put in the having map // Put in the having map
this.state.havingMap.push({ this.state.havingMap.push({
conjunction: (this.state.havingMap.length > 0) ? ` ${args.conj} ` : ' HAVING ', conjunction: (this.state.havingMap.length > 0) ? ` ${conj} ` : ' HAVING ',
string: clause string: clause
}); });
}); });
@ -248,7 +244,7 @@ class QueryBuilderBase {
this._appendMap(args.conj, str, 'whereIn'); this._appendMap(args.conj, str, 'whereIn');
} }
_run (type, table, callback, sql, vals) { _run (type, table, sql, vals) {
if (!sql) { if (!sql) {
sql = this._compile(type, table); sql = this._compile(type, table);
} }
@ -261,12 +257,8 @@ class QueryBuilderBase {
this._resetState(); this._resetState();
// Pass the sql and values to the adapter to run on the database // Pass the sql and values to the adapter to run on the database
if (callback) {
return this.query(sql, vals, callback);
} else {
return this.query(sql, vals); return this.query(sql, vals);
} }
}
_getCompile (type, table, reset) { _getCompile (type, table, reset) {
reset = reset || false; reset = reset || false;