More style fixes

This commit is contained in:
Timothy Warren 2015-12-07 17:03:36 -05:00
parent e1a9aa48ec
commit 577700ed10
23 changed files with 368 additions and 376 deletions

View File

@ -4,6 +4,7 @@ const documentation = require('gulp-documentation'),
eslint = require('gulp-eslint'), eslint = require('gulp-eslint'),
gulp = require('gulp'), gulp = require('gulp'),
istanbul = require('gulp-istanbul'), istanbul = require('gulp-istanbul'),
jscs = require('gulp-jscs'),
mocha = require('gulp-mocha'), mocha = require('gulp-mocha'),
pipe = require('gulp-pipe'), pipe = require('gulp-pipe'),
sloc = require('gulp-sloc'); sloc = require('gulp-sloc');
@ -54,19 +55,27 @@ const ESLINT_SETTINGS = {
}; };
gulp.task('lint', () => { gulp.task('lint', () => {
return pipe(gulp.src(SRC_FILES), [ pipe(gulp.src(SRC_FILES), [
eslint(ESLINT_SETTINGS), eslint(ESLINT_SETTINGS),
eslint.format(), eslint.format(),
eslint.failAfterError() eslint.failAfterError()
]); ]);
pipe(gulp.src(SRC_FILES), [
jscs(),
jscs.reporter()
]);
}); });
gulp.task('lint-tests', ['lint'], () => { gulp.task('lint-tests', ['lint'], () => {
return pipe(gulp.src(['test/**/*.js']), [ pipe(gulp.src(['test/**/*.js']), [
eslint(ESLINT_SETTINGS), eslint(ESLINT_SETTINGS),
eslint.format(), eslint.format(),
eslint.failAfterError() eslint.failAfterError()
]); ]);
pipe(gulp.src(['test/**/*.js']), [
jscs(),
jscs.reporter()
]);
}); });
gulp.task('sloc', () => gulp.src(SRC_FILES).pipe(sloc())); gulp.task('sloc', () => gulp.src(SRC_FILES).pipe(sloc()));
@ -86,9 +95,8 @@ gulp.task('mocha', ['lint-tests', 'sloc'], () => {
.pipe(mocha({ .pipe(mocha({
ui: 'tdd', ui: 'tdd',
bail: true, bail: true,
reporter: 'list' reporter: 'list',
//reporter: 'dot', timeout: 5000
//reporter: 'landing',
})) }))
.once('error', () => { .once('error', () => {
process.exit(1); process.exit(1);

View File

@ -38,21 +38,17 @@ module.exports = class QueryBuilder {
['queryMap', 'groupString', 'orderString', 'havingMap'].forEach(clause => { ['queryMap', 'groupString', 'orderString', 'havingMap'].forEach(clause => {
let param = this.state[clause]; let param = this.state[clause];
if ( ! helpers.isScalar(param)) if (! helpers.isScalar(param)) {
{
Object.keys(param).forEach(part => { Object.keys(param).forEach(part => {
sql += param[part].conjunction + param[part].string; sql += param[part].conjunction + param[part].string;
}); });
} } else {
else
{
sql += param; sql += param;
} }
}); });
// Append the limit, if it exists // Append the limit, if it exists
if (helpers.isNumber(this.state.limit)) if (helpers.isNumber(this.state.limit)) {
{
sql = this.driver.limit(sql, this.state.limit, this.state.offset); sql = this.driver.limit(sql, this.state.limit, this.state.offset);
} }
@ -62,8 +58,8 @@ module.exports = class QueryBuilder {
_compileType(type, table) { _compileType(type, table) {
let sql = ''; let sql = '';
switch(type) { switch (type) {
case "insert": case 'insert':
let params = Array(this.state.setArrayKeys.length).fill('?'); let params = Array(this.state.setArrayKeys.length).fill('?');
sql = `INSERT INTO ${table} (`; sql = `INSERT INTO ${table} (`;
@ -71,11 +67,11 @@ module.exports = class QueryBuilder {
sql += `) VALUES (${params.join(',')})`; sql += `) VALUES (${params.join(',')})`;
break; break;
case "update": case 'update':
sql = `UPDATE ${table} SET ${this.state.setString}`; sql = `UPDATE ${table} SET ${this.state.setString}`;
break; break;
case "delete": case 'delete':
sql = `DELETE FROM ${table}`; sql = `DELETE FROM ${table}`;
break; break;
@ -83,11 +79,11 @@ module.exports = class QueryBuilder {
sql = `SELECT * FROM ${this.state.fromString}`; sql = `SELECT * FROM ${this.state.fromString}`;
// Set the select string // Set the select string
if (this.state.selectString.length > 0) if (this.state.selectString.length > 0) {
{
// Replace the star with the selected fields // Replace the star with the selected fields
sql = sql.replace('*', this.state.selectString); sql = sql.replace('*', this.state.selectString);
} }
break; break;
} }
@ -99,16 +95,11 @@ module.exports = class QueryBuilder {
like = `${field} ${like} ?`; like = `${field} ${like} ?`;
if (pos == 'before') if (pos == 'before') {
{
val = `%${val}`; val = `%${val}`;
} } else if (pos == 'after') {
else if (pos == 'after')
{
val = `${val}%`; val = `${val}%`;
} } else {
else
{
val = `%${val}%`; val = `%${val}%`;
} }
@ -131,7 +122,7 @@ module.exports = class QueryBuilder {
this.state.queryMap.push({ this.state.queryMap.push({
type: type, type: type,
conjunction: conjunction, conjunction: conjunction,
string: string string: string,
}); });
} }
@ -147,36 +138,26 @@ module.exports = class QueryBuilder {
let obj = {}; let obj = {};
if (helpers.isScalar(args.$key) && !helpers.isUndefined(args.$val)) {
if (helpers.isScalar(args.$key) && !helpers.isUndefined(args.$val))
{
// Convert key/val pair to a simple object // Convert key/val pair to a simple object
obj[args.$key] = args.$val; obj[args.$key] = args.$val;
} } else if (helpers.isScalar(args.$key) && helpers.isUndefined(args.$val)) {
else if (helpers.isScalar(args.$key) && helpers.isUndefined(args.$val))
{
// If just a string for the key, and no value, create a simple object with duplicate key/val // If just a string for the key, and no value, create a simple object with duplicate key/val
obj[args.$key] = args.$key; obj[args.$key] = args.$key;
} } else {
else
{
obj = args.$key; obj = args.$key;
} }
Object.keys(obj).forEach(k => { Object.keys(obj).forEach(k => {
// If a single value for the return // If a single value for the return
if (['key','value'].indexOf(args.$valType) !== -1) if (['key', 'value'].indexOf(args.$valType) !== -1) {
{
let pushVal = (args.$valType === 'key') ? k : obj[k]; let pushVal = (args.$valType === 'key') ? k : obj[k];
this.state[args.$letName].push(pushVal); this.state[args.$letName].push(pushVal);
} } else {
else
{
this.state[args.$letName][k] = obj[k]; this.state[args.$letName][k] = obj[k];
} }
}); });
return this.state[args.$letName]; return this.state[args.$letName];
} }
@ -194,16 +175,11 @@ module.exports = class QueryBuilder {
let lastItem = this.state.queryMap[this.state.queryMap.length - 1]; let lastItem = this.state.queryMap[this.state.queryMap.length - 1];
let conjunctionList = helpers.arrayPluck(this.state.queryMap, 'conjunction'); let conjunctionList = helpers.arrayPluck(this.state.queryMap, 'conjunction');
if (this.state.queryMap.length === 0 || ( ! helpers.regexInArray(conjunctionList, /^ ?WHERE/i))) if (this.state.queryMap.length === 0 || (! helpers.regexInArray(conjunctionList, /^ ?WHERE/i))) {
{ conj = ' WHERE ';
conj = " WHERE "; } else if (lastItem.type === 'groupStart') {
}
else if (lastItem.type === 'groupStart')
{
conj = ''; conj = '';
} } else {
else
{
conj = ` ${conj} `; conj = ` ${conj} `;
} }
@ -249,13 +225,15 @@ module.exports = class QueryBuilder {
// 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) ? ` ${args.conj} ` : ' HAVING ',
string: clause string: clause,
}); });
}); });
// Clear the where Map // Clear the where Map
this.state.whereMap = {}; this.state.whereMap = {};
} }
_whereIn(/*key, val, inClause, conj*/) { _whereIn(/*key, val, inClause, conj*/) {
let args = getArgs('key:string, val:array, inClause:string, conj:string', arguments); let args = getArgs('key:string, val:array, inClause:string, conj:string', arguments);
@ -275,13 +253,11 @@ module.exports = class QueryBuilder {
_run(type, table, callback, sql, vals) { _run(type, table, callback, sql, vals) {
if ( ! sql) if (! sql) {
{
sql = this._compile(type, table); sql = this._compile(type, table);
} }
if ( ! vals) if (! vals) {
{
vals = this.state.values.concat(this.state.whereValues); vals = this.state.values.concat(this.state.whereValues);
} }
@ -304,7 +280,9 @@ module.exports = class QueryBuilder {
let sql = this._compile(type, table); let sql = this._compile(type, table);
if (reset) this._resetState(); if (reset) {
this._resetState();
}
return sql; return sql;
} }
@ -362,12 +340,11 @@ module.exports = class QueryBuilder {
// Split/trim fields by comma // Split/trim fields by comma
fields = (Array.isArray(fields)) fields = (Array.isArray(fields))
? fields ? fields
: fields.split(",").map(helpers.stringTrim); : fields.split(',').map(helpers.stringTrim);
// Split on 'As' // Split on 'As'
fields.forEach((field, index) => { fields.forEach((field, index) => {
if (field.match(/as/i)) if (field.match(/as/i)) {
{
fields[index] = field.split(/ as /i).map(helpers.stringTrim); fields[index] = field.split(/ as /i).map(helpers.stringTrim);
} }
}); });
@ -376,8 +353,7 @@ module.exports = class QueryBuilder {
// Join the strings back together // Join the strings back together
safeArray.forEach((field, index) => { safeArray.forEach((field, index) => {
if (Array.isArray(field)) if (Array.isArray(field)) {
{
safeArray[index] = safeArray[index].join(' AS '); safeArray[index] = safeArray[index].join(' AS ');
} }
}); });
@ -637,7 +613,7 @@ module.exports = class QueryBuilder {
* @return {QueryBuilder} - The Query Builder object, for chaining * @return {QueryBuilder} - The Query Builder object, for chaining
*/ */
join(table, cond, type) { join(table, cond, type) {
type = type || "inner"; type = type || 'inner';
// Prefix/quote table name // Prefix/quote table name
table = table.split(' ').map(helpers.stringTrim); table = table.split(' ').map(helpers.stringTrim);
@ -662,13 +638,10 @@ module.exports = class QueryBuilder {
* @return {QueryBuilder} - The Query Builder object, for chaining * @return {QueryBuilder} - The Query Builder object, for chaining
*/ */
groupBy(field) { groupBy(field) {
if ( ! helpers.isScalar(field)) if (! helpers.isScalar(field)) {
{
let newGroupArray = field.map(this.driver.quoteIdentifiers); let newGroupArray = field.map(this.driver.quoteIdentifiers);
this.state.groupArray = this.state.groupArray.concat(newGroupArray); this.state.groupArray = this.state.groupArray.concat(newGroupArray);
} } else {
else
{
this.state.groupArray.push(this.driver.quoteIdentifiers(field)); this.state.groupArray.push(this.driver.quoteIdentifiers(field));
} }
@ -860,8 +833,7 @@ module.exports = class QueryBuilder {
delete(/*table, [where], callback*/) { delete(/*table, [where], callback*/) {
let args = getArgs('table:string, [where]:object, callback:function', arguments); let args = getArgs('table:string, [where]:object, callback:function', arguments);
if (args.where) if (args.where) {
{
this.where(args.where); this.where(args.where);
} }
@ -882,8 +854,7 @@ module.exports = class QueryBuilder {
*/ */
getCompiledSelect(/*table, reset*/) { getCompiledSelect(/*table, reset*/) {
let args = getArgs('[table]:string, [reset]:boolean', arguments); let args = getArgs('[table]:string, [reset]:boolean', arguments);
if (args.table) if (args.table) {
{
this.from(args.table); this.from(args.table);
} }
@ -922,4 +893,4 @@ module.exports = class QueryBuilder {
getCompiledDelete(table, reset) { getCompiledDelete(table, reset) {
return this._getCompile('delete', this.driver.quoteTable(table), reset); return this._getCompile('delete', this.driver.quoteTable(table), reset);
} }
} };

View File

@ -15,9 +15,9 @@ module.exports = class QueryParser {
this.driver = driver; this.driver = driver;
let matchPatterns = { let matchPatterns = {
'function': /([a-z0-9_]+\((.*)\))/i, function: /([a-z0-9_]+\((.*)\))/i,
operator: /\!=?|\=|\+|&&?|~|\|\|?|\^|\/|<>|>=?|<=?|\-|%|OR|AND|NOT|XOR/ig, operator: /\!=?|\=|\+|&&?|~|\|\|?|\^|\/|<>|>=?|<=?|\-|%|OR|AND|NOT|XOR/ig,
literal: /([0-9]+)|'(.*?)'|true|false/ig literal: /([0-9]+)|'(.*?)'|true|false/ig,
}; };
// Full pattern for identifiers // Full pattern for identifiers
@ -29,19 +29,17 @@ module.exports = class QueryParser {
+ matchPatterns.literal.source + matchPatterns.literal.source
+ ')' + ')'
+ '([a-z_\-]+[0-9]*\\.?)' + '([a-z_\-]+[0-9]*\\.?)'
+ ')+' + ')+', 'ig');
, 'ig');
// Full pattern for determining ordering of the pieces // Full pattern for determining ordering of the pieces
matchPatterns.joinCombined = new RegExp( matchPatterns.joinCombined = new RegExp(
matchPatterns['function'].source + "+|" matchPatterns['function'].source + '+|'
+ matchPatterns.literal.source + '+|' + matchPatterns.literal.source + '+|'
+ matchPatterns.identifier.source + matchPatterns.identifier.source
+ '|(' + matchPatterns.operator.source + ')+' + '|(' + matchPatterns.operator.source + ')+', 'ig');
, 'ig');
this.matchPatterns = matchPatterns; this.matchPatterns = matchPatterns;
this.identifierBlacklist = ['true','false','null']; this.identifierBlacklist = ['true', 'false', 'null'];
} }
/** /**
@ -86,7 +84,7 @@ module.exports = class QueryParser {
functions: [], functions: [],
identifiers: [], identifiers: [],
operators: [], operators: [],
literals: [] literals: [],
}; };
// Get clause components // Get clause components
@ -117,8 +115,7 @@ module.exports = class QueryParser {
// Quote the identifiers // Quote the identifiers
parts.combined.forEach((part, i) => { parts.combined.forEach((part, i) => {
if (parts.identifiers.indexOf(part) !== -1 && ! helpers.isNumber(part)) if (parts.identifiers.indexOf(part) !== -1 && ! helpers.isNumber(part)) {
{
parts.combined[i] = this.driver.quoteIdentifiers(part); parts.combined[i] = this.driver.quoteIdentifiers(part);
} }
}); });
@ -146,25 +143,19 @@ module.exports = class QueryParser {
let fullClause = ''; let fullClause = '';
// Add an explicit = sign where one is inferred // Add an explicit = sign where one is inferred
if ( ! this.hasOperator(key)) if (! this.hasOperator(key)) {
{ fullClause = `${key} = ${whereMap[key]}`;
fullClause = key + ' = ' + whereMap[key]; } else if (whereMap[key] === key) {
}
else if (whereMap[key] === key)
{
fullClause = key; fullClause = key;
} } else {
else fullClause = `${key} ${whereMap[key]}`;
{
fullClause = key + ' ' + whereMap[key];
} }
// Separate the clause into separate pieces // Separate the clause into separate pieces
let parts = this.parseJoin(fullClause); let parts = this.parseJoin(fullClause);
// Filter explicit literals from lists of matches // Filter explicit literals from lists of matches
if (whereValues.indexOf(whereMap[key]) !== -1) if (whereValues.indexOf(whereMap[key]) !== -1) {
{
let value = whereMap[key]; let value = whereMap[key];
let identIndex = (helpers.isArray(parts.identifiers)) ? parts.identifiers.indexOf(value) : -1; let identIndex = (helpers.isArray(parts.identifiers)) ? parts.identifiers.indexOf(value) : -1;
let litIndex = (helpers.isArray(parts.literals)) ? parts.literals.indexOf(value) : -1; let litIndex = (helpers.isArray(parts.literals)) ? parts.literals.indexOf(value) : -1;
@ -174,12 +165,10 @@ module.exports = class QueryParser {
// Remove the identifier in question, // Remove the identifier in question,
// and add to the output values array // and add to the output values array
if (identIndex !== -1) if (identIndex !== -1) {
{
parts.identifiers.splice(identIndex, 1); parts.identifiers.splice(identIndex, 1);
if ( ! inOutputArray) if (! inOutputArray) {
{
outputValues.push(value); outputValues.push(value);
inOutputArray = true; inOutputArray = true;
} }
@ -187,12 +176,10 @@ module.exports = class QueryParser {
// Remove the value from the literals list // Remove the value from the literals list
// so it is not added twice // so it is not added twice
if (litIndex !== -1) if (litIndex !== -1) {
{
parts.literals.splice(litIndex, 1); parts.literals.splice(litIndex, 1);
if ( ! inOutputArray) if (! inOutputArray) {
{
outputValues.push(value); outputValues.push(value);
inOutputArray = true; inOutputArray = true;
} }
@ -200,13 +187,11 @@ module.exports = class QueryParser {
// Remove the value from the combined list // Remove the value from the combined list
// and replace it with a placeholder // and replace it with a placeholder
if (combIndex !== -1 && funcIndex === -1) if (combIndex !== -1 && funcIndex === -1) {
{
// Make sure to skip functions when replacing values // Make sure to skip functions when replacing values
parts.combined[combIndex] = '?'; parts.combined[combIndex] = '?';
if ( ! inOutputArray) if (! inOutputArray) {
{
outputValues.push(value); outputValues.push(value);
inOutputArray = true; inOutputArray = true;
} }
@ -223,12 +208,10 @@ module.exports = class QueryParser {
}, this); }, this);
// Quote identifiers // Quote identifiers
if (helpers.isArray(parts.identifiers)) if (helpers.isArray(parts.identifiers)) {
{
parts.identifiers.forEach(ident => { parts.identifiers.forEach(ident => {
let index = parts.combined.indexOf(ident); let index = parts.combined.indexOf(ident);
if (index !== -1) if (index !== -1) {
{
parts.combined[index] = driver.quoteIdentifiers(ident); parts.combined[index] = driver.quoteIdentifiers(ident);
} }
}); });
@ -239,13 +222,11 @@ module.exports = class QueryParser {
// This should only apply to literal values that are not // This should only apply to literal values that are not
// explicitly mapped to values, but have to be parsed from // explicitly mapped to values, but have to be parsed from
// a where condition, // a where condition,
if (helpers.isArray(parts.literals)) if (helpers.isArray(parts.literals)) {
{
parts.literals.forEach(lit => { parts.literals.forEach(lit => {
let litIndex = parts.combined.indexOf(lit); let litIndex = parts.combined.indexOf(lit);
if (litIndex !== -1) if (litIndex !== -1) {
{
parts.combined[litIndex] = (helpers.isArray(parts.operators)) ? '?' : '= ?'; parts.combined[litIndex] = (helpers.isArray(parts.operators)) ? '?' : '= ?';
outputValues.push(lit); outputValues.push(lit);
} }
@ -261,4 +242,4 @@ module.exports = class QueryParser {
return state; return state;
} }
} };

View File

@ -16,4 +16,4 @@ module.exports = class dblite extends Adapter {
let args = getArgs('sql:string, [params]:array, callback:function', arguments); let args = getArgs('sql:string, [params]:array, callback:function', arguments);
this.instance.query(args.sql, args.params, args.callback); this.instance.query(args.sql, args.params, args.callback);
} }
} };

View File

@ -16,4 +16,4 @@ module.exports = class mysql extends Adapter {
let args = getArgs('sql:string, [params], callback:function', arguments); let args = getArgs('sql:string, [params], callback:function', arguments);
return this.instance.query(args.sql, args.params, args.callback); return this.instance.query(args.sql, args.params, args.callback);
} }
} };

View File

@ -15,6 +15,5 @@ module.exports = class mysql2 extends Adapter {
execute(/*sql, params, callback*/) { execute(/*sql, params, callback*/) {
let args = getArgs('sql:string, [params], callback:function', arguments); let args = getArgs('sql:string, [params], callback:function', arguments);
return this.instance.execute(args.sql, args.params, args.callback); return this.instance.execute(args.sql, args.params, args.callback);
//this.instance.execute.apply(this.instance, args);
} }
} };

View File

@ -16,4 +16,4 @@ module.exports = class nodefirebird extends Adapter {
let args = getArgs('sql:string, [params], callback:function', arguments); let args = getArgs('sql:string, [params], callback:function', arguments);
return this.instance.execute(args.sql, args.params, args.callback); return this.instance.execute(args.sql, args.params, args.callback);
} }
} };

View File

@ -24,4 +24,4 @@ module.exports = class pg extends Adapter {
this.instance.query(args.sql, args.params, args.callback); this.instance.query(args.sql, args.params, args.callback);
} }
} };

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
let helpers = require('../helpers'); let helpers = require('../helpers');
@ -41,7 +41,7 @@ module.exports = (function() {
* @throws {Error} * @throws {Error}
*/ */
driver.insertBatch = function(table, data) { driver.insertBatch = function(table, data) {
throw new Error("Not Implemented"); throw new Error('Not Implemented');
}; };
return driver; return driver;

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
/** /**
* Driver for MySQL databases * Driver for MySQL databases
@ -22,8 +22,7 @@ module.exports = (function() {
* @return {String} - Modified SQL statement * @return {String} - Modified SQL statement
*/ */
driver.limit = function(sql, limit, offset) { driver.limit = function(sql, limit, offset) {
if ( ! helpers.isNumber(offset)) if (! helpers.isNumber(offset)) {
{
return sql += ` LIMIT ${limit}`; return sql += ` LIMIT ${limit}`;
} }

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
/** /**
* Driver for PostgreSQL databases * Driver for PostgreSQL databases

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
/** /**
* Driver for Sqlite databases * Driver for Sqlite databases
@ -25,16 +25,15 @@ module.exports = (function() {
// Get the data values to insert, so they can // Get the data values to insert, so they can
// be parameterized // be parameterized
let sql = "", let sql = '',
vals = [], vals = [],
cols = [], cols = [],
fields = [], fields = [],
first = data.shift(), first = data.shift(),
params = [], params = [],
paramString = "", paramString = '',
paramList = []; paramList = [];
data.forEach(obj => { data.forEach(obj => {
let row = []; let row = [];
Object.keys(obj).forEach(key => { Object.keys(obj).forEach(key => {
@ -54,18 +53,18 @@ module.exports = (function() {
sql += `SELECT ${cols.join(', ')}\n`; sql += `SELECT ${cols.join(', ')}\n`;
vals.forEach(row_values => { vals.forEach(rowValues => {
let quoted = row_values.map(value => { let quoted = rowValues.map(value => {
return String(value).replace("'", "'\'"); return String(value).replace('\'', '\'\'');
}); });
sql += `UNION ALL SELECT '${quoted.join("', '")}'\n`; sql += `UNION ALL SELECT '${quoted.join('\', \'')}'\n`;
}); });
return { return {
sql: sql, sql: sql,
values: null values: null,
}; };
} };
return driver; return driver;
}()); }());

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
let helpers = { let helpers = {
/** /**
@ -17,19 +17,20 @@ let helpers = {
* @return {String} - Type of the object * @return {String} - Type of the object
*/ */
type: o => { type: o => {
let type = Object.prototype.toString.call(o).slice(8, -1).toLowerCase(); let type = Object.prototype.toString.call(o).slice(8, -1).toLowerCase();
// handle NaN and Infinity // handle NaN and Infinity
if (type === 'number') { if (type === 'number') {
if (isNaN(o)) { if (isNaN(o)) {
return 'nan'; return 'nan';
} }
if (!isFinite(o)) {
return 'infinity';
}
}
return type; if (!isFinite(o)) {
return 'infinity';
}
}
return type;
}, },
/** /**
* Determine whether an object is scalar * Determine whether an object is scalar
@ -55,8 +56,7 @@ let helpers = {
if (arr.length === 0) return output; if (arr.length === 0) return output;
arr.forEach(obj => { arr.forEach(obj => {
if ( ! helpers.isUndefined(obj[key])) if (! helpers.isUndefined(obj[key])) {
{
output.push(obj[key]); output.push(obj[key]);
} }
}); });
@ -73,15 +73,17 @@ let helpers = {
*/ */
regexInArray: (arr, pattern) => { regexInArray: (arr, pattern) => {
// Empty case(s) // Empty case(s)
if ( ! helpers.isArray(arr)) return false; if (! helpers.isArray(arr) || arr.length === 0) {
if (arr.length === 0) return false; return false;
}
let i, l = arr.length; let i, l = arr.length;
for(i=0; i< l; i++) for (i = 0; i < l; i++) {
{
// Short circuit if any items match // Short circuit if any items match
if (pattern.test(arr[i])) return true; if (pattern.test(arr[i])) {
return true;
}
} }
return false; return false;
@ -96,11 +98,23 @@ let helpers = {
str += ''; str += '';
let first = str.charAt(0).toUpperCase(); let first = str.charAt(0).toUpperCase();
return first + str.substr(1); return first + str.substr(1);
} },
}; };
// Define an 'is' method for each type // Define an 'is' method for each type
let types = ['Null','Undefined','Object','Array','String','Number','Boolean','Function','RegExp','NaN','Infinite']; let types = [
'Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp',
'NaN',
'Infinite',
];
types.forEach(t => { types.forEach(t => {
/** /**
* Determine whether a variable is of the type specified in the * Determine whether a variable is of the type specified in the
@ -112,11 +126,10 @@ types.forEach(t => {
* @param {mixed} o * @param {mixed} o
* @return {Boolean} * @return {Boolean}
*/ */
helpers[`is${t}`] = function (o) { helpers[`is${t}`] = function(o) {
if (t.toLowerCase() === 'infinite') if (t.toLowerCase() === 'infinite') {
{ t = 'infinity';
t = 'infinity'; }
}
return helpers.type(o) === t.toLowerCase(); return helpers.type(o) === t.toLowerCase();
}; };

View File

@ -54,6 +54,7 @@
"gulp-documentation": "^2.1.0", "gulp-documentation": "^2.1.0",
"gulp-eslint": "", "gulp-eslint": "",
"gulp-istanbul": "^0.10.3", "gulp-istanbul": "^0.10.3",
"gulp-jscs": "^3.0.2",
"gulp-mocha": "^2.2.0", "gulp-mocha": "^2.2.0",
"gulp-pipe": "^1.0.4", "gulp-pipe": "^1.0.4",
"gulp-sloc": "", "gulp-sloc": "",

7
test/.jscsrc Normal file
View File

@ -0,0 +1,7 @@
{
"preset": "airbnb",
"validateIndentation": null,
"requireLineFeedAtFileEnd": null,
"disallowSpaceAfterPrefixUnaryOperators": null,
"disallowMultipleVarDecl": null
}

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
module.exports.tests = { module.exports.tests = {
'Get tests': { 'Get tests': {
@ -6,20 +6,20 @@ module.exports.tests = {
select: ['id, COUNT(id) as count'], select: ['id, COUNT(id) as count'],
from: ['create_test'], from: ['create_test'],
groupBy: ['id'], groupBy: ['id'],
get : [] get: [],
}, },
'Basic select all get': { 'Basic select all get': {
get: ['create_test'] get: ['create_test'],
}, },
'Basic select all with from': { 'Basic select all with from': {
from: ['create_test'], from: ['create_test'],
get: [] get: [],
}, },
'Get with limit': { 'Get with limit': {
get: ['create_test', 2] get: ['create_test', 2],
}, },
'Get with limit and offset': { 'Get with limit and offset': {
get: ['create_test', 2, 1] get: ['create_test', 2, 1],
}, },
'Get with having': { 'Get with having': {
select: ['id'], select: ['id'],
@ -31,7 +31,7 @@ module.exports.tests = {
['id !=', 3], ['id !=', 3],
['id', 900], ['id', 900],
], ],
get: [] get: [],
}, },
'Get with orHaving': { 'Get with orHaving': {
select: ['id'], select: ['id'],
@ -39,8 +39,8 @@ module.exports.tests = {
groupBy: ['id'], groupBy: ['id'],
having: [{'id >': 1}], having: [{'id >': 1}],
orHaving: ['id !=', 3], orHaving: ['id !=', 3],
get: [] get: [],
} },
}, },
'Select tests': { 'Select tests': {
'Select where get': { 'Select where get': {
@ -48,100 +48,100 @@ module.exports.tests = {
where: [ where: [
'multiple', 'multiple',
['id >', 1], ['id >', 1],
['id <', 900] ['id <', 900],
], ],
get: ['create_test', 2, 1] get: ['create_test', 2, 1],
}, },
'Select where get 2': { 'Select where get 2': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
where: ['id !=', 1], where: ['id !=', 1],
get: ['create_test', 2, 1] get: ['create_test', 2, 1],
}, },
'Multi Order By': { 'Multi Order By': {
from: ['create_test'], from: ['create_test'],
orderBy: ['id, key'], orderBy: ['id, key'],
get: [] get: [],
}, },
'Select get': { 'Select get': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
get: ['create_test', 2, 1] get: ['create_test', 2, 1],
}, },
'Select from get': { 'Select from get': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
from: ['create_test ct'], from: ['create_test ct'],
where: ['id >', 1], where: ['id >', 1],
get: [] get: [],
}, },
'Select from limit get': { 'Select from limit get': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
from: ['create_test ct'], from: ['create_test ct'],
where: ['id >', 1], where: ['id >', 1],
limit: [3], limit: [3],
get: [] get: [],
}, },
'Select where IS NOT NULL': { 'Select where IS NOT NULL': {
select: ['id', 'key as k', 'val'], select: ['id', 'key as k', 'val'],
from: ['create_test ct'], from: ['create_test ct'],
whereIsNotNull: ['id'], whereIsNotNull: ['id'],
get: [] get: [],
}, },
'Select where IS NULL': { 'Select where IS NULL': {
select: ['id', 'key as k', 'val'], select: ['id', 'key as k', 'val'],
from: ['create_test ct'], from: ['create_test ct'],
whereIsNull: ['id'], whereIsNull: ['id'],
get: [] get: [],
}, },
'Select where OR IS NOT NULL': { 'Select where OR IS NOT NULL': {
select: ['id', 'key as k', 'val'], select: ['id', 'key as k', 'val'],
from: ['create_test ct'], from: ['create_test ct'],
whereIsNull: ['id'], whereIsNull: ['id'],
orWhereIsNotNull: ['id'], orWhereIsNotNull: ['id'],
get: [] get: [],
}, },
'Select where OR IS NULL': { 'Select where OR IS NULL': {
select: ['id', 'key as k', 'val'], select: ['id', 'key as k', 'val'],
from: ['create_test ct'], from: ['create_test ct'],
where: ['id', 3], where: ['id', 3],
orWhereIsNull: ['id'], orWhereIsNull: ['id'],
get: [] get: [],
}, },
'Select with string where value': { 'Select with string where value': {
select: ['id', 'key as k', 'val'], select: ['id', 'key as k', 'val'],
from: ['create_test ct'], from: ['create_test ct'],
where: ['id > 3'], where: ['id > 3'],
get: [] get: [],
}, },
'Select with function and argument in WHERE clause': { 'Select with function and argument in WHERE clause': {
select: ['id'], select: ['id'],
from: ['create_test ct'], from: ['create_test ct'],
where: ['id', 'CEILING(SQRT(88))'], where: ['id', 'CEILING(SQRT(88))'],
get: [] get: [],
} },
}, },
'Where in tests': { 'Where in tests': {
'Where in': { 'Where in': {
from: ['create_test'], from: ['create_test'],
whereIn: ['id', [0, 6, 56, 563, 341]], whereIn: ['id', [0, 6, 56, 563, 341]],
get: [] get: [],
}, },
'Or Where in': { 'Or Where in': {
from: ['create_test'], from: ['create_test'],
where: ['key', 'false'], where: ['key', 'false'],
orWhereIn: ['id', [0, 6, 56, 563, 341]], orWhereIn: ['id', [0, 6, 56, 563, 341]],
get: [] get: [],
}, },
'Where Not in': { 'Where Not in': {
from: ['create_test'], from: ['create_test'],
where: ['key', 'false'], where: ['key', 'false'],
whereNotIn: ['id', [0, 6, 56, 563, 341]], whereNotIn: ['id', [0, 6, 56, 563, 341]],
get: [] get: [],
}, },
'Or Where Not in': { 'Or Where Not in': {
from: ['create_test'], from: ['create_test'],
where: ['key', 'false'], where: ['key', 'false'],
orWhereNotIn: ['id', [0, 6, 56, 563, 341]], orWhereNotIn: ['id', [0, 6, 56, 563, 341]],
get: [] get: [],
} },
}, },
'Query modifier tests': { 'Query modifier tests': {
'Order By': { 'Order By': {
@ -150,15 +150,15 @@ module.exports.tests = {
where: [ where: [
'multiple', 'multiple',
['id >', 0], ['id >', 0],
['id <', 9000] ['id <', 9000],
], ],
orderBy: [ orderBy: [
'multiple', 'multiple',
['id', 'DESC'], ['id', 'DESC'],
['k', "ASC"] ['k', 'ASC'],
], ],
limit: [5, 2], limit: [5, 2],
get: [] get: [],
}, },
'Group By': { 'Group By': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
@ -166,20 +166,20 @@ module.exports.tests = {
where: [ where: [
'multiple', 'multiple',
['id >', 0], ['id >', 0],
['id <', 9000] ['id <', 9000],
], ],
groupBy: [ groupBy: [
'multiple', 'multiple',
['k'], ['k'],
[['id', 'val']] [['id', 'val']],
], ],
orderBy: [ orderBy: [
'multiple', 'multiple',
['id', 'DESC'], ['id', 'DESC'],
['k', "ASC"] ['k', 'ASC'],
], ],
limit: [5,2], limit: [5, 2],
get: [] get: [],
}, },
'Or Where': { 'Or Where': {
select: ['id, key as k, val'], select: ['id, key as k, val'],
@ -187,70 +187,70 @@ module.exports.tests = {
where: [' id ', 1], where: [' id ', 1],
orWhere: ['key > ', 0], orWhere: ['key > ', 0],
limit: [2, 1], limit: [2, 1],
get: [] get: [],
}, },
'Like': { Like: {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og'], like: ['key', 'og'],
get: [] get: [],
}, },
'Or Like': { 'Or Like': {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og'], like: ['key', 'og'],
orLike: ['key', 'val'], orLike: ['key', 'val'],
get: [] get: [],
}, },
'Not Like': { 'Not Like': {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og', 'before'], like: ['key', 'og', 'before'],
notLike: ['key', 'val'], notLike: ['key', 'val'],
get: [] get: [],
}, },
'Or Not Like': { 'Or Not Like': {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og', 'before'], like: ['key', 'og', 'before'],
orNotLike: ['key', 'val'], orNotLike: ['key', 'val'],
get: [] get: [],
}, },
'Like Before': { 'Like Before': {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og', 'before'], like: ['key', 'og', 'before'],
get: [] get: [],
}, },
'Like After': { 'Like After': {
from: ['create_test'], from: ['create_test'],
like: ['key', 'og', 'after'], like: ['key', 'og', 'after'],
get: [] get: [],
}, },
'Basic Join': { 'Basic Join': {
from: ['create_test ct'], from: ['create_test ct'],
join: ['create_join cj', 'cj.id=ct.id'], join: ['create_join cj', 'cj.id=ct.id'],
get: [] get: [],
}, },
'Left Join': { 'Left Join': {
from: ['create_test ct'], from: ['create_test ct'],
join: ['create_join cj', 'cj.id=ct.id', 'left'], join: ['create_join cj', 'cj.id=ct.id', 'left'],
get: [] get: [],
}, },
'Inner Join': { 'Inner Join': {
from: ['create_test ct'], from: ['create_test ct'],
join: ['create_join cj', 'cj.id=ct.id', 'inner'], join: ['create_join cj', 'cj.id=ct.id', 'inner'],
get: [] get: [],
}, },
'Join with multiple where values': { 'Join with multiple where values': {
from: ['create_test ct'], from: ['create_test ct'],
join: ['create_join cj', 'cj.id=ct.id', 'inner'], join: ['create_join cj', 'cj.id=ct.id', 'inner'],
where: [{ where: [
'ct.id < ': 3, {
'ct.key ': 'foo' 'ct.id < ': 3,
}], 'ct.key ': 'foo',
get: [] },
} ],
} get: [],
},
},
}; };
let expect = require('chai').expect, let expect = require('chai').expect,
helpers = require('../../lib/helpers'), helpers = require('../../lib/helpers'),
State = require('../../lib/State'); State = require('../../lib/State');
@ -296,8 +296,8 @@ module.exports.runner = (tests, qb, callback) => {
}); });
test('Test Insert', done => { test('Test Insert', done => {
qb.set('id', 98) qb.set('id', 98)
.set('key', "84") .set('key', '84')
.set('val', new Buffer("120")) .set('val', new Buffer('120'))
.insert('create_test', (err, rows) => { .insert('create_test', (err, rows) => {
return callback(err, done); return callback(err, done);
}); });
@ -306,7 +306,7 @@ module.exports.runner = (tests, qb, callback) => {
qb.insert('create_test', { qb.insert('create_test', {
id: 587, id: 587,
key: 1, key: 1,
val: new Buffer('2') val: new Buffer('2'),
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, done);
}); });
@ -316,7 +316,7 @@ module.exports.runner = (tests, qb, callback) => {
.update('create_test', { .update('create_test', {
id: 7, id: 7,
key: 'gogle', key: 'gogle',
val: new Buffer('non-word') val: new Buffer('non-word'),
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, done);
}); });
@ -325,7 +325,7 @@ module.exports.runner = (tests, qb, callback) => {
let object = { let object = {
id: 22, id: 22,
key: 'gogle', key: 'gogle',
val: new Buffer('non-word') val: new Buffer('non-word'),
}; };
qb.set(object) qb.set(object)
@ -357,7 +357,7 @@ module.exports.runner = (tests, qb, callback) => {
test('Delete multiple where values', done => { test('Delete multiple where values', done => {
qb.delete('create_test', { qb.delete('create_test', {
id: 5, id: 5,
key: 'gogle' key: 'gogle',
}, (err, rows) => { }, (err, rows) => {
return callback(err, done); return callback(err, done);
}); });
@ -474,6 +474,6 @@ module.exports.runner = (tests, qb, callback) => {
let state = new State(); let state = new State();
expect(qb.getState()).to.be.deep.equal(state); expect(qb.getState()).to.be.deep.equal(state);
}) });
}); });
}; };

View File

@ -18,9 +18,6 @@ try {
connection = sqlite(':memory:'); connection = sqlite(':memory:');
} catch (e) { } catch (e) {
// Export an empty testsuite if module not loaded // Export an empty testsuite if module not loaded
console.log(e);
console.log("Database adapter dblite not found");
//return {};
} }
if (connection) { if (connection) {
@ -28,13 +25,12 @@ if (connection) {
let nodeQuery = require('../../lib/NodeQuery'); let nodeQuery = require('../../lib/NodeQuery');
let qb = nodeQuery.init('sqlite', connection, adapterName); let qb = nodeQuery.init('sqlite', connection, adapterName);
// Add a test for this adapter // Add a test for this adapter
tests['Select tests']['Select with function and argument in WHERE clause'] = { tests['Select tests']['Select with function and argument in WHERE clause'] = {
'select': ['id'], select: ['id'],
'from': ['create_test'], from: ['create_test'],
'where': ['id', 'ABS(-88)'], where: ['id', 'ABS(-88)'],
'get': [] get: [],
}; };
suite('Dblite adapter tests', () => { suite('Dblite adapter tests', () => {
@ -54,19 +50,21 @@ if (connection) {
.to.be.deep.equal(qb); .to.be.deep.equal(qb);
}); });
test('Test Insert Batch', done => { test('Test Insert Batch', done => {
let data = [{ let data = [
id: 544, {
key: 3, id: 544,
val: new Buffer('7') key: 3,
}, { val: new Buffer('7'),
id: 89, }, {
key: 34, id: 89,
val: new Buffer("10 o'clock") key: 34,
}, { val: new Buffer('10 o\'clock'),
id: 48, }, {
key: 403, id: 48,
val: new Buffer('97') key: 403,
}]; val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, (err, rows) => {
expect(err).is.not.ok; expect(err).is.not.ok;

View File

@ -33,19 +33,21 @@ suite('Mysql2 adapter tests', () => {
.to.be.deep.equal(qb); .to.be.deep.equal(qb);
}); });
test('Test Insert Batch', done => { test('Test Insert Batch', done => {
let data = [{ let data = [
id: 544, {
key: 3, id: 544,
val: new Buffer('7') key: 3,
}, { val: new Buffer('7'),
id: 89, }, {
key: 34, id: 89,
val: new Buffer("10 o'clock") key: 34,
}, { val: new Buffer('10 o\'clock'),
id: 48, }, {
key: 403, id: 48,
val: new Buffer('97') key: 403,
}]; val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, (err, rows) => {
expect(err).is.not.ok; expect(err).is.not.ok;

View File

@ -33,19 +33,21 @@ suite('Mysql adapter tests', () => {
.to.be.deep.equal(qb); .to.be.deep.equal(qb);
}); });
test('Test Insert Batch', done => { test('Test Insert Batch', done => {
let data = [{ let data = [
id: 544, {
key: 3, id: 544,
val: new Buffer('7') key: 3,
}, { val: new Buffer('7'),
id: 89, }, {
key: 34, id: 89,
val: new Buffer("10 o'clock") key: 34,
}, { val: new Buffer('10 o\'clock'),
id: 48, }, {
key: 403, id: 48,
val: new Buffer('97') key: 403,
}]; val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, (err, rows) => {
expect(err).is.not.ok; expect(err).is.not.ok;

View File

@ -36,19 +36,21 @@ suite('Pg adapter tests', () => {
.to.be.deep.equal(qb); .to.be.deep.equal(qb);
}); });
test('Test Insert Batch', done => { test('Test Insert Batch', done => {
let data = [{ let data = [
id: 544, {
key: 3, id: 544,
val: new Buffer('7') key: 3,
}, { val: new Buffer('7'),
id: 89, }, {
key: 34, id: 89,
val: new Buffer("10 o'clock") key: 34,
}, { val: new Buffer('10 o\'clock'),
id: 48, }, {
key: 403, id: 48,
val: new Buffer('97') key: 403,
}]; val: new Buffer('97'),
},
];
qb.insertBatch('create_test', data, (err, rows) => { qb.insertBatch('create_test', data, (err, rows) => {
expect(err).is.not.ok; expect(err).is.not.ok;

View File

@ -10,7 +10,7 @@ suite('Base tests', () => {
let files = glob.sync(`${__dirname}/../lib/**/*.js`); let files = glob.sync(`${__dirname}/../lib/**/*.js`);
files.forEach(mod => { files.forEach(mod => {
let obj = require(mod); let obj = require(mod);
let shortName = mod.replace(/^\/(.*?)\/lib\/(.*?)\.js$/g, "$2"); let shortName = mod.replace(/^\/(.*?)\/lib\/(.*?)\.js$/g, '$2');
test(`${shortName} module is sane`, () => { test(`${shortName} module is sane`, () => {
expect(obj).to.be.ok; expect(obj).to.be.ok;
}); });
@ -24,12 +24,12 @@ suite('Base tests', () => {
nodeQueryCopy.instance = null; nodeQueryCopy.instance = null;
expect(() => { expect(() => {
nodeQueryCopy.getQuery(); nodeQueryCopy.getQuery();
}).to.throw(Error, "No Query Builder instance to return"); }).to.throw(Error, 'No Query Builder instance to return');
}); });
test('Invalid driver type', () => { test('Invalid driver type', () => {
expect(() => { expect(() => {
nodeQuery.init('foo', {}, 'bar'); nodeQuery.init('foo', {}, 'bar');
}).to.throw(Error, "Selected driver (Foo) does not exist!"); }).to.throw(Error, 'Selected driver (Foo) does not exist!');
}); });
}); });

View File

@ -10,21 +10,33 @@ let helpers = require('../lib/helpers');
suite('Helper Module Tests', () => { suite('Helper Module Tests', () => {
suite('Type-checking methods', () => { suite('Type-checking methods', () => {
suite('Object wrappers are listed as their native type', () => { suite('Object wrappers are listed as their native type', () => {
test("Boolean Wrapper returns 'boolean' not 'object'", () => { test('Boolean Wrapper returns \'boolean\' not \'object\'', () => {
let item = Boolean(true); let item = Boolean(true);
expect(helpers.type(item)).to.deep.equal('boolean'); expect(helpers.type(item)).to.deep.equal('boolean');
}); });
test("Number Wrapper returns 'number' not 'object", () => { test('Number Wrapper returns \'number\' not \'object\'', () => {
let item = Number(4867); let item = Number(4867);
expect(helpers.type(item)).to.deep.equal('number'); expect(helpers.type(item)).to.deep.equal('number');
}); });
test("String Wrapper returns 'string' not 'object'", () => { test('String Wrapper returns \'string\' not \'object\'', () => {
let item = String("Foo"); let item = String('Foo');
expect(helpers.type(item)).to.deep.equal('string'); expect(helpers.type(item)).to.deep.equal('string');
}); });
}); });
suite('is..Method methods exist', () => { suite('is..Method methods exist', () => {
let types = ['Null','Undefined','Object','Array','String','Number','Boolean','Function','RegExp','NaN','Infinite']; let types = [
'Null',
'Undefined',
'Object',
'Array',
'String',
'Number',
'Boolean',
'Function',
'RegExp',
'NaN',
'Infinite',
];
types.forEach(type => { types.forEach(type => {
test(`is${type} method exists`, () => { test(`is${type} method exists`, () => {
@ -36,7 +48,7 @@ suite('Helper Module Tests', () => {
let trueCases = { let trueCases = {
'Strings are scalar': 'foo', 'Strings are scalar': 'foo',
'Booleans are scalar': true, 'Booleans are scalar': true,
'Numbers are scalar': 545 'Numbers are scalar': 545,
}; };
Object.keys(trueCases).forEach(desc => { Object.keys(trueCases).forEach(desc => {
test(desc, () => { test(desc, () => {
@ -56,10 +68,10 @@ suite('Helper Module Tests', () => {
}); });
suite('isInfinity', () => { suite('isInfinity', () => {
test('The type of 1/0 is infinity', () => { test('The type of 1/0 is infinity', () => {
expect(helpers.type(1/0)).to.equal('infinity'); expect(helpers.type(1 / 0)).to.equal('infinity');
}); });
test('isInfinity is the same as isInfinite', () => { test('isInfinity is the same as isInfinite', () => {
expect(helpers.isInfinite(1/0)).to.be.true; expect(helpers.isInfinite(1 / 0)).to.be.true;
}); });
}); });
suite('isNaN', () => { suite('isNaN', () => {
@ -81,18 +93,20 @@ suite('Helper Module Tests', () => {
}); });
}); });
suite('arrayPluck', () => { suite('arrayPluck', () => {
let orig = [{ let orig = [
foo: 1 {
},{ foo: 1,
foo: 2, }, {
bar: 10 foo: 2,
},{ bar: 10,
foo: 3, }, {
bar: 15 foo: 3,
}]; bar: 15,
},
];
test('Finding members in all objects', () => { test('Finding members in all objects', () => {
expect(helpers.arrayPluck(orig, 'foo')).to.be.deep.equal([1,2,3]); expect(helpers.arrayPluck(orig, 'foo')).to.be.deep.equal([1, 2, 3]);
}); });
test('Some members are missing in some objects', () => { test('Some members are missing in some objects', () => {
expect(helpers.arrayPluck(orig, 'bar')).to.be.deep.equal([10, 15]); expect(helpers.arrayPluck(orig, 'bar')).to.be.deep.equal([10, 15]);
@ -104,13 +118,15 @@ suite('Helper Module Tests', () => {
suite('regexInArray', () => { suite('regexInArray', () => {
let orig = ['apple', ' string ', 6, 4, 7]; let orig = ['apple', ' string ', 6, 4, 7];
let cases = [{ let cases = [
'Dollar sign is not in any of the array items': /\$/, {
'None of the numbers in the array match /5/': /5/ 'Dollar sign is not in any of the array items': /\$/,
},{ 'None of the numbers in the array match /5/': /5/,
"' string ' matches /^ ?string/": /^ ?string/, }, {
"'apple' matches /APPLE/i": /APPLE/i '\' string \' matches /^ ?string/': /^ ?string/,
}]; '\'apple\' matches /APPLE/i': /APPLE/i,
},
];
[0, 1].forEach(i => { [0, 1].forEach(i => {
let boolCase = cases[i]; let boolCase = cases[i];

View File

@ -1,5 +1,4 @@
"use strict"; 'use strict';
let expect = require('chai').expect; let expect = require('chai').expect;
// Use the base driver as a mock for testing // Use the base driver as a mock for testing
@ -7,8 +6,8 @@ let getArgs = require('getargs');
let helpers = require('../lib/helpers'); let helpers = require('../lib/helpers');
let driver = require('../lib/Driver'); let driver = require('../lib/Driver');
let p = require('../lib/QueryParser'); let P = require('../lib/QueryParser');
let parser = new p(driver); let parser = new P(driver);
let State = require('../lib/State'); let State = require('../lib/State');
@ -20,37 +19,28 @@ let mixedSet = function mixedSet(/* $letName, $valType, $key, [$val] */) {
let obj = {}; let obj = {};
if (helpers.isScalar(args.$key) && !helpers.isUndefined(args.$val)) if (helpers.isScalar(args.$key) && !helpers.isUndefined(args.$val)) {
{
// Convert key/val pair to a simple object // Convert key/val pair to a simple object
obj[args.$key] = args.$val; obj[args.$key] = args.$val;
} } else if (helpers.isScalar(args.$key) && helpers.isUndefined(args.$val)) {
else if (helpers.isScalar(args.$key) && helpers.isUndefined(args.$val))
{
// If just a string for the key, and no value, create a simple object with duplicate key/val // If just a string for the key, and no value, create a simple object with duplicate key/val
obj[args.$key] = args.$key; obj[args.$key] = args.$key;
} } else {
else
{
obj = args.$key; obj = args.$key;
} }
Object.keys(obj).forEach(k => { Object.keys(obj).forEach(k => {
// If a single value for the return // If a single value for the return
if (['key','value'].indexOf(args.$valType) !== -1) if (['key', 'value'].indexOf(args.$valType) !== -1) {
{
let pushVal = (args.$valType === 'key') ? k : obj[k]; let pushVal = (args.$valType === 'key') ? k : obj[k];
state[args.$letName].push(pushVal); state[args.$letName].push(pushVal);
} } else {
else
{
state[args.$letName][k] = obj[k]; state[args.$letName][k] = obj[k];
} }
}); });
return state[args.$letName]; return state[args.$letName];
} };
let whereMock = function() { let whereMock = function() {
let args = getArgs('key:string|object, [val]', arguments); let args = getArgs('key:string|object, [val]', arguments);
@ -60,7 +50,7 @@ let whereMock = function() {
mixedSet('rawWhereValues', 'value', args.key, args.val); mixedSet('rawWhereValues', 'value', args.key, args.val);
mixedSet('whereMap', 'both', args.key, args.val); mixedSet('whereMap', 'both', args.key, args.val);
} };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// ! Start Tests // ! Start Tests
@ -75,7 +65,7 @@ suite('Query Parser Tests', () => {
test('Has no operator', () => { test('Has no operator', () => {
let matches = parser.hasOperator('foo'); let matches = parser.hasOperator('foo');
expect(matches).to.be.null; expect(matches).to.be.null;
}) });
}); });
suite('Where parser tests', () => { suite('Where parser tests', () => {
setup(() => { setup(() => {
@ -95,7 +85,7 @@ suite('Query Parser Tests', () => {
}); });
test('Has function key/val object', () => { test('Has function key/val object', () => {
whereMock({ whereMock({
'time <': "SUM(FOO(BAR('x')))" 'time <': 'SUM(FOO(BAR(\'x\')))',
}); });
parser.parseWhere(driver, state); parser.parseWhere(driver, state);
expect(state.whereMap) expect(state.whereMap)
@ -103,7 +93,7 @@ suite('Query Parser Tests', () => {
}); });
test('Has literal value', () => { test('Has literal value', () => {
whereMock({ whereMock({
'foo': 3 foo: 3,
}); });
parser.parseWhere(driver, state); parser.parseWhere(driver, state);
expect(state.whereMap) expect(state.whereMap)
@ -114,59 +104,63 @@ suite('Query Parser Tests', () => {
test('Has multiple literal values', () => { test('Has multiple literal values', () => {
whereMock({ whereMock({
foo: 3, foo: 3,
bar: 5 bar: 5,
}); });
parser.parseWhere(driver, state); parser.parseWhere(driver, state);
expect(state.whereMap) expect(state.whereMap)
.to.be.deep.equal(['"foo" = ?', '"bar" = ?']); .to.be.deep.equal(['"foo" = ?', '"bar" = ?']);
expect(state.whereValues) expect(state.whereValues)
.to.be.deep.equal(['3','5']); .to.be.deep.equal(['3', '5']);
}); });
}); });
suite('Parse join tests', () => { suite('Parse join tests', () => {
let data = [{ let data = [
desc: 'Simple equals condition', {
join: 'table1.field1=table2.field2', desc: 'Simple equals condition',
expected: ['table1.field1','=','table2.field2'] join: 'table1.field1=table2.field2',
},{ expected: ['table1.field1', '=', 'table2.field2'],
desc: 'Db.table.field condition', }, {
join: 'db1.table1.field1!=db2.table2.field2', desc: 'Db.table.field condition',
expected: ['db1.table1.field1','!=', 'db2.table2.field2'] join: 'db1.table1.field1!=db2.table2.field2',
},{ expected: ['db1.table1.field1', '!=', 'db2.table2.field2'],
desc: 'Underscore in identifier', }, {
join: 'table_1.field1 = tab_le2.field_2', desc: 'Underscore in identifier',
expected: ['table_1.field1', '=', 'tab_le2.field_2'] join: 'table_1.field1 = tab_le2.field_2',
},{ expected: ['table_1.field1', '=', 'tab_le2.field_2'],
desc: 'Function in condition', }, {
join: 'table1.field1 > SUM(3+6)', desc: 'Function in condition',
expected: ['table1.field1', '>', 'SUM(3+6)'] join: 'table1.field1 > SUM(3+6)',
}]; expected: ['table1.field1', '>', 'SUM(3+6)'],
},
];
data.forEach(datum => { data.forEach(datum => {
test(datum.desc, () => { test(datum.desc, () => {
let matches = parser.parseJoin(datum.join); let matches = parser.parseJoin(datum.join);
expect(matches.combined).to.be.deep.equal(datum.expected); expect(matches.combined).to.be.deep.equal(datum.expected);
}) });
}); });
}); });
suite('Compile join tests', () => { suite('Compile join tests', () => {
let data = [{ let data = [
desc: 'Simple equals condition', {
clause: 'table1.field1=table2.field2', desc: 'Simple equals condition',
expected: '"table1"."field1" = "table2"."field2"' clause: 'table1.field1=table2.field2',
},{ expected: '"table1"."field1" = "table2"."field2"',
desc: 'Db.table.field condition', }, {
clause: 'db1.table1.field1!=db2.table2.field2', desc: 'Db.table.field condition',
expected: '"db1"."table1"."field1" != "db2"."table2"."field2"' clause: 'db1.table1.field1!=db2.table2.field2',
},{ expected: '"db1"."table1"."field1" != "db2"."table2"."field2"',
desc: 'Underscore in identifier', }, {
clause: 'table_1.field1 = tab_le2.field_2', desc: 'Underscore in identifier',
expected: '"table_1"."field1" = "tab_le2"."field_2"' clause: 'table_1.field1 = tab_le2.field_2',
},{ expected: '"table_1"."field1" = "tab_le2"."field_2"',
desc: 'Function in condition', }, {
clause: 'table1.field1 > SUM(3+6)', desc: 'Function in condition',
expected: '"table1"."field1" > SUM(3+6)' clause: 'table1.field1 > SUM(3+6)',
}]; expected: '"table1"."field1" > SUM(3+6)',
},
];
data.forEach(datum => { data.forEach(datum => {
test(datum.desc, () => { test(datum.desc, () => {