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.jdbc").getString() @KtorExperimentalAPI private val dbUser = appConfig.property("db.user").getString() @KtorExperimentalAPI private val dbPassword = appConfig.property("db.password").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 dbQuery(block: () -> T): T = withContext(Dispatchers.IO) { transaction { block() } } }