SHA256
64 lines
2.0 KiB
Java
64 lines
2.0 KiB
Java
package shine.db;
|
|
|
|
import shine.db.connection.DriverManagerDbProvider;
|
|
import utils.config.AppConfig;
|
|
|
|
import java.sql.Connection;
|
|
import java.sql.SQLException;
|
|
|
|
public final class PostgresDbController {
|
|
|
|
private static volatile PostgresDbController instance;
|
|
|
|
private final DriverManagerDbProvider delegate;
|
|
|
|
private PostgresDbController() {
|
|
AppConfig config = AppConfig.getInstance();
|
|
String jdbcUrl = trimToNull(config.getParam("db.url"));
|
|
String dbUser = trimToNull(config.getParam("db.user"));
|
|
String dbPassword = trimToNull(config.getParam("db.password"));
|
|
|
|
if (jdbcUrl == null) {
|
|
throw new IllegalStateException("Config param 'db.url' is required and must point to PostgreSQL");
|
|
}
|
|
if (!jdbcUrl.startsWith("jdbc:postgresql:")) {
|
|
throw new IllegalStateException("Only PostgreSQL runtime is supported. Unsupported db.url=" + jdbcUrl);
|
|
}
|
|
|
|
try {
|
|
DatabaseInitializer.ensurePostgresSchemaInitialized(jdbcUrl, dbUser, dbPassword);
|
|
} catch (SQLException e) {
|
|
throw new RuntimeException("PostgreSQL schema auto-init failed", e);
|
|
}
|
|
|
|
this.delegate = new DriverManagerDbProvider(jdbcUrl, dbUser, dbPassword, connection -> {
|
|
connection.setAutoCommit(true);
|
|
});
|
|
}
|
|
|
|
public static PostgresDbController getInstance() {
|
|
if (instance == null) {
|
|
synchronized (PostgresDbController.class) {
|
|
if (instance == null) {
|
|
instance = new PostgresDbController();
|
|
}
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
public Connection getConnection() throws SQLException {
|
|
return delegate.getConnection();
|
|
}
|
|
|
|
public void close() {
|
|
// no-op
|
|
}
|
|
|
|
private static String trimToNull(String value) {
|
|
if (value == null) return null;
|
|
String trimmed = value.trim();
|
|
return trimmed.isEmpty() ? null : trimmed;
|
|
}
|
|
}
|