output-service-rdb/src/database/DatabaseFactory.kt

46 lines
1.4 KiB
Kotlin
Raw Normal View History

2020-04-04 23:21:17 +02:00
package com.kmalbz.database
import com.typesafe.config.ConfigFactory
import com.zaxxer.hikari.*
import io.ktor.config.HoconApplicationConfig
import io.ktor.util.KtorExperimentalAPI
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
object DatabaseFactory {
@KtorExperimentalAPI
private val appConfig = HoconApplicationConfig(ConfigFactory.load())
@KtorExperimentalAPI
2020-04-06 01:43:43 +02:00
private val dbUrl = appConfig.property("ktor.db.jdbc").getString()
2020-04-04 23:21:17 +02:00
@KtorExperimentalAPI
2020-04-06 01:43:43 +02:00
private val dbUser = appConfig.property("ktor.db.user").getString()
2020-04-04 23:21:17 +02:00
@KtorExperimentalAPI
2020-04-06 01:43:43 +02:00
private val dbPassword = appConfig.property("ktor.db.password").getString()
2020-04-04 23:21:17 +02:00
@KtorExperimentalAPI
fun init() {
Database.connect(hikari())
}
@KtorExperimentalAPI
private fun hikari(): HikariDataSource {
val config = HikariConfig()
config.driverClassName = "org.postgresql.Driver"
config.jdbcUrl = dbUrl
config.username = dbUser
config.password = dbPassword
config.maximumPoolSize = 3
config.isAutoCommit = false
config.transactionIsolation = "TRANSACTION_REPEATABLE_READ"
config.validate()
return HikariDataSource(config)
}
suspend fun <T> dbQuery(block: () -> T): T =
withContext(Dispatchers.IO) {
transaction { block() }
}
}