Skip to content

Commit

Permalink
Fix #161 - Wrong queries causes unhandled exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
regevbr committed Nov 20, 2019
1 parent deb461e commit 4189787
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/sql.js
Original file line number Diff line number Diff line change
Expand Up @@ -1207,15 +1207,25 @@ SQLConnector.prototype.buildOrderBy = function(model, order) {
if (typeof order === 'string') {
order = [order];
}
const props = self.getModelDefinition(model).properties;
const clauses = [];
for (let i = 0, n = order.length; i < n; i++) {
const t = order[i].split(/[\s,]+/);
const key = t[0];
if (!props[key]) {
// Unknown property, ignore it
debug('Unknown property %s is skipped for model %s', key, model);
continue;
}
if (t.length === 1) {
clauses.push(self.columnEscaped(model, order[i]));
} else {
clauses.push(self.columnEscaped(model, t[0]) + ' ' + t[1]);
}
}
if (!clauses.length) {
return '';
}
return 'ORDER BY ' + clauses.join(',');
};

Expand Down Expand Up @@ -1456,7 +1466,12 @@ SQLConnector.prototype.all = function find(model, filter, options, cb) {
const self = this;
// Order by id if no order is specified
filter = filter || {};
const stmt = this.buildSelect(model, filter, options);
let stmt;
try {
stmt = this.buildSelect(model, filter, options);
} catch (err) {
return cb(err, []);
}
this.execute(stmt.sql, stmt.params, options, function(err, data) {
if (err) {
return cb(err, []);
Expand Down
19 changes: 19 additions & 0 deletions test/sql.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,21 @@ describe('sql connector', function() {
expect(orderBy).to.eql('ORDER BY `NAME` ASC,`VIP` DESC');
});

it('builds order by with non existent field filtered out', function() {
const orderBy = connector.buildOrderBy('customer', ['nam?e', 'name']);
expect(orderBy).to.eql('ORDER BY `NAME`');
});

it('builds order by with non existent field with direction filtered out', function() {
const orderBy = connector.buildOrderBy('customer', ['nam?e ASC', 'name']);
expect(orderBy).to.eql('ORDER BY `NAME`');
});

it('builds order by with only non existent fields', function() {
const orderBy = connector.buildOrderBy('customer', ['nam?e', 'n?ame', '?name DESC']);
expect(orderBy).to.eql('');
});

it('builds fields for columns', function() {
const fields = connector.buildFields('customer',
{name: 'John', vip: true, unknown: 'Random'});
Expand Down Expand Up @@ -503,4 +518,8 @@ describe('sql connector', function() {
expect(function() { runExecute(); }).to.not.throw();
ds.connected = true;
});

it('should not throw if invalid sql statement is created by all', function(done) {
connector.all('customer', {order: 'n?ame'}, {}, done);
});
});

0 comments on commit 4189787

Please sign in to comment.