From 145d061e94d80f74ce01ea734153eaa2d426b38b Mon Sep 17 00:00:00 2001 From: ssh24 Date: Mon, 12 Jun 2017 14:18:34 -0400 Subject: [PATCH] Allow case sensitive regex operation --- lib/mysql.js | 11 +++++++++-- test/mysql.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/lib/mysql.js b/lib/mysql.js index ca490b3..7bd2ae3 100644 --- a/lib/mysql.js +++ b/lib/mysql.js @@ -529,16 +529,23 @@ MySQL.prototype.ping = function(cb) { MySQL.prototype.buildExpression = function(columnName, operator, operatorValue, propertyDefinition) { if (operator === 'regexp') { + var clause = columnName + ' REGEXP ?'; + // By default, MySQL regexp is not case sensitive. (https://dev.mysql.com/doc/refman/5.7/en/regexp.html) + // To allow case sensitive regexp query, it has to be binded to a `BINARY` type. + // If ignore case is not specified, search it as case sensitive. + if (!operatorValue.ignoreCase) { + clause = columnName + ' REGEXP BINARY ?'; + } + if (operatorValue.ignoreCase) g.warn('{{MySQL}} {{regex}} syntax does not respect the {{`i`}} flag'); - if (operatorValue.global) g.warn('{{MySQL}} {{regex}} syntax does not respect the {{`g`}} flag'); if (operatorValue.multiline) g.warn('{{MySQL}} {{regex}} syntax does not respect the {{`m`}} flag'); - return new ParameterizedSQL(columnName + ' REGEXP ?', + return new ParameterizedSQL(clause, [operatorValue.source]); } diff --git a/test/mysql.test.js b/test/mysql.test.js index 1034a60..f2cc402 100644 --- a/test/mysql.test.js +++ b/test/mysql.test.js @@ -633,6 +633,15 @@ describe('mysql', function() { }); }); }); + + it('filter with case sensitive regex string', function(done) { + Post.find({where: {content: {regexp: '^a'}}}, function(err, posts) { + should.not.exist(err); + should.exist(posts); + posts.length.should.equal(0); + done(); + }); + }); }); context('with regex literals', function() { @@ -688,6 +697,16 @@ describe('mysql', function() { }); }); }); + + it('filter with case sensitive regex literal', function(done) { + Post.find({where: {content: {regexp: /^B/}}}, function(err, posts) { + should.not.exist(err); + should.exist(posts); + posts.length.should.equal(1); + posts[0].content.should.equal('BBB'); + done(); + }); + }); }); context('with regex objects', function() { @@ -746,6 +765,15 @@ describe('mysql', function() { done(); }); }); + + it('filter with case sensitive regex object', function(done) { + Post.find({where: {content: {regexp: new RegExp(/^a/)}}}, function(err, posts) { + should.not.exist(err); + should.exist(posts); + posts.length.should.equal(0); + done(); + }); + }); }); }); });