Play Framework (3) – evolutions

First if all, I need to explain why I use evolutions in Play Framework and why I write down this post. The reason is that when you design your database schema at the beginning of the project, you can’t expect everything. Your table schema might be needed to add new field, or change its length or other unpredictable operations. Of course, you can go to DB to change it directly, but in different env which is already deployed your project, how can they do? Change all of table schema by hand? Is it too stupid? In fact, before I really understand evolutions in Play Framework, I do it by hand :(. No worry, evolutions will remove all of the pains which I experienced before.

When you want to update your database design, you just need to write codes under evolutions folder and then, when you go to deploy your code to some env, it will automatically help you update the changes on database. Is it magic?

Let’s see how to really use evolutions.

1. Create evolutions scripts

mkdir conf/evolutions

Your scripts will be under this folder, like 1.sql, 2.sql, 3.sql, etc

The configuration of evolution is under application.conf. Default setting:

evolutionplugin=enable

Of course, you can disable it by setting its value as disabled.

2. Syntax

Each script contains two parts: one is Ups that describe the required transformations, the other is Downs which describe how to revert them.

# Users schema
# --- !Ups
CREATE TABLE User (
  id bigint(20) NOT NULL AUTO_INCREMENT,
  email varchar(255) NOT NULL,
  password varchar(255) NOT NULL,
  fullname varchar(255) NOT NULL,
  isAdmin boolean NOT NULL,
  PRIMARY KEY (id)
);
# --- !Downs
DROP TABLE User;

Play splits your .sql files into a series of semicolon-delimited statement before executing them one-by-one against database. So if you need to use a semicolon within a statement, escape it by enttering :: instead of ;.

3. Deployment

If you want to apply UP evolution automatically, you should set the system property

-DapplyEvolutions.<database>=true

Or set

applyEvolutions.<database>=true

in application.conf.

If you want to run UP and DOWN evolutions automatically, you should set the system property

-DapplyDownEvolutions.<database>=true

It is not recommended to have this setting in application.conf.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s