Skip to content

Commit

Permalink
Support connecting to uniq socket
Browse files Browse the repository at this point in the history
Set application_name to Postbird.app
  • Loading branch information
Paxa committed Nov 13, 2019
1 parent 9753934 commit 74d1b90
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 27 deletions.
3 changes: 3 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,9 @@ global.App = {
} else if (error.message.match(/^getaddrinfo ENOTFOUND/)) {
var host = error.message.match(/^getaddrinfo ENOTFOUND\s+(.+)$/);
return `Can not resolve host '${host[1]}'`;
} else if (error.message.match(/^connect ENOENT /)) {
var socket = error.message.match(/^connect ENOENT\s+(.+)$/);
return `Unix socket not found at ${socket[1]}`;
} else {
var message = error.message;
if (options.showQuery && error.query) {
Expand Down
92 changes: 65 additions & 27 deletions app/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ var semver = require('semver');
var colors = require('colors/safe');
colors.enabled = true;
var vsprintf = require("sprintf-js").vsprintf;
var ConnectionString = require('connection-string').ConnectionString;


// Change postgres' type parser to use moment instance instead of js Date instance
// because momentjs object has timezone information as in original string (js Date object always use local timezone)
Expand Down Expand Up @@ -107,19 +109,60 @@ class Connection {
return 'template1';
}

static parseConnectionString(postgresUrl /*: string */) {
var parsed = url.parse(postgresUrl);
var auth = (parsed.auth || '').split(':');
var dbname = !parsed.pathname || parsed.pathname == '/' ? this.defaultDatabaseName : parsed.pathname.replace(/^\//, '');
// Use ConnectionString lib to support parsing unix socket in connection string
static parseConnectionString(postgresUrl /*: string */) /*: ConnectionOptions */ {
var cs = new ConnectionString(postgresUrl);
if (!cs.params) cs.params = {};
if (!cs.params.application_name) cs.params.application_name = 'Postbird';

var res = Object.assign({}, cs.params, {
host: cs.hostname,
port: cs.port || cs.params && cs.params && cs.params.socketPort,
database: cs.path && cs.path[0],
user: cs.user,
password: cs.password,
ssl: (cs.params && 'ssl' in cs.params) ? Boolean(cs.params.ssl) : undefined,
sql_query: cs.params && cs.params.sql_query
});
delete res.socketPort;

return {
user: auth[0],
password: auth[1],
host: parsed.hostname,
port: parsed.port || '5432',
database: dbname,
query: parsed.query
};
return res;
}

// Use ConnectionString lib to support parsing unix socket in connection string
static generateConnectionString(options) {
if (options.port == undefined) options.port = '5432';
if (options.host == undefined) options.host = 'localhost';
if (!options.database) options.database = Connection.defaultDatabaseName;

var socketPort = null;

var host = options.host
if (host.startsWith('/')) {
host = {
type: "socket",
name: host,
port: options.port
};
if (`${options.port}` != '5432') {
socketPort = options.port;
}
} else {
host = ConnectionString.parseHost(`${host}${options.port ? ':' + options.port : ''}`);
}

const cs = new ConnectionString('postgres://');
cs.setDefaults({
hosts: [host],
path: [options.database],
user: options.user,
password: options.password
});
if (socketPort) {
cs.params = {};
cs.params.socketPort = socketPort
}
return cs.toString();
}

connectToServer(options /*: string | ConnectionOptions */, callback /*: (success: boolean, error?: Error) => void */) {
Expand All @@ -132,19 +175,7 @@ class Connection {
this.startQuery = options.sql_query;
}
// set defaults
if (options.port == undefined) options.port = '5432';
if (options.host == undefined) options.host = 'localhost';

if (!options.database) options.database = Connection.defaultDatabaseName;

var connectUser = options.user ? `${encodeURIComponent(options.user)}` : '';
if (options.password) connectUser += `:${encodeURIComponent(options.password)}`;
this.connectString = `postgres://${connectUser ? connectUser + '@' : ''}` +
`${options.host}:${options.port}/${encodeURIComponent(options.database)}`;

if (options.query) {
this.connectString += "?" + options.query;
}
this.connectString = Connection.generateConnectionString(options);
} else if (typeof options == 'string') {
this.connectString = options;
options = Connection.parseConnectionString(this.connectString);
Expand All @@ -165,7 +196,7 @@ class Connection {

this.options = options;

this.connection = new pg.Client({connectionString: this.connectString}) /*:: as pg.ClientExt */;
this.connection = this._initConnection(this.connectString);

return this.connection.connect().then(() => {
this.connection.on('notification', (msg) => {
Expand Down Expand Up @@ -208,6 +239,13 @@ class Connection {
});
}

_initConnection(connectString) /*: pg.ClientExt */ {
console.log('connectString', connectString, Connection.parseConnectionString(connectString));
// @ts-ignore
var clientConfig = Connection.parseConnectionString(connectString) /*:: as pg.ClientConfig */;
return new pg.Client(clientConfig) /*:: as pg.ClientExt */;
}

switchDb(database /*: string */, callback /*::? : (success: boolean, error?: Error) => void */) {
this.options.database = database;
return this.connectToServer(this.options, callback);
Expand Down Expand Up @@ -611,7 +649,7 @@ class Connection {
} else {
query = this.connection.activeQuery;
if (query) {
var otherConn = new pg.Client({connectionString: this.connectString});
var otherConn = this._initConnection(this.connectString);
otherConn.connect((error) => {
if (error) {
console.log(error);
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"needle": "2.4.0",
"pg": "7.12.1",
"pg-escape": "^0.2.0",
"connection-string": "3.0.4",
"pug": "2.0.4",
"raven": "2.6.4",
"semver": "^6.1.1",
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,11 @@ configstore@^4.0.0:
write-file-atomic "^2.0.0"
xdg-basedir "^3.0.0"

[email protected]:
version "3.0.4"
resolved "https://registry.yarnpkg.com/connection-string/-/connection-string-3.0.4.tgz#45080b52eeef86630924b6c93849eff90773a148"
integrity sha512-KNtK/TVPk1Ew7t/132fcXubHNytfv3m80vS8xx/ZVeMjH9aTroKAPEqkcJ/+AKaaKAcQQnjY5b3V5KIZTXKmCQ==

console-control-strings@^1.0.0, console-control-strings@~1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e"
Expand Down

0 comments on commit 74d1b90

Please sign in to comment.