diff --git a/lib/pool_cluster.js b/lib/pool_cluster.js index 8077cf1381..ef68e60fe6 100644 --- a/lib/pool_cluster.js +++ b/lib/pool_cluster.js @@ -37,6 +37,18 @@ const getMonotonicMilliseconds = function () { return Math.floor(ms); }; +const patternRegExp = function (pattern) { + if (pattern instanceof RegExp) { + return pattern; + } + + const source = pattern + .replace(/([.+?^=!:${}()|[\]/\\])/g, '\\$1') + .replace(/\*/g, '.*'); + + return new RegExp(`^${source}$`); +}; + class PoolNamespace { constructor(cluster, pattern, selector) { this._cluster = cluster; @@ -256,20 +268,12 @@ class PoolCluster extends EventEmitter { let currentTime = 0; let foundNodeIds = this._findCaches[pattern]; - if (typeof this._findCaches[pattern] === 'undefined') { - if (pattern === '*') { - // all - foundNodeIds = this._serviceableNodeIds; - } else if (this._serviceableNodeIds.indexOf(pattern) !== -1) { - // one - foundNodeIds = [pattern]; - } else { - // wild matching - const keyword = pattern.substring(pattern.length - 1, 0); - foundNodeIds = this._serviceableNodeIds.filter((id) => - id.startsWith(keyword) - ); - } + if (foundNodeIds === undefined) { + const expression = patternRegExp(pattern); + + foundNodeIds = this._serviceableNodeIds.filter((id) => + id.match(expression) + ); } this._findCaches[pattern] = foundNodeIds; diff --git a/test/esm/integration/pool-cluster/test-promise-wrapper.test.mjs b/test/esm/integration/pool-cluster/test-promise-wrapper.test.mjs index 09706f59db..1b407fdbac 100644 --- a/test/esm/integration/pool-cluster/test-promise-wrapper.test.mjs +++ b/test/esm/integration/pool-cluster/test-promise-wrapper.test.mjs @@ -110,4 +110,40 @@ const { createPoolCluster } = require('../../../../promise.js'); poolCluster.end(); }); + + await test(async () => { + const poolCluster = createPoolCluster(); + poolCluster.add('SLAVE', common.config); + + try { + await poolCluster.getConnection('SLAVE1'); + assert.fail('An error was expected'); + } catch (error) { + assert.equal( + error.code, + 'POOL_NOEXIST', + 'should throw when PoolNamespace does not exist' + ); + } finally { + poolCluster.end(); + } + }); + + await test(async () => { + const poolCluster = createPoolCluster(); + poolCluster.add('SLAVE1', common.config); + + try { + const connection = await poolCluster.getConnection(/SLAVE[12]/); + assert.equal( + connection.connection._clusterId, + 'SLAVE1', + 'should match regex pattern' + ); + } catch (error) { + assert.fail('should not throw'); + } finally { + poolCluster.end(); + } + }); })();