From 527e4ac7aa30a19acb743c8cbaff4f81e907e9cf Mon Sep 17 00:00:00 2001 From: Johan Steffner Date: Mon, 1 Feb 2021 10:16:32 +0100 Subject: [PATCH] Fix nin query replacement regexp issue --- helpers/conditional.js | 8 ++++++-- test/conditions.js | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/helpers/conditional.js b/helpers/conditional.js index cba6223..782b86c 100644 --- a/helpers/conditional.js +++ b/helpers/conditional.js @@ -19,6 +19,10 @@ function getValueInequalityOperator(value) { return valuesThatUseIsOrIsNot.indexOf(value) > -1 ? 'is not' : '!=' } +function escapeRegex(value) { + return value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); +} + /** * Querying where column is equal to a value * @param column {String} - Column name either table.column or column @@ -161,8 +165,8 @@ conditionals.add('$nin', { cascade: false }, function(column, set, values, colle return 'true' } return conditionals.get('$in').fn(column, set, values, collection, original) - .replace(new RegExp(column + ' in', 'g'), column + ' not in') - .replace(new RegExp(column + ' is', 'g'), column + ' is not'); + .replace(new RegExp(escapeRegex(column) + ' in', 'g'), column + ' not in') + .replace(new RegExp(escapeRegex(column) + ' is', 'g'), column + ' is not'); }); /** diff --git a/test/conditions.js b/test/conditions.js index ab0c8fe..7ead062 100644 --- a/test/conditions.js +++ b/test/conditions.js @@ -650,6 +650,25 @@ describe('Conditions', function(){ ); }); + it ('$nin with expression', function(){ + var query = builder.sql({ + type: 'select' + , table: 'users' + , where: { + id: { + '/* \\".* key */ (substring("id",1,1))': { + $nin: ['a'] + } + } + } + }); + + assert.equal( + query.toString() + , `select "users".* from "users" where /* \\".* key */ (substring("id",1,1)) not in ($1)` + ); + }); + it ('should allow an arbitrary amount of conditions', function(){ var query = builder.sql({ type: 'select'