2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2015-04-27 18:48:34 +08:00
|
|
|
var PSQL = require('cartodb-psql');
|
2019-11-12 20:12:01 +08:00
|
|
|
const dbParamsFromReqParams = require('../utils/database-params');
|
2015-04-27 18:48:34 +08:00
|
|
|
|
2019-10-22 01:07:24 +08:00
|
|
|
function PgQueryRunner (pgConnection) {
|
2015-04-27 18:48:34 +08:00
|
|
|
this.pgConnection = pgConnection;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = PgQueryRunner;
|
|
|
|
|
2015-12-31 00:44:49 +08:00
|
|
|
/**
|
|
|
|
* Runs `query` with `username`'s PostgreSQL role, callback receives error and rows array.
|
|
|
|
*
|
|
|
|
* @param {String} username
|
|
|
|
* @param {String} query
|
|
|
|
* @param {Function} callback function({Error}, {Array}) second argument is guaranteed to be an array
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
PgQueryRunner.prototype.run = function (username, query, callback) {
|
2018-02-08 19:04:03 +08:00
|
|
|
this.pgConnection.getDatabaseParams(username, (err, databaseParams) => {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
2015-04-27 18:48:34 +08:00
|
|
|
}
|
2018-02-08 19:04:03 +08:00
|
|
|
|
2019-11-12 20:12:01 +08:00
|
|
|
const psql = new PSQL(dbParamsFromReqParams(databaseParams));
|
2018-02-08 19:04:03 +08:00
|
|
|
|
|
|
|
psql.query(query, function (err, resultSet) {
|
|
|
|
resultSet = resultSet || {};
|
|
|
|
return callback(err, resultSet.rows || []);
|
|
|
|
});
|
|
|
|
});
|
2015-04-27 18:48:34 +08:00
|
|
|
};
|