Skip to content

Commit

Permalink
Commit transaction after early return (#63)
Browse files Browse the repository at this point in the history
* add test case to demonstrate early (non-labeled) return from transaction
* commit connection in finally block to support inline return
  • Loading branch information
sondrele authored Jan 9, 2025
1 parent 8027b36 commit 2b8388d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/main/kotlin/kotliquery/Session.kt
Original file line number Diff line number Diff line change
Expand Up @@ -304,17 +304,20 @@ open class Session(
}

inline fun <A> transaction(operation: (TransactionalSession) -> A): A {
var shouldCommit = true
try {
connection.begin()
transactional = true
val tx = TransactionalSession(connection, returnGeneratedKeys, autoGeneratedKeys, strict)
val result: A = operation.invoke(tx)
connection.commit()
return result
return operation.invoke(tx)
} catch (e: Exception) {
shouldCommit = false
connection.rollback()
throw e
} finally {
if (shouldCommit) {
connection.commit()
}
transactional = false
}
}
Expand Down
22 changes: 22 additions & 0 deletions src/test/kotlin/kotliquery/UsageTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,28 @@ class UsageTest {
}
}

@Test
fun transactionWithNonLabeledReturnGetsCommitted() {
fun insertAndReturn(session: Session, name: String) {
session.transaction { tx ->
tx.run(queryOf(insert, name, Date()).asUpdate)
// Non-labeled return
return
}
}

using(sessionOf(testDataSource)) { session ->
insertAndReturn(session, "Chris")
}

using(sessionOf(testDataSource)) { session ->
val membersCount = session.single(queryOf("select count(*) as count from members")) { row ->
row.int("count")
}
assertEquals(1, membersCount)
}
}

@Test
fun testHikariCPUsage() {

Expand Down

0 comments on commit 2b8388d

Please sign in to comment.