No rollback information available…Strip It!

There may be time when you like to undo a commit. In my situation, i was on the wrong branch when made the commit. To solve problem i try to run mercurial command ‘hg rollback’ that rolls back single commit or pull,however. When run, it returned:

 >No rollback information available

Fortunately, i had my changes saved in the patch using shelving. In this post, about alternative if ‘hg rollback’ does do it.

Strip It!

An alternative to rollback there is command ‘hg strip [hashOfChangeset]’. This removes the said changeset including changesets that descend from it.

In order, to use this command you need to enable ‘mq’ extension that is part of mercurial package(version 2.3.1). To enable this extension, update global mercurial configurations -.hgrc file(usually home directory) the ‘extensions’ section as follows:


Afterwards, run the command with the change set you wish to strip (use ‘hg log -l10 will show you last 10 changesets)

 >hg strip someChangeSet

Domain Object Many-To-One relationship Grails GORM and SQL Relationship

This is following post series from ‘Domain Object Relationships in Grails GORM and SQL Relational Databases‘ where we look at the details how the relationships are build in GORM with how physically structrured in DB while cascading and direction addressed.

From Grails Documentation, it appears that the relationship One-To-One is the same as Many-to-One in Grails GORM. In this post, we look at One-To-One relationship used as Many-to-One one and whether it is true that One-to-One equals Many-To-One relationship?

In this post, we use the same example – Book<->Author as in the post on Domain Object One-to-One relationship. In fact, this post builds on it since we are not  going to cover db structure, coding or direction/cascading of the One-to-One relationship. We are building Many-To-One relationship with One-to-One relationship implementation:

 def authorToShare = true)
 def book1 = authorToShare).save(flush: true)
 def book2 = authorToShare).save(flush: true)

As you see, a single Author object – authorToShare is shared  by adding to two different Book objects – book1 & book2 turning the Book and Author  relationship from One-to-One to Many-to-One relationship

Many-To-One with Unidirectional One-To-One Relationship

First, we consider unidirectional One-to-One Book to Author relationship as described in the post ‘Domain Object One-to-One relationship Grails GORM and SQL Relationship‘ to accomplish Many-to-One book and author relationship. If we adding shared author  to two different book objects, it indirectly builds Many-to-One Relationship. To validate, lets have test:

def "one-to-one relationship between Book and Author"() {
 def authorToShare = true)

 def book1 = authorToShare).save(flush: true)
 def book2 = authorToShare).save(flush: true)

 1 == Author.count() ==

This test pass, so GORM permits adding more books(i.e. book1 & book2) with the same author(i.e.authorToShare) making it also Many-to-One relationship. From ER diagram of One-To-One relationship, it is possible to add more books that contains the same id for author(i.e. ‘author_id’ column) . In another words, in the ‘book’ table there is entry for each book that contains author_id column holding the same ‘id’ of Author.

Many-To-One with Bidirectional Relationship

The same test as above is run, however, the relationship between Book and Author this time is bidirectional instead of unidirectional one. When running test, the following exceptions is rised:

 More than one row with the given identifier was found: 1, for class: Book; nested exception is org.hibernate.HibernateException:

To better understand what is going on we update the test as following:

def "one-to-one relationship between Book and Author"() {
 def authorToShare = true)

 def book1 = authorToShare).save(flush: true)
 def book2 = authorToShare).save(flush: true) = null

 1 == Author.count() ==

By adding ‘'(highlighted line), the test passes. This is because, we adjust GORM session, so that there is no two objects(book1 & book2 in our case) pointing to the same object(authorToShare). Apparently, while it is fine with Database table structure (as we see with Unidirection relationship above), the GORM session mechanism prohibit a shared entity (i.e. author) to be reference more than one object (i.e. books). In short, with bidirectional One-to-One relationship, we are unable to turn it into Many-to-One relationship

To summarize, it is true that GORM One-To-One relationship is equal to Many-To-One but ONLY if Unidirectional One.  For Bidirectional One-to-One relationship, while db structure permits Many-to-One relationship, the GORM session it does not. Thus, if you need true one-to-one relationship, make sure it is bidirectional instead unidirectional. Otherwise, by accident its is possible to create Many-to-one that may cause strange behavior when deleting due to extra references around.

Running Multiple Versions of Grails

There may be times when you have to run multiple versions of Grails in your local development environment. It may be because you supporting multiple Grails applications each running different version, or you would like to test your prime Grails app in different version before shipping to customer, or you just grabbed some Grails application from internet( ‘into wild’) and like try out. For whatever reason, in this post i describe one setup that auto detects version of the application and runs it in appropriate Grails version.

Pre-requisite: Unix based machine

General Idea

We set up so that when ‘grails’ command is called, it runs a script. This script will read the version from Grails application( you want to run and forwards all of the commands to the appropriate grails version to run.

All of the multiple Grails framework versions are installed in ‘/DevTools/grails’ folder in a format grails-x.x.x.

From the multiple Grails versions, we have chosen one version as default one  and defined env variable GRAILS_HOME that points to it.

Step 1 – Create Script

Create file ‘grails’ in some folder you choose. Make this file executable by running ‘chmod u+x filename’

Next, copy past the following:



if [ -f ];then
 export GRAILS_VERSION=`grep app.grails.version | sed -E 's/.*=(.*)/\1/'`
 export GRAILS_HOME="$DEV_TOOLS/grails/grails-$GRAILS_VERSION"
 echo " found, using \$GRAILS_HOME of $GRAILS_HOME"
 echo " NOT found, leaving \$GRAILS_HOME as $GRAILS_HOME"

if [ ! -d $GRAILS_HOME ]; then
 if [ ! $GRAILS_HOME = $GRAILS_DEFAULT ] && [ -d $GRAILS_DEFAULT ]; then
        echo "Unable to find $GRAILS_HOME. Switching back to default $GRAILS_DEFAULT"
        echo "ERROR: Unable to find \$GRAILS_HOME directory at $GRAILS_HOME"
        exit 1


Make sure to adjust the highlighted line 8 to point to your folder where all of the different Grails versions are located for you.

Step 2 – Setup ‘grails’ Command to Run Script

Update your PATH variable to include the folder containing the script – grails you created in Step 1.

Note: make sure you restart command line terminal to ensure your new updated env variable PATH is loaded

Running Different Versions

Afterwards, when command ‘grails something’ is called, then it goes to your ‘grails’ script. The scripts searches through the file for the version. Once found, it checks if this version is stored in your machine. If it is not, it runs the default version you have set in ‘GRAILS_HOME’ variable.

There may be times you need to run ‘grails-debug’ command. If that is the case you then change your setup as follows:
1. Rename ‘grails’ script to ‘grails-version’
2. Create new file named ‘grails’ and add the following:

grails-version grails $*

3. Create new file named ‘grails-debug’ and add the following:

grails-version grails-debug $*

Note:make sure you make new scripts executable like step 2

So this will forward ‘grails’ and ‘grails-debug’ commands to versioning script before running either of the commands

Useful Links

Unix Shell Scripting Tutorial

Grails Snippets

This is ongoing post to record different useful codes snippets related to Grails framework

1. Default and Shared Constraints.
It turns out you can specify default constraints that can be applied and shared in any Domain Class. For example, by default the ‘nullable’ constraint is set to ‘false’. If you wish change that,then updated conf/Config.groovy as follows:

grails.gorm.default.constraints = {
    '*'(nullable: false)
    noBlankSized(blank: fralse, size: 4..25)

The ‘*’ attaches the constraint to all property’ validations. The constraint ‘myShared’ can be references in any validation you choose as follows:

class User{
 static constraints = {
        favoriteDish shared: "noBlankSized"

This way you able to share your own default validations while ability to reuse as you like

2. Suppor Handling Request params

A request parameter value can be converted to a specific type with method invocation:


This takes and converts it to long type. Grails supports other methods like byte(), long(), boolean(). Since Grails 2.0 also support for dates.

3. Access Domain class from Plugin
Say you developing plugin that needs to access domain class in the application.

String className = ""
Class clazz = grailsApplication.getDomainClass(className).clazz
def findAnything = clazz.findByStuff(params.stuff)

If Domain class without package and name unique across all packages:

String className = "MyDomainClass"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def findAThing = clazz.findByStuff(params.stuff)

This may not be best practices as we are coupling the plugin with particular applications, however,perhaps in some circumstance it necessary

4. Mocking Upload File feature with multipart/form-data

void testFileUpload(){
        def imgContentType = 'image/jpeg'
        def imgContentBytes = '123' as byte[]
        controller.metaClass.request = new MockMultipartHttpServletRequest()
            new MockMultipartFile('image', 'myImage.jpg', imgContentType, imgContentBytes)
        assertEquals HttpServletResponse.SC_OK, controller.response.status

Current Path from Request
To get current path from the current controller and action:


Grails Environment Aware Framework

One of the awesome features Grails provides is its ability to configure multiple environments to run your application. It comes with three initial environment setups – Development, Test, Production. Besides these environments,  you are able to setup your own custom environment.

The advantage of having multiple environments is the ability to execute your application with different settings, different data sources and other specifics. For example, you may wish to run tests against different database than one used by actual application. Likewise, you may wish not load application data (User, etc) when testing to avoid tests to break. Despite the need, it is accomplished by having different settings in DataSource, Config, BootStrap, BuildConfig and Searchable configurations(grails-app/conf/) each executed per specified environment.

In this post, first I will briefly  cover how to run different environments. Afterwards, I will demonstrate how to declare and configure environments, all of which in relation to practical problem/solution examples from my development process

Run Apps Different Environment

To run app or execute any command(i.e grails war, etc.) in different environment it is needed to specify the environment after ‘grails’ command (i.e. ‘grails [env] run-app’). Here is some examples:

>grails dev run-app
>grails -Dgrails.env=mycustomenv war
>grails test dbm-status

As you can see, the enviroment is specified right after ‘grails’ command. If you don’t specify, it is using the default which is ‘dev’ or Development environment. For your custom environments, you add ‘Dgrails.enf=’ with the name of your custom environment you wish to run

Practical Usages

1. Loading App Data in Bootstrap

At some point, your application will need to have some data like users, roles, etc. One of the ways to import data is to BootStrap(specify in BootStrap.groovy file) the data into your application, however. At the time of running tests, that is in test environment, you probably don’t want to have any data bootstraped, otherwise, it will break your tests(i.e. assert User.count() == 0 fails). So, the solution is to look up environment before importing or not importing data in BootStrap.groovy. Here is example:

class BootStrap {

    def loadDomainDataService

    def init = { servletContext ->

        environments {
            test {
      "starting in Test env.....")
            dbgorm {
      "starting in dbgorm env.....")
            development {
      "starting in dev env.....")
                (User.findAll().empty) ? loadDomainDataService.loadSecurityData() :"Security Data already loaded. Skipped loading...")
                (RentalUnit.findAll().empty) ? loadDomainDataService.loadAppData() :"App Data already loaded. Skipped loading...")

                //don't start app if data not loaded
                assert User.count()
                assert RentalUnit.count()

Or Another way:

import grails.util.GrailsUtil
class BootStrap {

    def loadDomainDataService

    def init = { servletContext ->

        switch (GrailsUtil.environment) {
            case "test":
      "starting in Test env.....")
            case "dbgorm":
      "starting in dbgorm env.....")
                (User.findAll().empty) ? loadDomainDataService.loadSecurityData() :"Security Data already loaded. Skipped loading...")
                (RentalUnit.findAll().empty) ? loadDomainDataService.loadAppData() :"App Data already loaded. Skipped loading...")
                //don't start app if data not loaded
                assert User.count()
                assert RentalUnit.count()

In the above code snippets, the different environments configured is highlighted. There are the predefined env such as ‘test’, ‘dev’ and there is our custom env – ‘dbgorm’. For the custom env, there is no need declare it separately prior using them. Just use them in any configuration file like any of the predefined environments. The custom env will be referenced by the name you choose to use in the configuration files. It is case sensitive.

From the above you can see how we prevent the app data be loaded in ‘test’ or ‘dbgorm’ environment but do load data if application run in ‘dev’ and other env . On the side note, to load data itself we use Grails Fixture plugin about which another post

2. Data Source Dependent on Env
Once your application is loaded with data needed for application like Users, Roles, etc than this info is stored in Database. Afterwards, you would like run tests, however, many of the tests will fail because your database contains application data that most likely conflicts with assertions in your tests (i.e. Users.count()==0).

One of the solutions is to use a separate database for running tests. You have your ‘dev’ environment configured for one database and then your ‘test’ environment with another database. The database used by each environment is configure in conf/DataSource.groovy file. Here is an example:

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "" // one of 'create', 'create-drop', 'update', 'validate', ''
            driverClassName = "com.mysql.jdbc.Driver"
            url = "jdbc:mysql://localhost/minnehaha"
            username = "root"
            password = "mysql"
test {
        dataSource {
            dbCreate = "" // one of 'create', 'create-drop', 'update', 'validate', ''
            driverClassName = "com.mysql.jdbc.Driver"
            url = "jdbc:mysql://localhost/minnehaha_test"
            username = "root"
            password = "mysql"


The highlighted lines shows the each different database configured. So, in our situation, if application is started in ‘dev’ it will be using ‘minnehaha’ database. If  tests run(i.e. grails test-app) then it uses by default the ‘test’ environment, thus, the tests are run against database – ‘minnehaha_test’. This way we are sharing the same application to develop and test while separating the data into two different databases to avoid conflicting between process of testing and other

Interestingly to note, both 'test' and 'dev' databases is managed by Grails Database Migration Plugin, so how would you run migration commands against each different database? Make sure you specify environment when calling any of the Database migration plugin commands. Here is an example:
 >grails dbm-update
 >grails test dbm-update
 The first command will run migrations on default environment which is 'dev' updating database - 'minnehaha' in our case. The second command will run migration script in 'test' env that will update database - 'minnehaha_test' only

3. Migration Script Run at Start Up?… Not Always
We use Grails Database Migration Plugin to manage the database updates, new table creation and database roll backs when needed. Every time the branch is changed or  I received a new code changeset, I was finding myself repetitively running ‘dbm-update’ manually to get dev database in sync. It turns out, this step can be automized, so that when the grails application start, it runs ‘dbm-update’ if there is new migration scripts. For more, see section ‘Run Migration Scripts at Start’ in  the post – Grails Database Migration Plugin

In times adding/updating domain objects, this was a problem. This is because, after making changes in GORM, it was in conflict with current DB structure built by migration scripts at the start up. To solve the problem we created custom environment specifically for GORM development as follows:

Step 1. In the custom env – dbgorm the database will not use migration plugin. Here is conf/DataSource.groovy:

environments {
    dbgorm {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
//          url = "jdbc:h2:mem:devDb;MVCC=TRUE"
            driverClassName = "com.mysql.jdbc.Driver"
            url = "jdbc:mysql://localhost/minnehaha_gorm"
            username = "root"
            password = "mysql"


We accomplish this by configuring our custom environment create and drop database, instead of database migration plugin does it(change ‘dbCreate’ attribute to ‘create-drop’ data source as highlighted in above code).

Step 2. The step 1 takes care of building the database structure, but we still need to prevent migration scripts to run at start up in our custom env – dbgorm. To accomplish, we update conf/Config.groovy as follows:

//To dbm-update On Start
grails.plugin.databasemigration.updateOnStart = true
grails.plugin.databasemigration.updateOnStartFileNames = ["changelog.groovy"]
grails.plugin.databasemigration.changelogLocation = 'grails-app/migrations'

environments {
    dbgorm {
        grails.plugin.databasemigration.updateOnStart = false

So, if the application is run in env – dbgorm, we set the updateOnStart to false that way preventing migrations scripts to be run at start up.

With this setup, we change/update domain class or GORM in dbgorm environment. Afterwards, when we satisfied with the changes then we run:

 grails dbm-gorm-diff --add filename.groovy

in dev environment for capturing the changes. This generates migration scripts added in the changeset log(for more, see post ‘Grails Database Migration Plugin‘) and that is run next time app starts in environment other than dbgorm.

How To Know What’s default?

You may wonder what is the default settings if none is specified for your custom environment. For example, if you have custom environment but you don’t specify Data Source for it, what Data Source is it going to use?

Grails configuration files – DataSurce, Config, BuildConfig,etc are using Groovy utility – ConfigSlurper. The ConfigSlurper “allows a default setting to exist in the property file that can be superceded by a setting in the appropriate environments closure”(from ConfigSlurper documentation). In another words, following example of Data Source, there is the default property – ‘datasource’  following with declarations of ‘datasource’ for each environment that supercedes the default one.

dataSource {

// environment specific settings
environments {

	development {
		dataSource {

Useful Links

Shelving Uncommitted Changes in Mercurial

There may be a time when your realize that the changes you just made (uncommitted changes), need to be on separate branch. That happend to me in my new workplace few days ago. My new workplace use branching extensively to ensure code review process is taking place. Every feature or defect is done on separate branch. After work completed, the developer initiates a pull request via bitBucket so that there is another developer who approves the changes before merged into main trunk. So, for my first changes i forgot and i completed my changes on the main trunk just to later learn it has to be on a separate branch.  The Shelving feature in Mercurial came to rescue me. I was surprised to learn that a task that can become time consuming and challenging was accomplished so easy thanks to shelving feature. This post will cover how to install Shelve extension and then use this feature to move some uncommitted changes into a different branch.

Install Extension – hgshelve

You may not need this because some IDE like IntelliJ comes with the extention – hgshelve preinstalled and configured, however, if you are like me who likes command line mercurial hg then we have to install.

1. Clone the extension – hgshelve

>hg clone ssh://

2. Configure the extension – hgshelve

To do so, update your global mercurial config .hgrc file section ‘extensions’ in your home directory as follows:


This completes the installation and configuration of the extension – hgshelve. Now, you are able to take advantage of the power that shelving brings to you

Using Shelve

1. Shelve Uncommitted Changes

First, i shelve my uncommitted changes while on the main branch by executing command:

>hg shelve --name DE4653_DE3847_Shelved

Once started, mercurial will be asking to confirm each change that adding to shelve something like:

>$ hg shelve my_dir/my_file.ext
>examine changes to 'my_dir/my_file.ext'? [Ynsfdaq?]

The options – [Ynsfdaq?] stand for:

y - shelve this change
n - skip this change

s - skip remaining changes to this file
f - shelve remaining changes to this file

d - done, skip remaining changes and files
a - shelve all changes to all remaining files
q - quit, shelveing no changes

? - display help</pre>

If you like to see every change added to this shelve then select ‘Y’ or ‘a’ for shelving all of the changes without confirming each

This shelves the changes and i am safe to change branches

Verify Shelved Changes

1. To verify your changes has been shelved, run:

>hg shelve --list

This would list all of the shelved changes. In our case, there is only one

2. Another way to ensure changes has been shelved is to run ‘hg status’. If changes shelved, this should return nothing

3. If you doing for the first time and you are afraid of losing, then look at .hg/shelve directory in application dir (precisely, mercurial working directory). There you should find text files containing the changes per each shelving. You can back those up. You can email to your friend developer to finish, perhaps,  in situations where you have shelved uncommitted changes and you are unable to complete because you going out town. Or email to yourself to finish at home. By putting these text files in your home computer .hg/shelve folder, makes those available to unshelve and finish

Unshelve Changes

2. Create New Branch. To create new branch, run command:

>hg branch DE4653_DE3847

This not only creates new branch, it also automatically puts you in the new branch. To verify what branch you are at any time, run ‘hg branch’

3. Unshelve Changes

When ready, to unshelve your changes, run:

>hg unshelve --name DE4653_DE3847_Shelved

This takes our uncomitted changes shelved previously and adds to our working directory. To verify you can run ‘hg st’ or ‘hg shelve –list’. The latter will return nothing in our case because after unshelving the shelvDE4653_DE3847_Shelved is destroyed.

Now, we are able to commit the new changes in the separate appropriate branch, so we can create pull request , thus, accomplishing our goal.

4. Nudge Changes

Not related  shelving, however part of the exercise – putting your changes on separate branch. The last step after unshelleving the changes and committing, perhaps, is to push your branch with the unshelled changes into the central repo. This allows others to code review and approve pull request(i.e. bitbucket)

The general ‘hg push’ method will push all branches in your local repo that you may not want. You only need to push your new branch. For that purpose, use ‘hg nudge’ that is a push command but only for the branch you are on at the given moment. Before that works you need to update .hgrc – mercurial global configuration in home directory as follows:

nudge = push --rev .

Afterwards, make sure you are in the proper branch and call method:

>hg nudge

This pushes just unshelved changes as separate branch into centra repo

Bug – Added Files Unable Shelve

It turns out that for newest current version of the ‘hgshelve’ extension there is bug which prevents to shelve any files that has been added to working directory and has status ‘A’.

The best solution i found is to use a different mercurial extension – hgattic that contains the shelve feature but does not have the bug. Make sure you grab it from the repo version that works with the newest version of mercurial

Everything applies the same way except the commands are named slight different. It also add some extra goodies about all of which you can learn from hgattic wiki

Useful Links:

Someone Has Already Registered That SSH key

You may have been using SSH key to login, retrieve code on for some account. Perhaps, then you wished to do the same for another account but when adding your public ssh key for the another account you got the error – Someone has already registered that SSH key. This post is how to automatically push, pull and connect to any of Repo’s from your machine on any of the accounts hosted by

We found our solution to this limitation in mercurial extension – mercurial_keyring. In this post we will cover how to install the extensions and then how to configure mercurial to remember credentials for different repos on different accounts in

About The Extension – mercurial_keyring

Here description from

mercurial_keyring is a Mercurial extension used to securely save HTTP and SMTP authentication passwords in password databases (Gnome Keyring, KDE KWallet, OSXKeyChain, specific solutions for Win32 and command line). This extension uses and wraps services of thekeyring library.

The extension prompts for the password on the first pull/push (in case of HTTP) or first email (in case of SMTP), just like it is done by default, but saves the password. On successive runs it checks for the username in .hg/hgrc, then for suitable password in the password database, and uses those credentials (if found).

In case password turns out to be incorrect (either because it was invalid, or because it was changed on the server) or missing it just prompts the user again.

Passwords are identified by the combination of username and remote address, so they can be reused between repositories if they access the same remote repository (or the same SMTP server).

Installing The Extensions – mercurial_keyring

1. Clone The Project

>hg clone

2. Configure Extension. To do so update .hgrc config file ‘extensions’ section in your home directory(the global mercurial config) as following:

mercurial_keyring = /path_To_dir_cloned_step_1/

This will enable the extension – mercurial_keyring for mercurial hg

Configuring For Multiple BitBucket Accounts

In the global mercurial config (.hgrc in home directory) you can config each Repo on different BitBucket accounts as follows:

 minnehaha.prefix =
 minnehaha.username = minnehahalofts
 minnehaha.schemes = http https
 kapasoft.prefix =
 kapasoft.username = kapasoft
 kapasoft.shcemes = http https

In above, we created two aliases – minnehaha and kapasoft each referencing two different BitBucket accounts. The good thing this works for clone  command as well, so now i can quickly clone three different repos on two different BitBucket accounts:

>hg clone
http authorization required
realm: HTTP
user: minnehahalofts
>hg clone
http authorization required
 realm: HTTP
 user: kapasoft
>hg clone
http authorization required
 realm: HTTP
 user: kapasoft

Each time it will prompt for password for the appropriate username. It is only for the first time since we connecting for the first time. Afterwards, the extension save the passwords making it very convenient to push, pull or any other way connect to the Repos


1. ‘abort: No module named keyring!’

Issue: keyring library missing on your machine. To install, run ‘easy_install keyring’ from command line


Useful Links

Domain Object Many-To-Many Relationship in Grails GORM and SQL Relational DB

This is following post series about ‘Domain Object Relationships in Grails GORM and SQL Relational Databases‘ where we look at the details how the relationships build in GORM with how physically structrured in DB while cascading and direction addressed.

In this post, i have a sample of Many-To-Many relationship between entities ‘RentalUnit’ and ‘Review’. A particular RentalUnit may have many Reviews. One guest my have stayed in multiple RentalUnits, so a review written by this guest is linked to many RentalUnits

In our example, there is ‘Save, Update and Delete’ cascading from RentalUnit to Review and ‘none’ cascading from Review to RentalUnit

Class Diagram

From class diagram you can see there is ‘has to’ relationship between RentalUnit and Review entities

Code Snippet

In the above code snippet, the red colored code sets the relationship Many-To-Many. The green colored code sets the cascading

Database Structure

From the ER Diagram above, we see that GORM creates a separated table – RentalUnit_Review that is a child to parent ‘RentalUnit’ and another parent ‘Review’ tables. The IDs of entities ‘Review’ and ‘RentalUnit’ combines the primary key for the new table


Our conclusion that GORM creates additional table every single time there are Many-To-Many or One-To-Many relationship.


1. addTo* And removeTo* methods.

Whenever there are Many-To-Many or One-To-Many relationship, GORM provides you with methods – addTo* and removeTo*. These methods does important part – it sets the relationships in both ways. Consider the following:

def review2 = new Review(rentalUnits: [rentalUnit], ...., isApproved: false).save(flush: true) 

In the above code we initialize object ‘review2’ that points to object ‘rentalUnit’ and ‘rentalUnit2’, however.  While object ‘rentalUnit2’ is pointing back to object ‘review2’, the object ‘rentalUnit’ does not. This is because adding object ‘rentalUnit2’ we used method ‘addTo*’ where as for object ‘rentalUnit’ we did not. As result we have incomplete session.

2. “deleted object would be re-saved by cascade”

Entities like ‘Review’ that have references from multiple ‘RentalUnit’ objects while no cascading applied, will cause errors if not handled with care. For example, if you have to delete a review object R1 that is contained by two rentalUnit objects A and B, then you have to first delete the references from A->R1 and B->R1 before deleting the review – R1 itself. Here is example

def r = []
 r += review1.rentalUnits
 r.each {RentalUnit renUnit -&gt;
 review1.delete(flush: true)

In another words, we are doing cascading manually and should not be needed if we have specified cascading from Review to RentalUnit.

If we don’t handle these RentalUnit references as shown above before deleting the review R1, we will receive an error – deleted object would be re-saved by cascade – and the review R1 is not removed. This because GORM deletes the review R1 in session and before flushing, it detects that there exists other references to this review R1, thus , it cannot be remove, instead restores (re-saved) the review R1 back in session.

3. Cascading gets tricky in Many-To-Many relationship

Consider a RentalUnits U1 and U2 with reviews R1 and R2 with associations as following:

U1 -> R1,R2
U2 ->R2

Now, if you wish to remove rentalUnit U1, it will fail even with cascading on ‘delete’ present from RentalUnit->Review as described above. It fails because GORM is executing cascading on all children of rentalUnit that includes all reviews, so it attempts to delete the review R2, however. The review R2 is also referenced by another rentalUnit U2 resulting GORM unable to remove R2, and also U1 as the result.

Grails Database Migration Plugin

Grails Database Migration Plugin is very useful for managing SQL database for your grails application. The most useful aspect of it is that it can generate SQL  scripts from current GORM. In my previous job, we used MyBatis to manage Database, however. With MyBatis we had to create SQL scripts manually and to make it according to GORM was very time consuming, error prone and not efficient process.

In this space, i will cover the installation, setup and everyday use of Grails Database Migration Plugin.

Pre-Condition: SQL Db setup and installed

Install & Setup DataBase Migration Plugin

1. Installation.

To install Grails Database Migration Plugin, run the following command:

grails install-plugin database-migration

Add the line ‘runtime “:database-migration:1.1″‘ in the ‘plugin’ code section in grails-app/conf/BuildConfig.groovy just like this:

To verify, open Dependency report (‘grails open dep-report’) and see if there DB migration plugin listed just like this:

2. Generate Initial Script

Next, we are going to generate intial migration script:

grails dbm-generate-changelog changelog.groovy

This will generate ‘changelog.groovy’ containing SQL scripts to create current GORM state and save it in ‘grails-app/migrations’ folder

Note:You may choose to run ‘grails dbm-changelog-sync’ that will record that the changes have already been applied if you don’t wish to dump tables and test this script.

3. Update Datasource

Last, we need to change the app DataSource to inform GORM that it does not need to ‘create’, ‘update’, or do anything with the Database at the application startup since we are going to use DB migration plugin for ‘create’, ‘update’ the app database. So, update variable ‘dbCreate’ in ‘grails-app/conf/DataSource.groovy’ to nothing just like the following:

Using Database Migration Plugin

Test Run

At any given time, to test Database migration plugin and scripts do the following:

1. Drop all tables in the Database.

You can do that manually or utilize Migration plugin by running the following command

grails dbm-rollback-to-date  1900-01-01

2. Roll back the record. ONLY If you drop tables manually you need to update migration record log, so that it appears no migrations scripts have run so far. To do that run the following command:

grails dbm-drop-all

If you have run ‘dbm-rollback-to-date’ as specified above, it would have done this step for you already

3. Run the Scripts and Check Database

To run all of the migration scripts call the following command:

grails dbm-update

This will run any script that is registered in the migration log as hasn’t been run. In our case, we drop all the records, so it will run all migration scripts

Note: At any time, you can check the migration plugin status of what migrations scripts have and have not been run by calling ‘grails dbm-status’. It will display only scripts that haven’t been run

Generating Migrations Scripts

After making changes in GORM all tested then run the following command:

grails dbm-gorm-diff --add filename.groovy

This will generation and register the script as well as include for the filename in the main changelog for you. You are done. Other developer will get your new script and run ‘dbm-update’ to update their database accordingly

Other Useful Migration Commands

1. dbm-clear-checksum.  You can change any Migrations scripts manually but if you do, then don’t forget to run ‘grails dbm-clear-checksum’ afterwards to make the changes valid

2.  dbm-gorm-diff without ‘–add’. If you run only ‘grails dbm-gorm-diff’ without the ‘–add’ tag, it will display what are the current difference between GORM and your database

Run Migration Scripts at Start

Its all good running ‘dbm-update’ every single time you receive new migration script in your workspace , however. You are able to make it automatic at next time your grails application start by adding  the following in the conf/Config.groovy file:

grails.plugin.databasemigration.updateOnStart = true
grails.plugin.databasemigration.updateOnStartFileNames = ["changelog.groovy"]
grails.plugin.databasemigration.changelogLocation = 'grails-app/migrations'

This will detect what changes hasn’t been run from the change log and run appropriate migration scripts all automatically at grails app startup.

Running the migration script also at the time you making changes in GORM (domain classes) q

Issues Encountered

1. ‘Change Set changelog.groovy::[…] (generated) failed.  Error: Error executing SQL ALTER TABLE[…]

We got this error after cloning the project and running the migrations scripts.

It turned out that this error was caused because only on Windows when you generate initial migration script it includes references to specific database name.

To solve it, we manually deleted these references in the initial migration script. Afterwards don’t forget to run ‘dbm-clear-checksum’ to make changes valid

2. ‘Error: Error executing SQL CREATE INDEX `[…]: Incorrect index name’

This error seems to be specific to Database installation,setup or version. Either way, the solution was to manually updated migration script so that this index is created after the foreign key is added

As you can see it is the same index name as marked in above screenshot. So moving the changeSet 5 in front of the changeSet 4 and then updating the numbering(red color) solved the problem for us

Afterwards, don’t forget to run ‘dbm-clear-checksum’ to make the changes valid

3. Grails Migration plugin fails silently.

Most of the time this happens when there is syntax error in one of the migration scripts. I find myself often times deleting a migrations script and then forgetting to update the initial changelog. groovy. At the bottom, the changelog.groovy contains ‘include’ for each migrations script. If you delete some migration script but fail to update (remove the includes) the changelog.groovy, then migration plugin fails silently for ‘update’, ‘status’ and other cmd.

Debugging Grails Database Migration plugin

1. Enable logging. It may help troubleshoot your issue if you enable the Database Migration Plugin by adding following line in Config.groovy:

log4j = {
           debug 'grails.plugin.databasemigration', 'liquibase'

Useful Sources:


Working with the Grails Database Migration Plugin

Database Migration Plugin

IntelliJ Shortcuts and Configurations

In this space, all of the intelliJ shortcuts and configurations that we find more practical then others are listed


1. CTRL+J – Opens up Live Templates. Used for Spock individual test creation in quick way


2. Optimize Import Statements. It removes unused imports and sorts in alphabetical order. To use:

Command + Alt + O


1. Enable line numbers show at all times. (Settings->Editor->Appearance->Show Line Numbers)

From ‘How Can i Permanently Have Line Numbers in IntellJ’ 

2. Code Formatting For Labels
To see labels(when,then,setup,etc) formated on left (good for GEB Tests):
File->Other Settings->Template Settings…->Code Style->Groovy-> Set “label indent” to 2 and checking the “Absolute label indent” checkbox.