

What it does
Automatically caches SELECT sql's in memory, you have serveral cache providers at your disposal and it can even work in clustered mode via redis or mmap!!
This module is wrapping some functions of the mysql2 module for ease of use

Getting Started
1. Start by installing the package:
yarn add mysql-cache
2. Load the code
const MysqlCache = require('mysql-cache')
const mysql = new MysqlCache({
host: '',
user: '',
password: '',
database: '',
cacheProvider: 'LRU',
})
mysql.connect(err => {
if (err) {
throw err
}
console.log('W00t! i\'m connected!!')
})
3. Do awesome stuff!
mysql.query('SELECT ? + ? AS solution', [1, 5], (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(cache.hash + ' is the cache key')
console.log(cache.sql + ' was the sql generated and run (if not cached)')
console.log(cache.isCache + ' boolean if the result was from cache or not')
console.log(res)
mysql.query({
sql: 'SELECT ? + ? AS solution',
params: [1, 5],
}, (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(cache.isCache === true)
})
})
In-depth configuration
Here you can have a overview of a more defined mysql-cache object
const mysql = new MysqlCache({
prettyError: true,
stdoutErrors: true,
TTL: 0,
connectionLimit: 100,
hashing: 'farmhash64',
verbose: true,
caching: true,
cacheProvider: 'memcached',
cacheProviderSetup: {
serverLocation: '127.0.0.1:11211',
options: {
retries:10,
retry:10000,
remove:true,
failOverServers:['192.168.0.103:11211'],
}
}
})
Automatic package installer
mysql-cache can use some packages that will optimise the performance. This is dependent on your settings but if mysql-cache wants to use a module that is not installed (for example mmap-object, farmhash or xxhash) then it will be Automatically installed, so the first time might run a bit slow. Any warnings or errors are printed to the console, fatal errors will throw a exception
Promises
mysql-cache uses bluebird to create promises. If you would like to use them just append the word 'Async' to any api call of mysql-cache that you would like to return promises.
Example
mysql.connectAsync().then(() => {
mysql.flushAsync().then(() => {
mysql.queryAsync({
sql: 'SELECT from test where name = ?',
nestTables: true,
params: [
'Joe'
]
}).then(result => {
console.log(result[1])
console.log(result[0])
}).catch(e => {
throw e
}).finally(() => {
})
}).catch(e => {
throw e
})
}).catch(e => {
throw e
})
Clustered mode or Persistent mode
Want cached data to persist on restarts in your application? OR Running a application in clustered mode but want to share the cache? check this list below for compatibility for the cacheProviders:
Troubleshooting
Glibc errors on yarn/npm install (ubuntu)
wget http://launchpadlibrarian.net/130794928/libc6_2.17-0ubuntu4_amd64.deb
sudo dpkg -i libc6_2.17-0ubuntu4_amd64.deb
Getting make errors on yarn/npm install (ubuntu)
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-5 g++-5
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 80 --slave /usr/bin/g++ g++ /usr/bin/g++-5
sudo update-alternatives --config gcc
// (choose gcc-5 from the list)
Benchmarks
Edit the file settings.js make sure it reflects your mysql database settings
Then execute in the mysql-cache root directory:
node benchmark/samequery.js
node benchmark/randomquery.js
node benchmark/createhash.js
Example output:

Events
mysql.event.on('connected', () => {
console.log('We are now connected to the mysql database')
})
mysql.event.on('flush', () => {
console.log('mysql-cache cache was flushed!')
})
mysql.event.on('hit', (query, hash, result) => {
console.log('mysql-cache hit a cache object!', query, hash, result)
})
mysql.event.on('miss', (query, hash, result) => {
console.log('mysql-cache got a miss on a cache object!', query, hash, result)
})
mysql.event.on('query', sql => {
console.log('mysql-cache is going to run a query, it might be cached or not we dont know yet: ' + sql)
})
mysql.event.on('dbQuery', obj => {
console.log(obj)
})
mysql.event.on('getPool', connection => {
console.log('Pool connection aqquired!')
})
mysql.event.on('endPool', connection => {
console.log('Pool connection was dropped!')
})
mysql.event.on('killPool', () => {
console.log('Pool connection was killed!')
})
mysql.event.on('create', (hash, val, ttl) => {
console.log('Creating cache object: ', hash, val, ttl)
})
mysql.event.on('get', hash => {
console.log('Retrieving cache object: ', hash)
})
mysql.event.on('delete', hash => {
console.log('this cache object was deleted from cache: ', hash)
})
Properties
console.log(mysql.misses)
console.log(mysql.hits)
console.log(mysql.queries)
console.log(mysql.inserts)
console.log(mysql.deletes)
console.log(mysql.selects)
console.log(mysql.updates)
console.log(mysql.poolConnections)
console.log(mysql.config)
mysql.config.TTL = 5
console.log(mysql.config.TTL)
console.log(mysql.mysql)
console.log(mysql.cacheProviders)
API
.query (sql,params,callback,data)
sql: String
*params: Object
callback: Function
data: Object
* More about escaping values by using params
Will execute the given SQL and cache the (err, res, cache) if it's a SELECT statement.
If the SQL was executed before, it will skip the database request and retrieve it from the cache straight away.
Invalid queries will throw a error
Example #1
mysql.query('SELECT id,username,avatar FROM accounts WHERE id = ?', [530], (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
})
Example #2
mysql.query({
sql:'SELECT 6 + ? AS solution',
params: [4],
}, (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
})
Example with one time setting per query
mysql.query('SELECT id, username, avatar FROM accounts WHERE id = ?', [530], (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
}, {
TTL: 6
})
mysql.query('SELECT id, username, avatar FROM accounts WHERE id = ?', [530], (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
}, {
cache: false
})
mysql.query({
sql:'SELECT 6 + 6 AS solution',
cache: false,
}, (err, res, cacheMysql, mysqlCache) => {
})
Example with error handling
mysql.query('SELECT id, username, avatar FROM accounts WHERE id = ?', [530], (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
})
Example with getting some extra information from mysql-cache
mysql.query('SELECT 6 + 6 AS solution', (err, res, cache) => {
const mysqlCacheHash = cache.hash.slice(0, 12)
if (mysqlCache.isCache) {
console.log(mysqlCacheHash + ': is from the cache!')
} else {
console.log(mysqlCacheHash + ': is NOT from the cache!')
}
console.log('The result of the sql ' + cache.sql + ' = ' + mysqlResult[0].solution)
})
The mysql.query function is using node-mysql for querying.
It's wrapping the sql function, check the mysql2 documentation for more information about escaping values
mysql-cache only supports the use of questionmarks in sql at the moment for escaping values
.delKey (id,params)
id: String
params: Object
Deletes a cache key in the cache. You will need to supply a SQL format, this function always expects a callback
Example #1
mysql.delKey('SELECT id,username,avatar FROM accounts WHERE id = ?', [530], err => {
if (err) {
throw new Error(err)
}
console.log('key deleted!')
})
Example #2
mysql.delKey({
sql: 'SELECT id,username,avatar FROM accounts WHERE id = ?',
params: [530],
}, err => {
if (err) {
throw new Error(err)
}
console.log('key deleted!')
})
This exact SQL is now removed from the cache. Making sure the next time this query is executed it will be retrieved from the database.
.stats (object)
object: boolean
Will console.log() some statistics regarding mysql-cache
Example #1
mysql.stats()
Example #2
console.log(mysql.stats(true))
.flush ()
removes all keys and values from the cache, this function always expects a callback
Example
mysql.flush(err => {
if (err) {
throw new Error(err)
}
console.log('cache flushed!')
})
.killPool ()
Kills the connection pool
Example
mysql.killPool(err => {
if (err) {
throw new Error(err)
}
console.log('Pool killed!')
})
Important editor notes
Refreshing cache objects
A already cached object can be refreshed (retrieve from db and then re-cache):
mysql.query({
sql: 'select 1 + 1 as solution',
refreshCache: true,
}, (err, res, cache) => {
if (err) {
throw new Error(err)
}
console.log(result)
})
Contact
You can contact me at specamps@gmail.com