Add disconnect method

This commit is contained in:
2021-02-26 23:00:29 +01:00
parent c2c8b91dc5
commit 36ed678c5a

View File

@@ -25,17 +25,26 @@ class Connection(
private val host: String = "localhost", private val host: String = "localhost",
private val port: Int = 5432 private val port: Int = 5432
) : Executable { ) : Executable {
private lateinit var connection: ConnectionPool<PostgreSQLConnection> private var connection: ConnectionPool<PostgreSQLConnection>? = null
private val serializer = Serializer() private val serializer = Serializer()
private val logger: Logger? by LoggerDelegate() private val logger: Logger? by LoggerDelegate()
internal fun connect(): ConnectionPool<PostgreSQLConnection> { internal fun connect(): ConnectionPool<PostgreSQLConnection> {
if (!::connection.isInitialized || !connection.isConnected()) { return connection.let { connectionPool ->
connection = PostgreSQLConnectionBuilder.createConnectionPool( if (connectionPool == null || !connectionPool.isConnected()) {
PostgreSQLConnectionBuilder.createConnectionPool(
"jdbc:postgresql://$host:$port/$database?user=$username&password=$password" "jdbc:postgresql://$host:$port/$database?user=$username&password=$password"
) ).also {
connection = it
} }
return connection } else {
connectionPool
}
}
}
fun disconnect() {
connection?.run { disconnect() }
} }
fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) = connect().inTransaction(f) fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) = connect().inTransaction(f)