Allan Wang
11/17/2018, 7:10 PMoverride fun beforeTestExecution(context: ExtensionContext) {
println("BeforeEx")
Database.connect("jdbc:h2:mem:test;MODE=MySQL", "org.h2.Driver", "test", "test")
transaction {
debug = this@TableExtension.debug
SchemaUtils.create(*tables)
println("Initialized 1 ${SessionTable.selectAll().count()}")
}
transaction {
println("Test 2")
println("Initialized 2 ${SessionTable.selectAll().count()}")
}
}
Everything works until initialized 1, but at the second transaction, the session table does not exist. Previously before extensions, I’d use a single lambda to create a table, execute a test, then drop it, so I didn’t have this problem. Is there anything I did wrong here that causes tables to not persist until they are dropped?
Edit: Fixed for those who are interested
override fun beforeTestExecution(context: ExtensionContext) {
Database.connect("jdbc:h2:mem:test;MODE=MySQL", "org.h2.Driver", "test", "test") {
ThreadLocalTransactionManager(it, DEFAULT_ISOLATION_LEVEL, 1)
}
// New transaction saves transaction to ThreadLocal; accessible through TransactionManager.currentOrNull()
val transaction = TransactionManager.manager.newTransaction(DEFAULT_ISOLATION_LEVEL)
transaction.debug = debug
SchemaUtils.create(*tables)
}
override fun afterTestExecution(context: ExtensionContext) {
val transaction = TransactionManager.currentOrNull() ?: fail("No transaction manager found after sql test")
transaction.commit()
TransactionManager.resetCurrent(TransactionManager.manager)
transaction.currentStatement?.let {
if (!it.isClosed) it.close()
transaction.currentStatement = null
}
transaction.closeExecutedStatements()
}
Not sure if this is the best way to go though as I’ve basically just copied the transaction method, removed the try catch, as well as the loops. This also looks like to me that I need to connect the database with each transaction