In this post, we take a look how to get your database up and running in your new Play framework-based application while also managing schema changes.
Once you start a Play prototype application, one of the priorities is to initialize your database and also manage database schema changes.
Play provides us with evolutions. By utilizing evolutions, we are able to create our database and manage any futures changes to the schema.
To get started, we need to add the JDBC dependency and the evolutions dependency.
Then we shall use a simple H2 database persisted on a disk as our Play application's default database. We'll edit the conf/application.conf file and add the following lines.
Pay extra attention that our database location is the tmp directory, thus all changes shall be deleted once we reboot our workstation.
Our first script '1.sql', shall create the users table.
As we can see, we have ups and downs. What do they stand for? As you might have guessed, ups describe the transformations while downs describe how to revert them. So the next question would be how this functionality comes into use.
Suppose you have two developers working on 2.sql. Locally, they have successfully migrated their database. Once they are done, however, the merge result is far different than the file they executed on their database.
Evolutions detect whether the file is different and reverts the old revision by applying downs and then applying the up-to-date revision.
Now we are all set to run our application.
Once we navigate to localhost:9000, we shall be presented with a screen that forces us to run the evolutions detected.
Let us go one step further and see what has been done to our database schema. We can easily explore an H2 database using dbeaver or your IDE. Upon issuing the show tables command, the results contain one extra table.
The PLAY_EVOLUTIONS table keeps track of our changes.
Id is the number of the evolution script that we created. The apply and revert fields are the ups and downs of the SQL statements we created previously.
The hash field is used in order to detect changes to our file. In case of an evolution that has a different hash from the one applied, the previous evolution is reverted and applies the new script.
For example, let's enhance our previous script and add one more field: username.
Once we start our application, we will be presented with a screen that forces us to issue an evolution for our different revision. If we hit apply, the users table shall contain the username field.
So the process of a new revision is pretty straightforward. The hash from the new 1.sql file is extracted. Then, a query checks whether the 1.sql file has already been applied. If it has been applied, a check is issued in case the hashes are the same. If they are not, then the downs script from the current database entry is executed. Once that's finished, the new script is applied.