46 lines
1.4 KiB
Kotlin
46 lines
1.4 KiB
Kotlin
|
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
|
||
|
private val dbUrl = appConfig.property("db.jdbcUrl").getString()
|
||
|
@KtorExperimentalAPI
|
||
|
private val dbUser = appConfig.property("db.dbUser").getString()
|
||
|
@KtorExperimentalAPI
|
||
|
private val dbPassword = appConfig.property("db.dbPassword").getString()
|
||
|
|
||
|
@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() }
|
||
|
}
|
||
|
}
|