return "jdbc:postgresql" + "://" + host + ":" + port + "/" + db;
}
protected DataSource createDataSource(Map params, SQLDialect dialect) throws IOException {
DataSource ds = super.createDataSource(params, dialect);
JDBCDataStore closer = new JDBCDataStore();
if (Boolean.TRUE.equals(CREATE_DB_IF_MISSING.lookUp(params))) {
// verify we can connect
Connection cx = null;
boolean canConnect = true;
try {
cx = ds.getConnection();
} catch (SQLException e) {
canConnect = false;
} finally {
closer.closeSafe(cx);
}
if (!canConnect) {
// get the connection params
String host = (String) HOST.lookUp(params);
int port = (Integer) PORT.lookUp(params);
String db = (String) DATABASE.lookUp(params);
String user = (String) USER.lookUp(params);
String password = (String) PASSWD.lookUp(params);
Statement st = null;
try {
// connect to template1 instead
String url = "jdbc:postgresql" + "://" + host + ":" + port + "/template1";
cx = getConnection(user, password, url);
// create the database
String createParams = (String) CREATE_PARAMS.lookUp(params);
String sql = "CREATE DATABASE \"" + db + "\" " + (createParams == null ? "" : createParams);
st = cx.createStatement();
st.execute(sql);
} catch (SQLException e) {
throw new IOException("Failed to create the target database", e);
} finally {
closer.closeSafe(st);
closer.closeSafe(cx);
}
// if we got here the database has been created, now verify it has the postgis
// extensions
// and eventually try to create them
ResultSet rs = null;
try {
String url = "jdbc:postgresql" + "://" + host + ":" + port + "/" + db;
cx = DriverManager.getConnection(url, user, password);
// check we have postgis
st = cx.createStatement();
try {
rs = st.executeQuery("select PostGIS_version()");
rs.close();
} catch (SQLException e) {
// not available eh? create it
st.execute("create extension postgis");
}
} catch (SQLException e) {
throw new IOException("Failed to create the target database", e);
} finally {
closer.closeSafe(st);
closer.closeSafe(cx);
}
// and finally re-create the connection pool
ds = super.createDataSource(params, dialect);
}