2016-03-08 21:48:56 +08:00
|
|
|
var QueryTables = require('cartodb-query-tables');
|
|
|
|
|
|
|
|
var generateMD5 = require('../utils/md5');
|
|
|
|
|
|
|
|
function CachedQueryTables(tableCache) {
|
|
|
|
this.tableCache = tableCache;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = CachedQueryTables;
|
|
|
|
|
2016-03-11 02:20:56 +08:00
|
|
|
CachedQueryTables.prototype.getAffectedTablesFromQuery = function(pg, sql, skipCache, callback) {
|
2016-03-08 21:48:56 +08:00
|
|
|
var self = this;
|
|
|
|
|
|
|
|
var cacheKey = sqlCacheKey(pg.username(), sql);
|
2016-03-11 02:20:56 +08:00
|
|
|
|
|
|
|
var cachedResult;
|
|
|
|
if (!skipCache) {
|
2017-07-03 17:13:17 +08:00
|
|
|
cachedResult = this.tableCache.peek(cacheKey);
|
2016-03-11 02:20:56 +08:00
|
|
|
}
|
2016-03-08 21:48:56 +08:00
|
|
|
|
|
|
|
if (cachedResult) {
|
|
|
|
cachedResult.hits++;
|
|
|
|
return callback(null, cachedResult.result);
|
|
|
|
} else {
|
|
|
|
QueryTables.getAffectedTablesFromQuery(pg, sql, function(err, result) {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
self.tableCache.set(cacheKey, {
|
|
|
|
result: result,
|
2016-03-08 21:50:08 +08:00
|
|
|
hits: 0
|
2016-03-08 21:48:56 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
return callback(null, result);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
function sqlCacheKey(user, sql) {
|
|
|
|
return user + ':' + generateMD5(sql);
|
|
|
|
}
|