node-postgres/lib/connection-parameters.js

88 lines
2.3 KiB
JavaScript
Raw Normal View History

2014-03-16 05:40:45 +08:00
var url = require('url');
var dns = require('dns');
var defaults = require('./defaults');
2013-01-18 08:14:13 +08:00
var val = function(key, config, envVar) {
if (envVar === undefined) {
envVar = process.env[ 'PG' + key.toUpperCase() ];
} else if (envVar === false) {
// do nothing ... use false
} else {
envVar = process.env[ envVar ];
}
return config[key] ||
envVar ||
2013-01-18 08:14:13 +08:00
defaults[key];
2013-01-18 08:27:48 +08:00
};
2013-01-18 08:14:13 +08:00
//parses a connection string
var parse = require('pg-connection-string').parse;
2013-01-18 08:27:48 +08:00
var useSsl = function() {
switch(process.env.PGSSLMODE) {
case "disable":
return false;
case "prefer":
case "require":
case "verify-ca":
case "verify-full":
return true;
}
return defaults.ssl;
};
2013-01-18 08:27:48 +08:00
var ConnectionParameters = function(config) {
config = typeof config == 'string' ? parse(config) : (config || {});
this.user = val('user', config);
this.database = val('database', config);
this.port = parseInt(val('port', config), 10);
2013-01-18 08:27:48 +08:00
this.host = val('host', config);
this.password = val('password', config);
this.binary = val('binary', config);
this.ssl = config.ssl || useSsl();
2013-06-07 03:24:12 +08:00
this.client_encoding = val("client_encoding", config);
//a domain socket begins with '/'
this.isDomainSocket = (!(this.host||'').indexOf('/'));
this.application_name = val('application_name', config, 'PGAPPNAME');
this.fallback_application_name = val('fallback_application_name', config, false);
};
var add = function(params, config, paramName) {
var value = config[paramName];
if(value) {
params.push(paramName+"='"+value+"'");
}
};
ConnectionParameters.prototype.getLibpqConnectionString = function(cb) {
var params = [];
add(params, this, 'user');
add(params, this, 'password');
add(params, this, 'port');
add(params, this, 'application_name');
add(params, this, 'fallback_application_name');
if(this.database) {
params.push("dbname='" + this.database + "'");
}
2013-12-11 08:24:55 +08:00
if(this.host) {
params.push("host=" + this.host);
2013-12-11 08:24:55 +08:00
}
if(this.isDomainSocket) {
return cb(null, params.join(' '));
}
2013-06-07 03:06:52 +08:00
if(this.client_encoding) {
params.push("client_encoding='" + this.client_encoding + "'");
2013-06-07 03:06:52 +08:00
}
dns.lookup(this.host, function(err, address) {
if(err) return cb(err, null);
params.push("hostaddr=" + address);
return cb(null, params.join(' '));
});
2013-01-18 08:27:48 +08:00
};
2013-01-18 08:14:13 +08:00
module.exports = ConnectionParameters;