4.3.2.2. The Structure of Groovy scripts

Groovy update scripts have the following structure:

  • The main part, which contains the code executed before the start of the application context. In this section, you can use any Java, Groovy and the Middleware application block classes. However, it should be kept in mind that no beans, infrastructure interfaces and other application objects have yet been instantiated and it is impossible to use them.

    The main part is primarily designed to update the database schema, as usually done with ordinary SQL scripts.

  • The PostUpdate part – a set of closures, which will be executed after the start of the application context and once the update process is finished. Inside these closures, it is possible to use any Middleware objects.

    In this part of the script, it is convenient to perform data import as it is possible to use the Persistence interface and data model objects.

The execution mechanism passes the following variables to the Groovy scripts:

  • ds – instance of javax.sql.DataSource for the application database;

  • log – instance of org.apache.commons.logging.Log to output messages in the server log;

  • postUpdate – object that contains the add(Closure closure) method to add PostUpdate closures described above.

Warning

Groovy scripts are executed only by the server mechanism to launch database scripts.

An example of the Groovy update script:

import com.haulmont.cuba.core.Persistence
import com.haulmont.cuba.core.global.AppBeans
import com.haulmont.refapp.core.entity.Colour
import groovy.sql.Sql

log.info('Executing actions in update phase')

Sql sql = new Sql(ds)
sql.execute """ alter table MY_COLOR add DESCRIPTION varchar(100); """

// Add post update action
postUpdate.add({
    log.info('Executing post update action using fully functioning server')

    def p = AppBeans.get(Persistence.class)
    def tr = p.createTransaction()
    try {
        def em = p.getEntityManager()

        Colour c = new Colour()
        c.name = 'yellow'
        c.description = 'a description'

        em.persist(c)
        tr.commit()
    } finally {
        tr.end()
    }
})