Exposed verison: 0.12.1
Postgres version: 11.1 (42.2.2 version of it's JDBC driver)
Kotlin version: 1.3.20
Ktor version: 1.1.2 (if it matters)
OS: Linux Mint 19.2
I have two interactions with a database:
class RepositoryImpl : Repository {
override fun save(original: String): Option<Int> {
val insertionKey = transaction {
Model.insertAndGetId {
it[original] = original
}
}
return insertionKey.value.map { Option.just(it) }
}
override fun get(original: String): Option<String> {
val selectionResult = transaction {
Model.selectAll()
}.firstOrNull()
return selectionResult?.tryGet(Model.original)?.map { Option.just(it) } ?: Option.empty()
}
}
I can call save as many times as I want and it's all good, but every time I've tried calling get, I got java.lang.IllegalStateException: No transaction in context.. I thought that the problem was that I'm not calling Database.connect before every transaction so I've tried that, but that didn't help. I've also tried using hikari and it didn't help.
Here is my DB config:
object Database {
fun init() {
val hikariConfig = HikariConfig().apply {
jdbcUrl = "jdbc:postgresql://localhost:5432/db_name"
driverClassName = "org.postgresql.Driver"
username = "user"
password = "admin"
maximumPoolSize = 3
isAutoCommit = false
transactionIsolation = "TRANSACTION_REPEATABLE_READ"
validate()
}
Database.connect(HikariDataSource(hikariConfig))
}
}
I'm calling that only once when application is initialized. As I said, since save is working multiple times in a row, I assume I don't have to call connect every time I want to interact with a database.
As I've wrote this, I got the idea what might be wrong.
firstOrNull has to be called in a transaction.
override fun get(original: String): Option<String> {
val selectionResult = transaction {
Model.selectAll().firstOrNull()
}
return selectionResult?.tryGet(Model.original)?.map { Option.just(it) } ?: Option.empty()
}
Most helpful comment
As I've wrote this, I got the idea what might be wrong.
firstOrNullhas to be called in a transaction.