What is the recommended approach to use Exposed in...
# exposed
r
What is the recommended approach to use Exposed in Ktor apps? I'm aware of
transaction
and
newSuspendedTransaction
functions, so far in my app I've used
newSuspendedTransaction
. However, I have a scenario where I'll need to call a set of functions that each interact with the database using
newSuspendedTransaction
, and if something goes wrong, I'd like the whole set to be rolled back instead of just the transaction that went wrong. The issue doesn't happen if I use
transaction
, but then I'm afraid I won't use Ktor appropriately since coroutines won't be used at all and the thread will be blocked until all the queries are done. Any suggestions?
Just realized that
withSuspendedTransaction
reuses the parent transaction. Did I get this right?
👆 1
👍 1
I created the following helper function to test the behavior and it seems to rollback all parents as well:
Copy code
private suspend fun onSuspendedTransaction(f: suspend Transaction.() -> Unit) {
  val currentTransaction = TransactionManager.currentOrNull()
    
  if (currentTransaction == null) {

newSuspendedTransaction(Dispatchers.IO) { f() }
    } else {
        currentTransaction.withSuspendTransaction(Dispatchers.IO) { f() }
    }
}
My test:
Copy code
try {         
    onSuspendedTransaction {
      onSuspendedTransaction {
        items2.forEach {              
          insertGame(it) }
        }
      
      items1.forEach {    
        insertGame(it) 
      }
    
      onSuspendedTransaction {
        items3.forEach {  
          insertGame(it) 
        }
        throw Exception()
      }
    }
} catch (_: Exception) {}