Fast MySQL client for Node.js with support for prepared statements, SSL, compression, and promise-based APIs
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Pool cluster management for multiple connection pools with pattern-based routing, load balancing across multiple databases, and high availability configurations for distributed database architectures.
Creates a pool cluster for managing multiple connection pools.
/**
* Creates a pool cluster
* @param config - Pool cluster configuration options
* @returns PoolCluster instance
*/
function createPoolCluster(config?: PoolClusterOptions): PoolCluster;Usage Examples:
const mysql = require('mysql2');
// Create a pool cluster
const cluster = mysql.createPoolCluster({
canRetry: true,
removeNodeErrorCount: 5,
restoreNodeTimeout: 50000,
defaultSelector: 'RR'
});
// Add pools to cluster
cluster.add('MASTER', {
host: 'master.example.com',
user: 'root',
password: 'password',
database: 'testdb'
});
cluster.add('SLAVE1', {
host: 'slave1.example.com',
user: 'root',
password: 'password',
database: 'testdb'
});
cluster.add('SLAVE2', {
host: 'slave2.example.com',
user: 'root',
password: 'password',
database: 'testdb'
});
// Use cluster for read operations
cluster.getConnection('SLAVE*', (err, connection) => {
if (err) throw err;
connection.query('SELECT * FROM users', (error, results) => {
connection.release();
if (error) throw error;
console.log(results);
});
});
// Use specific pool for write operations
cluster.getConnection('MASTER', (err, connection) => {
if (err) throw err;
connection.query('INSERT INTO users SET ?', userData, (error, results) => {
connection.release();
if (error) throw error;
console.log('User inserted:', results.insertId);
});
});Main pool cluster class providing pool management and connection routing methods.
interface PoolCluster extends EventEmitter {
/** Pool cluster configuration */
config: PoolClusterOptions;
/** Add pool to cluster */
add(config: PoolOptions): void;
add(group: string, config: PoolOptions): void;
add(group: string, connectionUri: string): void;
/** Remove pool from cluster */
remove(pattern?: string): void;
/** Get connection from cluster using pattern matching */
getConnection(callback: (err: Error | null, connection?: PoolConnection) => void): void;
getConnection(pattern: string, callback: (err: Error | null, connection?: PoolConnection) => void): void;
getConnection(pattern: string, selector: string, callback: (err: Error | null, connection?: PoolConnection) => void): void;
/** Get pool namespace for pattern */
of(pattern: string, selector?: string): PoolNamespace;
/** Execute query on cluster */
query(sql: string, callback?: QueryCallback): Query;
query(sql: string, values: any[], callback?: QueryCallback): Query;
/** Execute prepared statement on cluster */
execute(sql: string, values?: any[], callback?: ExecuteCallback): void;
/** Close all pools in cluster */
end(callback?: (err: Error | null) => void): void;
}Namespace interface for executing operations on a subset of pools matching a pattern.
interface PoolNamespace {
/** Execute query on namespace */
query(sql: string, callback?: QueryCallback): Query;
query(sql: string, values: any[], callback?: QueryCallback): Query;
/** Execute prepared statement on namespace */
execute(sql: string, values?: any[], callback?: ExecuteCallback): void;
/** Get connection from namespace */
getConnection(callback: (err: Error | null, connection?: PoolConnection) => void): void;
}Configuration interface for pool clusters.
interface PoolClusterOptions {
/** Enable connection retry on failure */
canRetry?: boolean;
/** Remove node after this many errors */
removeNodeErrorCount?: number;
/** Restore node after this timeout (ms) */
restoreNodeTimeout?: number;
/** Default connection selector algorithm */
defaultSelector?: 'RR' | 'RANDOM' | 'ORDER';
/** Maximum reconnection attempts */
maxReconnects?: number;
/** Selector functions for custom load balancing */
selectors?: {
[name: string]: (pools: Pool[]) => Pool;
};
}Pool clusters emit events for pool management and error handling.
// Event: 'remove' - Pool removed from cluster
cluster.on('remove', (nodeId) => {
console.log('Pool removed:', nodeId);
});
// Event: 'warn' - Warning occurred
cluster.on('warn', (error) => {
console.warn('Cluster warning:', error);
});
// Event: 'online' - Pool came online
cluster.on('online', (nodeId) => {
console.log('Pool online:', nodeId);
});
// Event: 'offline' - Pool went offline
cluster.on('offline', (nodeId) => {
console.log('Pool offline:', nodeId);
});Master-Slave Configuration:
const cluster = mysql.createPoolCluster({
canRetry: true,
removeNodeErrorCount: 3,
restoreNodeTimeout: 60000,
defaultSelector: 'RANDOM'
});
// Add master for writes
cluster.add('MASTER', {
host: 'master.db.com',
user: 'app_user',
password: 'password',
database: 'production',
connectionLimit: 5
});
// Add slaves for reads
cluster.add('SLAVE1', {
host: 'slave1.db.com',
user: 'app_user',
password: 'password',
database: 'production',
connectionLimit: 10
});
cluster.add('SLAVE2', {
host: 'slave2.db.com',
user: 'app_user',
password: 'password',
database: 'production',
connectionLimit: 10
});
// Create namespaces for different operations
const readPool = cluster.of('SLAVE*', 'RANDOM');
const writePool = cluster.of('MASTER');
// Read operations
readPool.query('SELECT * FROM users WHERE active = 1', (err, results) => {
if (err) throw err;
console.log('Active users:', results.length);
});
// Write operations
writePool.query('UPDATE users SET last_login = NOW() WHERE id = ?', [userId], (err, result) => {
if (err) throw err;
console.log('User updated');
});Geographic Distribution:
const cluster = mysql.createPoolCluster();
// US East region
cluster.add('US_EAST_1', {
host: 'us-east-1.rds.amazonaws.com',
user: 'app_user',
password: 'password',
database: 'app_db'
});
cluster.add('US_EAST_2', {
host: 'us-east-2.rds.amazonaws.com',
user: 'app_user',
password: 'password',
database: 'app_db'
});
// EU region
cluster.add('EU_WEST_1', {
host: 'eu-west-1.rds.amazonaws.com',
user: 'app_user',
password: 'password',
database: 'app_db'
});
// Route based on user location
function getConnectionForRegion(region) {
const pattern = region === 'EU' ? 'EU_*' : 'US_*';
return cluster.of(pattern, 'RANDOM');
}Custom Selector:
const cluster = mysql.createPoolCluster({
defaultSelector: 'CUSTOM',
selectors: {
CUSTOM: (pools) => {
// Custom load balancing logic
const availablePools = pools.filter(pool => pool._freeConnections.length > 0);
return availablePools.length > 0
? availablePools[Math.floor(Math.random() * availablePools.length)]
: pools[0];
}
}
});Pool clusters support pattern-based pool selection:
* - Matches any characters? - Matches single characterSLAVE* - Matches SLAVE1, SLAVE2, SLAVE_BACKUP, etc.US_*_1 - Matches US_EAST_1, US_WEST_1, etc.Available selector algorithms:
Pool clusters provide automatic failover and error recovery:
cluster.on('remove', (nodeId) => {
console.log(`Pool ${nodeId} removed due to errors`);
// Optionally add replacement pool
if (nodeId.startsWith('SLAVE')) {
cluster.add('SLAVE_BACKUP', backupConfig);
}
});
cluster.on('warn', (error) => {
console.warn('Cluster warning:', error.message);
// Monitor and alert on cluster health
if (error.code === 'POOL_NONEONLINE') {
console.error('All pools offline! Emergency failover needed.');
}
});