Custom Groovy Changes In Grails DbMigration (Part II)

In my previous post for Custom Groovy Changes In Grails DbMigration, you have seen various example to write custom changes for your migrations. Here are some more more cases with example: 

Case 1: Changing a field’s data type

databaseChangeLog = {

    changeSet(author: 'Vishesh', id: 'content.body-1') {
        comment { 'change type to text' }
        modifyDataType(tableName: 'content', columnName: 'body', newDataType: 'longtext')
        // or
        // modifyDataType(tableName: 'content', columnName: 'body', newDataType: 'text')
    }
}

Case 2: Custom Id generation to auto increment id generation.

By default grails adds a id field to domain class which is marked to auto increment. But grails also provide configuration to generate custom ids (see here). When changing the id generator from custom id generator to an auto increment field (default of grails), the migration plugin does not generate the changeset and it has to be manually added.

databaseChangeLog = {
    
    changeSet(author: "John", id: "dummy-10182013-1") {
        addAutoIncrement(columnName: "id", tableName: "expired_invite", columnDataType: "bigint")
    }
 
}

Case 3: Deleting records

   changeSet(author: "John", id: "content-plugin-upgrade-09-20-2013-1") {
       delete(tableName: "cc_content_menu_item", whereClause: "id < 7")
   }

Case 4: Adding unique constraint

   changeSet(author: "John", id: "10182013-1") {
       addUniqueConstraint(columnNames: "user_id", tableName: "user_profile")
   }

Case 5: Adding a foreign key

DbMigration generates both a changeset for adding a column and an index for a foreign key but MySql creates an index by default for a Foriegn Key. Which makes the second changeset generated by dbmigration for creating an index useless. You will have to remove the generated code which adds the index on foreign keys for the migration to run error free.

    changeSet(author: "Shashank (generated)", id: "1317282537891-3") {
        createIndex(indexName: "FK7268FEF5EE5762B4", tableName: "user_profile") {
            column(name: "user_id")
        }
    }
About CauseCode: We are a technology company specializing in Healthtech related Web and Mobile application development. We collaborate with passionate companies looking to change health and wellness tech for good. If you are a startup, enterprise or generally interested in digital health, we would love to hear from you! Let's connect at bootstrap@causecode.com

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY UPDATED!

Do you want to get articles like these in your inbox?

Email *

Interested groups *
Healthtech
Business
Technical articles

Archives