2020-11-11 17:05:21 +00:00
|
|
|
package dev.inmo.plagubot.config
|
|
|
|
|
2022-09-04 09:07:30 +00:00
|
|
|
import dev.inmo.kslog.common.e
|
|
|
|
import dev.inmo.kslog.common.logger
|
|
|
|
import kotlinx.coroutines.delay
|
2020-11-11 17:05:21 +00:00
|
|
|
import kotlinx.serialization.Serializable
|
|
|
|
import kotlinx.serialization.Transient
|
|
|
|
import org.jetbrains.exposed.sql.Database
|
|
|
|
import org.jetbrains.exposed.sql.transactions.transactionManager
|
2022-05-16 14:07:57 +00:00
|
|
|
import org.koin.core.scope.Scope
|
2020-11-11 17:05:21 +00:00
|
|
|
import org.sqlite.JDBC
|
2022-09-04 08:37:22 +00:00
|
|
|
import java.lang.Exception
|
2020-11-11 17:05:21 +00:00
|
|
|
import java.sql.Connection
|
|
|
|
|
2022-05-16 17:58:16 +00:00
|
|
|
inline val Scope.database: Database?
|
|
|
|
get() = getOrNull<Database>()
|
2021-02-16 19:21:41 +00:00
|
|
|
|
2020-11-11 17:05:21 +00:00
|
|
|
@Serializable
|
|
|
|
data class DatabaseConfig(
|
2020-11-12 05:52:09 +00:00
|
|
|
val url: String = "jdbc:sqlite:file:test?mode=memory&cache=shared",
|
2020-11-11 17:05:21 +00:00
|
|
|
val driver: String = JDBC::class.qualifiedName!!,
|
|
|
|
val username: String = "",
|
2022-09-04 08:37:22 +00:00
|
|
|
val password: String = "",
|
2022-09-04 09:07:30 +00:00
|
|
|
val reconnectOptions: DBConnectOptions? = DBConnectOptions()
|
2020-11-11 17:05:21 +00:00
|
|
|
) {
|
|
|
|
@Transient
|
2022-09-04 09:07:30 +00:00
|
|
|
val database: Database = (0 until (reconnectOptions ?.attempts ?: 1)).firstNotNullOfOrNull {
|
|
|
|
runCatching {
|
|
|
|
Database.connect(
|
|
|
|
url,
|
|
|
|
driver,
|
|
|
|
username,
|
|
|
|
password
|
|
|
|
).also {
|
|
|
|
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED
|
2022-09-04 09:57:40 +00:00
|
|
|
it.connector().close()
|
2022-09-04 08:37:22 +00:00
|
|
|
}
|
2022-09-04 09:07:30 +00:00
|
|
|
}.onFailure {
|
|
|
|
logger.e(it)
|
|
|
|
Thread.sleep(reconnectOptions ?.delay ?: return@onFailure)
|
|
|
|
}.getOrNull()
|
|
|
|
} ?: error("Unable to create database")
|
2020-11-11 17:05:21 +00:00
|
|
|
}
|