Thursday, June 21, 2012

Grails/ Hibernate clean schema

Sometimes you may want to clean up the entire DB. Grails does this for you if you specify create-drop as the datasource dbCreate property, but sometimes (e.g. if you are deploying to a test of prod server, you can't set this to create-drop), you might just want to be able to clean down the database.



One handy script to clear the DB is to run grails schema-export export. This will run the hibernate schema-export ant task, setting the flag to clear the DB. (It will recreate it again after, using the new schema).

If you want to permanently delete the schema you can modify the schema-export and create your own, e.g.

...
target(cleanDb: 'Clean Db using Run Hibernate SchemaExport') {
    depends(packageApp)

    configureFromArgs()

    def file = new File(filename)
    ant.mkdir(dir: file.parentFile)

    configClasspath()
    loadApp()

    populateProperties()

    def configuration = classLoader.loadClass(configClassName).newInstance()
    configuration.setGrailsApplication(grailsApp)
    configuration.setProperties(props)
    def hibernateCfgXml = eventsClassLoader.getResource('hibernate.cfg.xml')
    if (hibernateCfgXml) {
        configuration.configure(hibernateCfgXml)
    }

    def schemaExport = classLoader.loadClass('org.hibernate.tool.hbm2ddl.SchemaExport')
        .newInstance(configuration)
        .setHaltOnError(true)
        .setOutputFile(file.path)
        .setDelimiter(';')

    def action = "Cleaning Db "
    println "${action} in environment '${grailsEnv}' using properties ${props}"


    // 1st drop, warning exceptions
    //schemaExport.execute(stdout, true, true, false)
    schemaExport.drop(true, true)


    if (!schemaExport.exceptions.empty) {
        schemaExport.exceptions[0].printStackTrace()
    }
}




No comments: