Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support utility for performing Transactions #201

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions runtime/src/main/kotlin/norm/transaction/TransactionResult.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package norm.transaction

/**
* A result model which will be returned on execution on [executeTransaction].
*/
sealed class TransactionResult<R> {
data class Success<R>(val data: R) : TransactionResult<R>()
data class Error<R>(val error: Throwable) : TransactionResult<R>()

/**
* Returns `true` if transaction is successful. Else `false`.
*/
val isSuccessful: Boolean = this is Success

/**
* Forcefully tries to provide a successful result data.
* If transaction is not successful, it throws [IllegalStateException].
*/
fun get(): R = runCatching { (this as Success).data }
.getOrElse { throw IllegalStateException("Transaction is not successful") }

/**
* @return a result if transaction is successful otherwise null.
*/
fun getOrNull(): R? = if (this is Success) data else null

/**
* @return an error if transaction is failed otherwise null.
*/
fun errorOrNull(): Throwable? = if (this is Error) error else null
}
46 changes: 46 additions & 0 deletions runtime/src/main/kotlin/norm/transaction/TransactionUtil.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package norm.transaction

import java.sql.Connection
import java.sql.SQLException
import javax.sql.DataSource

/**
* Executes queries specified by [block] in the transaction.
*
* @param block Lambda block with connection on which transaction queries will be executed.
* @return The transaction result.
*
* Example:
*
* ```
* val result = dataSource.executeTransaction {
* val user = FindUserByIdQuery().query(it, FindUserByIdParams(id))
* AddUserItemOneCommand().command(it, AddUserItemOneParams(item1, user.id))
* AddUserItemTwoCommand().command(it, AddUserItemTwoParams(item2, user.id))
* }
*
* // Check whether transaction is successful
* val isSuccessful = result.isSuccessful
*
* // Retrieve transaction result
* val viewCount = result.get() // or `result.getOrNull()` to retrieve safely.
*
* // Retrieve exception (if it's failed)
* val error = result.errorOrNull()
* ```
*/
fun <R> DataSource.executeTransaction(block: (Connection) -> R): TransactionResult<R> {
return connection.use { connection ->
connection.autoCommit = false
try {
block(connection)
.also { connection.commit() }
.let { result -> TransactionResult.Success(result) }
} catch (exception: SQLException) {
exception.printStackTrace()

val rollbackError = runCatching { connection.rollback() }.exceptionOrNull()
TransactionResult.Error(rollbackError ?: exception)
}
}
}