Windshaft-cartodb/lib/cartodb/backends/pg_query_runner.js
Raul Ochoa 76cbc2f863 Improve PgQueryRunner public run method
Last param is callback function, receiving err + result, no need to
keep passing two functions, the query handler and the final callback.

It should be easier to understand now as query handler was in a position
where it had to know about receiving a callback, that was exposing an
implementation detail of PgQueryRunner.
2015-12-30 17:44:49 +01:00

47 lines
1.3 KiB
JavaScript

var assert = require('assert');
var PSQL = require('cartodb-psql');
var step = require('step');
function PgQueryRunner(pgConnection) {
this.pgConnection = pgConnection;
}
module.exports = PgQueryRunner;
/**
* 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
*/
PgQueryRunner.prototype.run = function(username, query, callback) {
var self = this;
var params = {};
step(
function setAuth() {
self.pgConnection.setDBAuth(username, params, this);
},
function setConn(err) {
assert.ifError(err);
self.pgConnection.setDBConn(username, params, this);
},
function executeQuery(err) {
assert.ifError(err);
var psql = new PSQL({
user: params.dbuser,
pass: params.dbpass,
host: params.dbhost,
port: params.dbport,
dbname: params.dbname
});
psql.query(query, function(err, resultSet) {
resultSet = resultSet || {};
return callback(err, resultSet.rows || []);
});
}
);
};