Start of some code style cleanup

This commit is contained in:
Timothy Warren 2015-12-07 15:58:31 -05:00
parent 2cc48b56f8
commit e1a9aa48ec
15 changed files with 76 additions and 53 deletions

7
.jscsrc Normal file
View File

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

View File

@ -86,6 +86,7 @@ gulp.task('mocha', ['lint-tests', 'sloc'], () => {
.pipe(mocha({ .pipe(mocha({
ui: 'tdd', ui: 'tdd',
bail: true, bail: true,
reporter: 'list'
//reporter: 'dot', //reporter: 'dot',
//reporter: 'landing', //reporter: 'landing',
})) }))

View File

@ -21,6 +21,14 @@ module.exports = class Adapter {
* @return {void} * @return {void}
*/ */
execute(/*sql, params, callback*/) { execute(/*sql, params, callback*/) {
throw new Error("Correct adapter not defined for query execution"); throw new Error('Correct adapter not defined for query execution');
} }
}
/**
* Close the current database connection
* @return {void}
*/
close() {
this.instance.close();
}
};

View File

@ -95,7 +95,7 @@ let d = {
raw = raw.replace(funcs[0], funcs[1]); raw = raw.replace(funcs[0], funcs[1]);
// Quote the identifiers inside of the parens // Quote the identifiers inside of the parens
let inParens = funcs[3].substring(1, funcs[3].length -1); let inParens = funcs[3].substring(1, funcs[3].length - 1);
raw = raw.replace(inParens, d.quoteIdentifiers(inParens)); raw = raw.replace(inParens, d.quoteIdentifiers(inParens));
} }
@ -128,9 +128,9 @@ let d = {
insertBatch(table, data) { insertBatch(table, data) {
let vals = [], let vals = [],
fields = Object.keys(data[0]), fields = Object.keys(data[0]),
sql = "", sql = '',
params = [], params = [],
paramString = "", paramString = '',
paramList = []; paramList = [];
// Get the data values to insert, so they can // Get the data values to insert, so they can
@ -145,7 +145,7 @@ let d = {
// object inserted // object inserted
table = d.quoteTable(table); table = d.quoteTable(table);
sql += `INSERT INTO ${table} (${d.quoteIdentifiers(fields).join(",")}) VALUES `; sql += `INSERT INTO ${table} (${d.quoteIdentifiers(fields).join(',')}) VALUES `;
// Create placeholder groups // Create placeholder groups
params = Array(fields.length).fill('?'); params = Array(fields.length).fill('?');
@ -156,10 +156,9 @@ let d = {
return { return {
sql: sql, sql: sql,
values: vals values: vals,
}; };
} },
}; };
module.exports = d; module.exports = d;

View File

@ -1,4 +1,4 @@
"use strict"; 'use strict';
let fs = require('fs'), let fs = require('fs'),
helpers = require('./helpers'), helpers = require('./helpers'),
@ -31,13 +31,13 @@ class NodeQuery {
let paths = { let paths = {
driver: `${__dirname}/drivers/${helpers.upperCaseFirst(driverType)}`, driver: `${__dirname}/drivers/${helpers.upperCaseFirst(driverType)}`,
adapter: `${__dirname}/adapters/${connLib}` adapter: `${__dirname}/adapters/${connLib}`,
}; };
Object.keys(paths).forEach(type => { Object.keys(paths).forEach(type => {
try { try {
fs.statSync(`${paths[type]}.js`); fs.statSync(`${paths[type]}.js`);
} catch(e) { } catch (e) {
throw new Error( throw new Error(
`Selected ${type} (${helpers.upperCaseFirst(driverType)}) does not exist!` `Selected ${type} (${helpers.upperCaseFirst(driverType)}) does not exist!`
); );
@ -60,7 +60,7 @@ class NodeQuery {
*/ */
getQuery() { getQuery() {
if (this.instance == null) { if (this.instance == null) {
throw new Error("No Query Builder instance to return"); throw new Error('No Query Builder instance to return');
} }
return this.instance; return this.instance;

View File

@ -68,8 +68,7 @@ module.exports = class QueryBuilder {
sql = `INSERT INTO ${table} (`; sql = `INSERT INTO ${table} (`;
sql += this.state.setArrayKeys.join(','); sql += this.state.setArrayKeys.join(',');
sql += ") VALUES ("; sql += `) VALUES (${params.join(',')})`;
sql += params.join(',') + ')';
break; break;
case "update": case "update":
@ -205,7 +204,7 @@ module.exports = class QueryBuilder {
} }
else else
{ {
conj = ' ' + conj + ' '; conj = ` ${conj} `;
} }
return conj; return conj;
@ -229,7 +228,7 @@ module.exports = class QueryBuilder {
_whereNull(field, stmt, conj) { _whereNull(field, stmt, conj) {
field = this.driver.quoteIdentifiers(field); field = this.driver.quoteIdentifiers(field);
let item = field + ' ' + stmt; let item = `${field} ${stmt}`;
this._appendMap(this._fixConjunction(conj), item, 'whereNull'); this._appendMap(this._fixConjunction(conj), item, 'whereNull');
} }
@ -268,8 +267,8 @@ module.exports = class QueryBuilder {
this.state.whereValues.push(value); this.state.whereValues.push(value);
}); });
args.conj = (this.state.queryMap.length > 0) ? " " + args.conj + " " : ' WHERE '; args.conj = (this.state.queryMap.length > 0) ? ` ${args.conj} ` : ' WHERE ';
let str = args.key + " " + args.inClause + " (" + params.join(',') + ") "; let str = `${args.key} ${args.inClause} (${params.join(',')}) `;
this._appendMap(args.conj, str, 'whereIn'); this._appendMap(args.conj, str, 'whereIn');
} }
@ -648,10 +647,10 @@ module.exports = class QueryBuilder {
// Parse out the join condition // Parse out the join condition
let parsedCondition = this.parser.compileJoin(cond); let parsedCondition = this.parser.compileJoin(cond);
let condition = table + ' ON ' + parsedCondition; let condition = `${table} ON ${parsedCondition}`;
// Append the join condition to the query map // Append the join condition to the query map
this._appendMap("\n" + type.toUpperCase() + ' JOIN ', condition, 'join'); this._appendMap(`\n${type.toUpperCase()} JOIN `, condition, 'join');
return this; return this;
} }
@ -673,7 +672,7 @@ module.exports = class QueryBuilder {
this.state.groupArray.push(this.driver.quoteIdentifiers(field)); this.state.groupArray.push(this.driver.quoteIdentifiers(field));
} }
this.state.groupString = ' GROUP BY ' + this.state.groupArray.join(','); this.state.groupString = ` GROUP BY ${this.state.groupArray.join(',')}`;
return this; return this;
} }
@ -697,11 +696,11 @@ module.exports = class QueryBuilder {
// Flatten key/val pairs into an array of space-separated pairs // Flatten key/val pairs into an array of space-separated pairs
Object.keys(this.state.orderArray).forEach(key => { Object.keys(this.state.orderArray).forEach(key => {
orderClauses.push(key + ' ' + this.state.orderArray[key].toUpperCase()); orderClauses.push(`${key} ${this.state.orderArray[key].toUpperCase()}`);
}); });
// Set the final string // Set the final string
this.state.orderString = ' ORDER BY ' + orderClauses.join(', '); this.state.orderString = ` ORDER BY ${orderClauses.join(', ')}`;
return this; return this;
} }

View File

@ -25,5 +25,6 @@ module.exports = class State {
this.limit = null; this.limit = null;
this.offset = null; this.offset = null;
} }
} };
// End of module State // End of module State

View File

@ -15,6 +15,5 @@ module.exports = class mysql 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.query(args.sql, args.params, args.callback); return this.instance.query(args.sql, args.params, args.callback);
//this.instance.query.apply(this.instance, Array(args));
} }
} }

View File

@ -19,7 +19,7 @@ module.exports = class pg extends Adapter {
let count = 0; let count = 0;
args.sql = args.sql.replace(/\?/g, () => { args.sql = args.sql.replace(/\?/g, () => {
count++; count++;
return '$' + count; return `$${count}`;
}); });
this.instance.query(args.sql, args.params, args.callback); this.instance.query(args.sql, args.params, args.callback);

View File

@ -14,22 +14,22 @@ module.exports = (function() {
driver.hasTruncate = false; driver.hasTruncate = false;
/** /**
* Generate a limit clause for firebird, which uses the syntax closest to the SQL standard * Set the limit clause
*
* @param {String} sql * @param {String} origSql - SQL statement to modify
* @param {Number} limit * @param {Number} limit - Maximum number of rows to fetch
* @param {Number} offset * @param {Number|null} offset - Number of rows to skip
* @return {String} * @return {String} - Modified SQL statement
*/ */
driver.limit = function(origSql, limit, offset) { driver.limit = function(origSql, limit, offset) {
let sql = 'FIRST ' + limit; let sql = `FIRST ${limit}`;
if (helpers.isNumber(offset)) if (helpers.isNumber(offset))
{ {
sql += ' SKIP ' + offset; sql += ` SKIP ${offset}`;
} }
return origSql.replace(/SELECT/i, "SELECT " + sql);; return origSql.replace(/SELECT/i, `SELECT ${sql}`);
}; };
/** /**
@ -37,7 +37,8 @@ module.exports = (function() {
* *
* @param {String} table - The table to insert to * @param {String} table - The table to insert to
* @param {Array} [data] - The array of object containing data to insert * @param {Array} [data] - The array of object containing data to insert
* @return {String} * @return {void}
* @throws {Error}
*/ */
driver.insertBatch = function(table, data) { driver.insertBatch = function(table, data) {
throw new Error("Not Implemented"); throw new Error("Not Implemented");

View File

@ -14,15 +14,20 @@ module.exports = (function() {
driver.identifierEndChar = '`'; driver.identifierEndChar = '`';
/** /**
* Override default limit method because mysql likes to be different * Set the limit clause
* @param {String} sql - SQL statement to modify
* @param {Number} limit - Maximum number of rows to fetch
* @param {Number|null} offset - Number of rows to skip
* @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}`;
} }
return sql += " LIMIT " + offset + "," + limit; return sql += ` LIMIT ${offset},${limit}`;
}; };
return driver; return driver;

View File

@ -19,7 +19,7 @@ module.exports = (function() {
* *
* @param {String} table - The table to insert to * @param {String} table - The table to insert to
* @param {Array} [data] - The array of object containing data to insert * @param {Array} [data] - The array of object containing data to insert
* @return {String} * @return {String} - The generated sql statement
*/ */
driver.insertBatch = function(table, data) { driver.insertBatch = function(table, data) {
@ -35,30 +35,30 @@ module.exports = (function() {
paramList = []; paramList = [];
data.forEach(function(obj) { data.forEach(obj => {
let row = []; let row = [];
Object.keys(obj).forEach(function(key) { Object.keys(obj).forEach(key => {
row.push(obj[key]); row.push(obj[key]);
}); });
vals.push(row); vals.push(row);
}); });
sql += "INSERT INTO " + driver.quoteTable(table) + "\n"; sql += `INSERT INTO ${driver.quoteTable(table)}\n`;
// Get the field names from the keys of the first // Get the field names from the keys of the first
// object to be inserted // object to be inserted
fields = Object.keys(first); fields = Object.keys(first);
Object.keys(first).forEach(function(key) { Object.keys(first).forEach(key => {
cols.push("'" + driver._quote(first[key]) + "' AS " + driver.quoteIdentifiers(key)); cols.push(`'${driver._quote(first[key])}' AS ${driver.quoteIdentifiers(key)}`);
}); });
sql += "SELECT " + cols.join(', ') + "\n"; sql += `SELECT ${cols.join(', ')}\n`;
vals.forEach(function(row_values) { vals.forEach(row_values => {
let quoted = row_values.map(function(value) { let quoted = row_values.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 {

View File

@ -112,7 +112,7 @@ 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';

View File

@ -75,7 +75,7 @@ if (connection) {
}); });
}); });
suiteTeardown(() => { suiteTeardown(() => {
connection.close(); qb.end();
}); });
}); });
} }

View File

@ -1,4 +1,7 @@
--ui tdd --ui tdd
--bail --bail
--recursive --recursive
--reporter nyan --reporter dot
--slow 100
--timeout 5000
--check-leaks