Permalink
Browse files

Add per-connection prepared query cache

  • Loading branch information...
1 parent 43e38cd commit bd4873b2e4951131a11bc23173c12de3ab77d900 @mscdex committed Sep 12, 2012
Showing with 17 additions and 6 deletions.
  1. +17 −6 lib/Client.js
View
@@ -25,10 +25,13 @@ var ABORT_QUERY = 1,
var RE_PARAM = /(?:\?)|(?::(\d+|(?:[a-zA-Z][a-zA-Z0-9_]*)))/g,
DQUOTE = 34,
SQUOTE = 39,
- BSLASH = 92;
+ BSLASH = 92,
+ MAX_CACHE_SIZE = 30;
function Client() {
var self = this;
+ this.queryCache = [];
+ this.queryCache.keys = {};
this.threadId = undefined;
this.connected = false;
this._closeOnEmpty = false;
@@ -171,9 +174,11 @@ Client.prototype.escape = function(str) {
};
Client.prototype.prepare = function(query) {
+ if (this.queryCache.keys[query] !== undefined)
+ return this.queryCache[this.queryCache.keys[query]];
var ppos = RE_PARAM.exec(query), curpos = 0, start = 0, end, parts = [],
i, chr, inQuote = false, escape = false, qchr, tokens = [], qcnt = 0,
- self = this;
+ fn, self = this;
if (ppos) {
do {
for (i=curpos,end=ppos.index; i<end; ++i) {
@@ -209,18 +214,24 @@ Client.prototype.prepare = function(query) {
if (tokens.length) {
if (curpos < query.length)
parts.push(query.substring(curpos));
- return function(values) {
+
+ fn = function(values) {
var ret = '', j, len;
for (j=0,len=tokens.length; j<len; ++j) {
ret += parts[j];
ret += "'";
- ret += self._client.escape(values[tokens[j]]);
+ ret += self._client.escape(values[tokens[j]] + '');
ret += "'";
}
if (j < parts.length)
ret += parts[j];
return ret;
};
+ if (this.queryCache.length === MAX_CACHE_SIZE)
+ delete this.queryCache.keys[this.queryCache.shift().orig];
+ fn.orig = query;
+ this.queryCache.keys[query] = this.queryCache.push(fn) - 1;
+ return fn;
}
}
return function() { return query; };
@@ -243,8 +254,6 @@ Client.prototype._processQueries = function() {
}
};
-Client.LIB_VERSION = addon.version();
-
function Query(parent) {
this._removed = false;
this._parent = parent;
@@ -283,4 +292,6 @@ Results.prototype.abort = function(active) {
return this._aborted;
};
+Client.LIB_VERSION = addon.version();
+Client.escape = addon.escape;
module.exports = Client;

0 comments on commit bd4873b

Please sign in to comment.