'Parse postgres URL

I'm trying to parse postgres db credentials, the format is as follows:

postgres://usernname:password@hostaddress:port/databasename

I'm calling a method which returns these credentials in the form of a String in one line and trying to figure out if there is a simple way of parsing them out by username,password port etc instead of using regex.



Solution 1:[1]

As suggested in the comment by @OneCricketeer - you can use URI parser to do this kind of things and it seems also to me like a best possible solution. You can implement it this way:

try {
    URI uri = new URI("postgres://username:[email protected]:123/databasename");
    String[] userAndPassword = uri.getUserInfo().split(":");
    String user = userAndPassword[0];
    String password = userAndPassword[1];
    String host = uri.getHost();
    int port = uri.getPort();
    String database = uri.getPath().substring(1);
} catch (URISyntaxException e) {
    e.printStackTrace(); // handle invalid JDBC URL syntax
}

Also think about your JDBC URL - maybe you have some possibilities to keep those parameters separately in some config and create JDBC URL as a concatentation from these parameters? It would make things easier - this way you wouldn't need any extraction of the parameters from URL.


My old answer below (which is worse than usage of URI parser but I'm leaving it just for comparison with the above solution):

I would go with regex which would be not that hard in this case and it would be then easy to extract parts of data you need.

However, you can also use split method of String to get parts of the String you need, something like:

String url = "postgres://username:password@hostaddress:port/databasename";
String[] urlSplitByColon = url.split(":");
String[] passwordAndHost = urlSplitByColon[2].split("@");
String[] portAndDatabaseName = urlSplitByColon[3].split("/");

String username = urlSplitByColon[1].substring(2); // substring to cut out double slash at the beginning of username
String password = passwordAndHost[0];
String host = passwordAndHost[1];
String port = portAndDatabaseName[0];
String databaseName = portAndDatabaseName[1];

but I would really advice usage of regexp.

Solution 2:[2]

In Node JS, the code below is working for me to connect to Heroku Postgres:

  // Using URL to parse database URL parameters
  const { URL } = require('url');
  const myURL =
  new URL(process.env.DATABASE_URL);
 
  // establishing a database connection
  var { Client } = require('pg');
  var client = new Client({
    user: myURL.username, //local: postgres
    host: myURL.hostname, //local: localhost
    database: myURL.pathname.substring(1), //local: postgres
    password: myURL.password, // local: admin
    port: myURL.port,
    connectionString: process.env.DATABASE_URL,
    ssl: {
      rejectUnauthorized: false
    }
  });

Had to use 'substring' to remove the '/' from the pathname in order to extract the database string.

Running Node v16.14.2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Eric Aya