Skip to content

Instantly share code, notes, and snippets.

@ntung
Forked from eliotsykes/DataNukerService.groovy
Created January 17, 2020 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntung/636d0a22afcea5d3f0ae39d477222568 to your computer and use it in GitHub Desktop.
Save ntung/636d0a22afcea5d3f0ae39d477222568 to your computer and use it in GitHub Desktop.
Grails GORM Truncate Tables in H2
package com.jetbootlabs.services
/*
* Truncates H2 tables mapped by the domainClasses variable. Useful for cleaning up test data.
*
* Temporarily disables referential integrity to avoid constraint violation errors when
* deleting records.
*
* Inspired by Luke Daley's blog post on how to do this in MySQL:
* http://ldaley.com/post/398082618/brute-force-fixture-cleanup-in-grails
*/
class DataNukerService {
def sessionFactory
def dataSource
def grailsApplication
def execute() {
sessionFactory.currentSession.flush()
def db = new Sql(dataSource)
db.withBatch { stmt ->
stmt.addBatch("SET REFERENTIAL_INTEGRITY FALSE")
def domainClasses = grailsApplication.domainClasses*.clazz
domainClasses.each { domainClass ->
def metadata = sessionFactory.getClassMetadata(domainClass)
stmt.addBatch("TRUNCATE TABLE ${metadata.tableName}")
}
stmt.addBatch("SET REFERENTIAL_INTEGRITY TRUE")
}
sessionFactory.currentSession.clear()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment