2016-03-31 18:39:03 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var PSQL = require('cartodb-psql');
|
2016-09-13 18:32:41 +08:00
|
|
|
var BATCH_QUERY_TIMEOUT = global.settings.batch_query_timeout || 12 * 3600 * 1000; // 12 hours in millisecond
|
2016-10-07 00:24:28 +08:00
|
|
|
var debug = require('./util/debug')('query-runner');
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2016-05-23 23:51:56 +08:00
|
|
|
function QueryRunner(userDatabaseMetadataService) {
|
|
|
|
this.userDatabaseMetadataService = userDatabaseMetadataService;
|
2016-03-31 18:39:03 +08:00
|
|
|
}
|
|
|
|
|
2016-05-14 00:50:55 +08:00
|
|
|
module.exports = QueryRunner;
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2016-05-23 23:51:56 +08:00
|
|
|
QueryRunner.prototype.run = function (job_id, sql, user, callback) {
|
|
|
|
this.userDatabaseMetadataService.getUserMetadata(user, function (err, userDatabaseMetadata) {
|
|
|
|
if (err) {
|
2016-03-31 18:39:03 +08:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
2016-05-23 23:51:56 +08:00
|
|
|
var pg = new PSQL(userDatabaseMetadata, {}, { destroyOnError: true });
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2016-09-13 18:32:41 +08:00
|
|
|
pg.query('SET statement_timeout=' + BATCH_QUERY_TIMEOUT, function (err) {
|
2016-05-23 23:51:56 +08:00
|
|
|
if(err) {
|
2016-03-31 18:39:03 +08:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
2016-05-23 23:51:56 +08:00
|
|
|
// mark query to allow to users cancel their queries
|
|
|
|
sql = '/* ' + job_id + ' */ ' + sql;
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2016-10-07 00:44:21 +08:00
|
|
|
debug('Running query %s', sql);
|
2016-05-23 23:51:56 +08:00
|
|
|
pg.eventedQuery(sql, function (err, query) {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
2016-03-31 18:39:03 +08:00
|
|
|
}
|
2016-05-23 23:51:56 +08:00
|
|
|
|
|
|
|
query.on('error', callback);
|
|
|
|
|
|
|
|
query.on('end', function (result) {
|
|
|
|
// only if result is present then query is done sucessfully otherwise an error has happened
|
|
|
|
// and it was handled by error listener
|
|
|
|
if (result) {
|
|
|
|
callback(null, result);
|
|
|
|
}
|
|
|
|
});
|
2016-03-31 18:39:03 +08:00
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|