mysql-wrap-production
Advanced tools
Comparing version 0.6.0 to 0.7.0
{ | ||
"name": "mysql-wrap-production", | ||
"version": "0.6.0", | ||
"version": "0.7.0", | ||
"description": "Mysql interface and helper functions, wrapping node-mysql", | ||
@@ -5,0 +5,0 @@ "main": "src/mysql-wrap.js", |
@@ -23,2 +23,8 @@ 'use strict'; | ||
let addCalcFoundRows = function (sql) { | ||
let pieces = sql.split(' '); | ||
pieces.splice(1, 0, 'SQL_CALC_FOUND_ROWS'); | ||
return pieces.join(' '); | ||
}; | ||
let getStatementObject = function (statementOrObject) { | ||
@@ -32,5 +38,10 @@ let statement = _.isObject(statementOrObject) ? | ||
if(statement.paginate) { | ||
statement.sql = stripLimit(statement.sql) + ' ' + | ||
paginateLimit(statement.paginate); | ||
statement.sql = addCalcFoundRows( | ||
stripLimit(statement.sql) + ' ' + | ||
paginateLimit(statement.paginate) | ||
); | ||
} | ||
else if(statement.resultCount) { | ||
statement.sql = addCalcFoundRows(statement.sql); | ||
} | ||
@@ -125,7 +136,33 @@ return statement; | ||
conn.query(statementObject, values || [], function (err, rows) { | ||
conn && conn.release && conn.release(); | ||
if(err) { | ||
conn.release(); | ||
reject(err); | ||
} | ||
else if (statementObject.paginate || statementObject.resultCount) { | ||
conn.query('SELECT FOUND_ROWS() AS count', function (err, result) { | ||
conn.release(); | ||
if(err) { | ||
reject(err); | ||
} | ||
else if(statementObject.paginate){ | ||
resolve({ | ||
resultCount: _.first(result).count, | ||
pageCount: Math.ceil( | ||
_.first(result).count / | ||
statementObject.paginate.resultsPerPage | ||
), | ||
currentPage: statementObject.paginate.page, | ||
results: rows | ||
}); | ||
} | ||
else if(statementObject.resultCount) { | ||
resolve({ | ||
resultCount: _.first(result).count, | ||
results: rows | ||
}); | ||
} | ||
}); | ||
} | ||
else { | ||
conn.release(); | ||
resolve(rows); | ||
@@ -132,0 +169,0 @@ } |
@@ -233,4 +233,9 @@ 'use strict'; | ||
}) | ||
.then(function (rows) { | ||
chai.assert.deepEqual(rows, [that.a, that.b]); | ||
.then(function (resp) { | ||
chai.assert.deepEqual(_.omit(resp, 'results'), { | ||
resultCount: 3, | ||
pageCount: 2, | ||
currentPage: 1 | ||
}); | ||
chai.assert.sameDeepMembers(resp.results, [that.a, that.b]); | ||
done(); | ||
@@ -240,2 +245,18 @@ }) | ||
}); | ||
it('should have option to include result count', function (done) { | ||
let that = this; | ||
that.sql.query({ | ||
sql: 'SELECT * FROM `table` LIMIT 2', | ||
resultCount: true | ||
}) | ||
.then(function (resp) { | ||
chai.assert.deepEqual(_.omit(resp, 'results'), { | ||
resultCount: 3 | ||
}); | ||
chai.assert.sameDeepMembers(resp.results, [that.a, that.b]); | ||
done(); | ||
}) | ||
.done(); | ||
}); | ||
}); | ||
@@ -242,0 +263,0 @@ |
39000
762