Make executeOnce public

Signed-off-by: Graham <gpe@openrs2.org>
Graham 3 years ago
parent 2eaba6a680
commit ebfe01e4c4
  1. 9
      db/src/main/kotlin/org/openrs2/db/Database.kt
  2. 41
      db/src/test/kotlin/org/openrs2/db/DatabaseTest.kt

@ -79,7 +79,14 @@ public class Database(
throw AssertionError() throw AssertionError()
} }
private fun <T> executeOnce(transaction: Transaction<T>): T { /**
* Executes a [Transaction]. If the transaction fails due to deadlock, it
* is not retried. This method should therefore only be used if the
* [Transaction.execute] method has side effects.
* @param transaction the transaction.
* @return the result returned by [Transaction.execute].
*/
public fun <T> executeOnce(transaction: Transaction<T>): T {
dataSource.connection.use { connection -> dataSource.connection.use { connection ->
val oldAutoCommit = connection.autoCommit val oldAutoCommit = connection.autoCommit
connection.autoCommit = false connection.autoCommit = false

@ -44,6 +44,19 @@ class DatabaseTest {
assertEquals(0, elapsed) assertEquals(0, elapsed)
} }
@Test
fun testSuccessfulOnce() {
val result = database.executeOnce { connection ->
connection.prepareStatement("VALUES 12345").use { stmt ->
val rows = stmt.executeQuery()
assertTrue(rows.next())
return@executeOnce rows.getInt(1)
}
}
assertEquals(12345, result)
}
@Test @Test
fun testDeadlockRetry() = runBlockingTest { fun testDeadlockRetry() = runBlockingTest {
var attempts = 0 var attempts = 0
@ -68,6 +81,20 @@ class DatabaseTest {
assertEquals(10, elapsed) assertEquals(10, elapsed)
} }
@Test
fun testDeadlockOnce() {
var attempts = 0
assertFailsWith<DeadlockException> {
database.executeOnce<Unit> {
attempts++
throw DeadlockException()
}
}
assertEquals(1, attempts)
}
@Test @Test
fun testDeadlockFailure() { fun testDeadlockFailure() {
var attempts = 0 var attempts = 0
@ -100,6 +127,20 @@ class DatabaseTest {
assertEquals(1, attempts) assertEquals(1, attempts)
} }
@Test
fun testNonDeadlockFailureOnce() {
var attempts = 0
assertFailsWith<TestException> {
database.executeOnce<Unit> {
attempts++
throw TestException()
}
}
assertEquals(1, attempts)
}
@Test @Test
fun testDeadlockCauseChain() = runBlockingTest { fun testDeadlockCauseChain() = runBlockingTest {
var attempts = 0 var attempts = 0

Loading…
Cancel
Save