Skip to content

Commit 6b0d77b

Browse files
committed
fix: use autocloseable on all postgresql connections
1 parent ca36875 commit 6b0d77b

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

src/main/kotlin/io/sdkman/broker/adapter/secondary/persistence/PostgresHealthRepository.kt

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
package io.sdkman.broker.adapter.secondary.persistence
22

33
import arrow.core.Either
4-
import arrow.core.flatMap
54
import arrow.core.getOrElse
6-
import arrow.core.left
7-
import arrow.core.right
85
import arrow.core.toOption
96
import io.sdkman.broker.domain.repository.HealthCheckFailure
107
import io.sdkman.broker.domain.repository.HealthCheckSuccess
@@ -18,8 +15,11 @@ class PostgresHealthRepository(private val dataSource: DataSource) : HealthRepos
1815
private val logger = LoggerFactory.getLogger(this::class.java)
1916

2017
override fun checkConnectivity(): Either<HealthCheckFailure, HealthCheckSuccess> =
21-
Either.catch { dataSource.connection }
22-
.flatMap { executeHealthCheck(it) }
18+
Either.catch {
19+
dataSource.connection.use { connection ->
20+
executeHealthCheck(connection).getOrElse { throw it }
21+
}
22+
}
2323
.map { HealthCheckSuccess }
2424
.mapLeft { exception ->
2525
logger.error("PostgreSQL health check failed: {}", exception.message, exception)
@@ -35,11 +35,13 @@ class PostgresHealthRepository(private val dataSource: DataSource) : HealthRepos
3535
private fun ResultSet.isHealthCheckSuccessful(): Boolean = this.next() && this.getInt(1) == 1
3636

3737
private fun executeHealthCheck(connection: Connection): Either<RuntimeException, Unit> =
38-
Either.catch { connection.prepareStatement("SELECT 1") }.flatMap { statement ->
39-
Either.catch { statement.executeQuery() }.flatMap { resultSet: ResultSet ->
40-
when {
41-
resultSet.isHealthCheckSuccessful() -> Unit.right()
42-
else -> RuntimeException("PostgreSQL health check query did not return expected result").left()
38+
Either.catch {
39+
connection.prepareStatement("SELECT 1").use { statement ->
40+
statement.executeQuery().use { resultSet ->
41+
when {
42+
resultSet.isHealthCheckSuccessful() -> Unit
43+
else -> throw RuntimeException("PostgreSQL health check query did not return expected result")
44+
}
4345
}
4446
}
4547
}.mapLeft { RuntimeException(it) }

0 commit comments

Comments
 (0)