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

View File

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

View File

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

View File

@ -16,4 +16,4 @@ module.exports = class dblite extends Adapter {
let args = getArgs('sql:string, [params]:array, callback:function', arguments);
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);
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*/) {
let args = getArgs('sql:string, [params], callback:function', arguments);
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);
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);
}
}
};

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
let helpers = {
/**
@ -24,6 +24,7 @@ let helpers = {
if (isNaN(o)) {
return 'nan';
}
if (!isFinite(o)) {
return 'infinity';
}
@ -55,8 +56,7 @@ let helpers = {
if (arr.length === 0) return output;
arr.forEach(obj => {
if ( ! helpers.isUndefined(obj[key]))
{
if (! helpers.isUndefined(obj[key])) {
output.push(obj[key]);
}
});
@ -73,15 +73,17 @@ let helpers = {
*/
regexInArray: (arr, pattern) => {
// Empty case(s)
if ( ! helpers.isArray(arr)) return false;
if (arr.length === 0) return false;
if (! helpers.isArray(arr) || arr.length === 0) {
return false;
}
let i, l = arr.length;
for(i=0; i< l; i++)
{
for (i = 0; i < l; i++) {
// Short circuit if any items match
if (pattern.test(arr[i])) return true;
if (pattern.test(arr[i])) {
return true;
}
}
return false;
@ -96,11 +98,23 @@ let helpers = {
str += '';
let first = str.charAt(0).toUpperCase();
return first + str.substr(1);
}
},
};
// 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 => {
/**
* Determine whether a variable is of the type specified in the
@ -112,9 +126,8 @@ types.forEach(t => {
* @param {mixed} o
* @return {Boolean}
*/
helpers[`is${t}`] = function (o) {
if (t.toLowerCase() === 'infinite')
{
helpers[`is${t}`] = function(o) {
if (t.toLowerCase() === 'infinite') {
t = 'infinity';
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ suite('Base tests', () => {
let files = glob.sync(`${__dirname}/../lib/**/*.js`);
files.forEach(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`, () => {
expect(obj).to.be.ok;
});
@ -24,12 +24,12 @@ suite('Base tests', () => {
nodeQueryCopy.instance = null;
expect(() => {
nodeQueryCopy.getQuery();
}).to.throw(Error, "No Query Builder instance to return");
}).to.throw(Error, 'No Query Builder instance to return');
});
test('Invalid driver type', () => {
expect(() => {
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('Type-checking methods', () => {
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);
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);
expect(helpers.type(item)).to.deep.equal('number');
});
test("String Wrapper returns 'string' not 'object'", () => {
let item = String("Foo");
test('String Wrapper returns \'string\' not \'object\'', () => {
let item = String('Foo');
expect(helpers.type(item)).to.deep.equal('string');
});
});
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 => {
test(`is${type} method exists`, () => {
@ -36,7 +48,7 @@ suite('Helper Module Tests', () => {
let trueCases = {
'Strings are scalar': 'foo',
'Booleans are scalar': true,
'Numbers are scalar': 545
'Numbers are scalar': 545,
};
Object.keys(trueCases).forEach(desc => {
test(desc, () => {
@ -56,10 +68,10 @@ suite('Helper Module Tests', () => {
});
suite('isInfinity', () => {
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', () => {
expect(helpers.isInfinite(1/0)).to.be.true;
expect(helpers.isInfinite(1 / 0)).to.be.true;
});
});
suite('isNaN', () => {
@ -81,18 +93,20 @@ suite('Helper Module Tests', () => {
});
});
suite('arrayPluck', () => {
let orig = [{
foo: 1
},{
let orig = [
{
foo: 1,
}, {
foo: 2,
bar: 10
},{
bar: 10,
}, {
foo: 3,
bar: 15
}];
bar: 15,
},
];
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', () => {
expect(helpers.arrayPluck(orig, 'bar')).to.be.deep.equal([10, 15]);
@ -104,13 +118,15 @@ suite('Helper Module Tests', () => {
suite('regexInArray', () => {
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/
},{
"' string ' matches /^ ?string/": /^ ?string/,
"'apple' matches /APPLE/i": /APPLE/i
}];
'None of the numbers in the array match /5/': /5/,
}, {
'\' string \' matches /^ ?string/': /^ ?string/,
'\'apple\' matches /APPLE/i': /APPLE/i,
},
];
[0, 1].forEach(i => {
let boolCase = cases[i];

View File

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