add more functionality to connection parameters

This commit is contained in:
bmc 2013-01-21 15:44:55 -06:00
parent 6da25609cf
commit 9dad56a54e
2 changed files with 29 additions and 6 deletions

View File

@ -1,4 +1,5 @@
var dns = require('dns');
var path = require('path');
var defaults = require(__dirname + '/defaults');
@ -35,6 +36,7 @@ var ConnectionParameters = function(config) {
this.password = val('password', config);
this.binary = val('binary', config);
this.ssl = config.ssl || defaults.ssl;
//a domain socket begins with '/'
this.isDomainSocket = (!(this.host||'').indexOf('/'));
};
@ -54,7 +56,7 @@ ConnectionParameters.prototype.getLibpqConnectionString = function(cb) {
params.push("dbname='" + this.database + "'");
}
if(this.isDomainSocket) {
params.push("host=" + this.host);
params.push("host=" + this.getDomainSocketName());
return cb(null, params.join(' '));
}
dns.lookup(this.host, function(err, address) {
@ -64,4 +66,14 @@ ConnectionParameters.prototype.getLibpqConnectionString = function(cb) {
});
};
ConnectionParameters.prototype.getDomainSocketName = function() {
var filename = '.s.PGSQL.' + this.port;
//if host is full path to socket fd with port number, just return it
if(this.host.indexOf(filename) > -1) return this.host;
//otherwise, build it from host + standard filename + port
return path.join(this.host, filename);
};
module.exports = ConnectionParameters;

View File

@ -48,9 +48,20 @@ test('ConnectionParameters initializing from config', function() {
});
test('initializing with unix domain socket', function() {
var subject = new ConnectionParameters('/var/run/pg.sock');
var subject = new ConnectionParameters('/var/run/');
assert.ok(subject.isDomainSocket);
assert.equal(subject.host, '/var/run/pg.sock');
assert.equal(subject.host, '/var/run/');
});
test('builds domain socket', function() {
var subject = new ConnectionParameters({
host: '/var/run/',
port: 1234
});
assert.equal(subject.getDomainSocketName(), '/var/run/.s.PGSQL.1234');
subject.host = '/tmp';
assert.equal(subject.getDomainSocketName(), '/tmp/.s.PGSQL.1234');
assert.equal(subject.getDomainSocketName(), '/tmp/.s.PGSQL.1234');
});
test('libpq connection string building', function() {
@ -113,14 +124,14 @@ test('libpq connection string building', function() {
user: 'brian',
password: 'asf',
port: 5432,
host: '/var/run/pgsockbla'
host: '/tmp/'
};
var subject = new ConnectionParameters(config);
subject.getLibpqConnectionString(assert.calls(function(err, constring) {
assert.isNull(err);
var parts = constring.split(" ");
checkForPart(parts, "user='brian'");
checkForPart(parts, "host=/var/run/pgsockbla");
checkForPart(parts, "host=/tmp/.s.PGSQL.5432");
}));
});
@ -138,4 +149,4 @@ test('libpq connection string building', function() {
assert.equal(subject.password, sourceConfig.password);
});
})
});