2016-03-31 18:39:03 +08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var PSQL = require('cartodb-psql');
|
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
|
|
|
|
2018-02-15 19:25:55 +08:00
|
|
|
function hasDBParams (dbparams) {
|
|
|
|
return (dbparams.user && dbparams.host && dbparams.port && dbparams.dbname && dbparams.pass);
|
|
|
|
}
|
|
|
|
|
|
|
|
QueryRunner.prototype.run = function (job_id, sql, user, timeout, dbparams, callback) {
|
|
|
|
if (hasDBParams(dbparams)) {
|
|
|
|
return this._run(dbparams, job_id, sql, timeout, callback);
|
|
|
|
}
|
|
|
|
|
2018-05-25 23:25:38 +08:00
|
|
|
const dbConfigurationError = new Error('Batch Job DB misconfiguration');
|
|
|
|
dbConfigurationError.type = 'batch-job';
|
|
|
|
dbConfigurationError.subtype = 'job-db-conf-error';
|
|
|
|
dbConfigurationError.http_status = 400;
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2018-05-25 23:25:38 +08:00
|
|
|
return callback(dbConfigurationError);
|
2018-02-15 19:25:55 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
QueryRunner.prototype._run = function (dbparams, job_id, sql, timeout, callback) {
|
|
|
|
var pg = new PSQL(dbparams);
|
|
|
|
|
|
|
|
pg.query('SET statement_timeout=' + timeout, function (err) {
|
|
|
|
if(err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// mark query to allow to users cancel their queries
|
|
|
|
sql = '/* ' + job_id + ' */ ' + sql;
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2018-02-15 19:25:55 +08:00
|
|
|
debug('Running query [timeout=%d] %s', timeout, sql);
|
|
|
|
pg.eventedQuery(sql, function (err, query) {
|
|
|
|
if (err) {
|
2016-03-31 18:39:03 +08:00
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
|
2018-02-15 19:25:55 +08:00
|
|
|
query.on('error', callback);
|
2016-03-31 18:39:03 +08:00
|
|
|
|
2018-02-15 19:25:55 +08:00
|
|
|
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
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|