jdaugherty commented on issue #14920:
URL: https://github.com/apache/grails-core/issues/14920#issuecomment-3084794109
I've had this same problem. A quick solution for your project would to be
introduce a method interceptor (AbstractMethodInterceptor) from Spock so that
it does withSession { } around every method call. The issue is then how do you
handle roll back? The `@Rollback` annotation exists to help clean-up data.
An alternative route is to clean-up data if you need it, and then use
withSession {} when you need it. The way my team has handled this is we added
a `DatabaseCleanupInterceptor` that is invoked after each test. This then
removes the need for the `@Rollback` and only cleans up data if the test
decides to add it.
This is the relevant clean up method we call from our interceptor:
/**
* Truncate all tables that have been modified since initialization
(or last truncation)
* @return map keyed by table name with a row count of the rows
truncated
*/
static Map<String, Long> truncateDatabase(ApplicationContext
applicationContext, String dataSourceName = "dataSource") {
Map<String, Long> tableRowCount = [:].withDefault { 0 }
DataSource dataSource = lookupDataSource(applicationContext,
dataSourceName)
if (dataSource) {
Sql sql = new Sql(dataSource)
try {
sql.execute('SET ' + 'REFERENTIAL_INTEGRITY FALSE')
sql.eachRow("SELECT table_name, row_count_estimate FROM
information_schema.tables WHERE table_schema = 'TESTDB' AND row_count_estimate
> 0") { row ->
log.debug("Truncating table: ${row.table_name}")
tableRowCount[row.table_name] +=
row.row_count_estimate
sql.executeUpdate('truncate table ' + row.table_name)
}
// Clear the 2nd layer cache if it exists
def sessionFactory =
applicationContext.getBean("sessionFactory", SessionFactory)
sessionFactory?.cache?.evictAllRegions()
}
finally {
try {
sql.execute('SET ' + 'REFERENTIAL_INTEGRITY TRUE')
sql.close()
}
catch (e) {
log.error("Error cleaning up after cleaning up
database", e)
}
}
}
tableRowCount
}
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]