2020-11-11 17:05:21 +00:00
|
|
|
package dev.inmo.plagubot.config
|
|
|
|
|
|
|
|
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 = "",
|
|
|
|
val waitForConnection: Boolean = true
|
2020-11-11 17:05:21 +00:00
|
|
|
) {
|
|
|
|
@Transient
|
2022-09-04 08:37:22 +00:00
|
|
|
val database: Database by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
|
|
|
|
while (true) {
|
|
|
|
return@lazy try {
|
|
|
|
Database.connect(
|
|
|
|
url,
|
|
|
|
driver,
|
|
|
|
username,
|
|
|
|
password
|
|
|
|
).also {
|
|
|
|
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED
|
|
|
|
}
|
|
|
|
} catch (e: Throwable) {
|
|
|
|
if (waitForConnection) {
|
|
|
|
Thread.sleep(1000L)
|
|
|
|
continue
|
|
|
|
} else {
|
|
|
|
throw e
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
error("Unable to get database by some reason")
|
2020-11-11 17:05:21 +00:00
|
|
|
}
|
|
|
|
}
|