Redshift and Postgres JDBC driver both intercept jdbc://postgresql connection string

Another solution would be to add "OpenSourceSubProtocolOverride=true" to JDBC connection string for regular PostgreSQL connections.

Example:

jdbc:postgresql://localhost:5432/postgres?OpenSourceSubProtocolOverride=true  

This is because the redshift driver registers as being able to handle both the jdbc:postgresql and jdbc:redshift URL prefix.

When the Postgres & Redshift drivers are loaded from their jars they each register with DriverManger.

The logic implemented in DriverMananger.getDriver() and DriverManager.getConnection() is to loop through each of the drivers and stop once a driver indicates that it is able to handle the given URL.

If the Postgres driver registers first, everything works out fine as the Postgres driver only attempts to handle jdbc:postgresql. If Redshift driver manages to register first, then the Postgres driver will never be used.

The only way I have figured out to solve this is to add:

static {
    // Put the redshift driver at the end so that it doesn't
    // conflict with postgres queries
    java.util.Enumeration<Driver> drivers =  DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver d = drivers.nextElement();
        if (d.getClass().getName().equals("com.amazon.redshift.jdbc41.Driver")) {
            try {
                DriverManager.deregisterDriver(d);
                DriverManager.registerDriver(d);
            } catch (SQLException e) {
                throw new RuntimeException("Could not deregister redshift driver");
            }
            break;
        }
    }
}