Created
May 10, 2012 08:01
-
-
Save eliotsykes/2651804 to your computer and use it in GitHub Desktop.
Grails GORM Truncate Tables in H2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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