Skip to content

Commit

Permalink
Forenkle PostgresDataSourceBuilder
Browse files Browse the repository at this point in the history
Co-authored-by: Giao The Cung <giaothe@gmail.com>
  • Loading branch information
MariusEriksen and gtcno committed May 22, 2024
1 parent cc42262 commit b5b8015
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,18 @@ package no.nav.dagpenger.oppslag.journalpost.id.db
import ch.qos.logback.core.util.OptionHelper.getEnv
import ch.qos.logback.core.util.OptionHelper.getSystemProperty
import com.zaxxer.hikari.HikariDataSource
import mu.KotlinLogging
import org.flywaydb.core.Flyway
import org.flywaydb.core.api.configuration.FluentConfiguration

// Understands how to create a data source from environment variables
internal object PostgresDataSourceBuilder {
const val DB_USERNAME_KEY = "DB_USERNAME"
const val DB_PASSWORD_KEY = "DB_PASSWORD"
const val DB_URL_KEY = "DB_JDBC_URL"
const val DB_JDBC_URL_KEY = "DB_JDBC_URL"

private fun getOrThrow(key: String): String = getEnv(key) ?: getSystemProperty(key)

private val logger = KotlinLogging.logger {}
val dataSource by lazy {
HikariDataSource().apply {
jdbcUrl =
getOrThrow(DB_URL_KEY).ensurePrefix("jdbc:postgresql://").stripCredentials().also {
logger.info("Connecting to $it")
}
username = getOrThrow(DB_USERNAME_KEY)
password = getOrThrow(DB_PASSWORD_KEY)
jdbcUrl = getOrThrow(DB_JDBC_URL_KEY)
maximumPoolSize = 10
minimumIdle = 1
idleTimeout = 10001
Expand Down Expand Up @@ -56,12 +47,3 @@ internal object PostgresDataSourceBuilder {
.migrations
.size
}

private fun String.stripCredentials() = this.replace(Regex("://.*:.*@"), "://")

private fun String.ensurePrefix(prefix: String) =
if (this.startsWith(prefix)) {
this
} else {
prefix + this.substringAfter("//")
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,17 @@ internal object Postgres {
return PostgresDataSourceBuilder.dataSource
}

fun setup() {
private fun setup() {
System.setProperty(ConfigUtils.CLEAN_DISABLED, "false")
System.setProperty(PostgresDataSourceBuilder.DB_URL_KEY, instance.jdbcUrl)
System.setProperty(PostgresDataSourceBuilder.DB_USERNAME_KEY, instance.username)
System.setProperty(PostgresDataSourceBuilder.DB_PASSWORD_KEY, instance.password)
System.setProperty(
PostgresDataSourceBuilder.DB_JDBC_URL_KEY,
instance.jdbcUrl + "&user=${instance.username}&password=${instance.password}",
)
}

fun tearDown() {
System.clearProperty(PostgresDataSourceBuilder.DB_URL_KEY)
System.clearProperty(PostgresDataSourceBuilder.DB_USERNAME_KEY)
System.clearProperty(PostgresDataSourceBuilder.DB_PASSWORD_KEY)
private fun tearDown() {
System.clearProperty(ConfigUtils.CLEAN_DISABLED)
System.clearProperty(PostgresDataSourceBuilder.DB_JDBC_URL_KEY)
}

fun withCleanDb(block: () -> Unit) {
Expand Down

0 comments on commit b5b8015

Please sign in to comment.