terça-feira, 18 de outubro de 2016

Managing your Database with Liquibase and Gradle

One of the major system development problems has always been how and when we will update the database.

When happen some database change in the development environment, always some questions appear:
  • Scripts for DB changes were created?
  • Where to save the DB changes?
  • When should we apply these changes?
  • These changes have already been implemented?
  • How do we track and manage database changes?
  • Who did these changes?

Liquibase is the library that can help address these issues.

Liquibase is an independent library open source database used to track, manage, and apply changes to the database.

Liquibase works better because it understands what the changes are. For example, a database comparison program would simply see the “person” table on integration has a “firstname” and a “lastname” column, but on live, the “person” table has a “name” column. It would report that you need to drop the “name” column and add a “firstname” and a “lastname” column. While this would leave you with the correct schema, you would lose everyone’s name in the process. With Liquibase, you would have a changeset that says “rename ‘name’ to ‘lastname’ and add a ‘firstname’ column” or, even better, “split the name column on a space and place the values in new ‘firstname’ and ‘lastname’ columns, then drop the ‘name’ column.” Knowing why they are different allows changes to production databases without the fear of losing valuable data.

In this post I will show how you can use the powerful tool Liquibase together with Gradle to automate these tasks, from there will be easy to put Liquibase to work with your continuos integration tools.

Some important concepts:

Changelog file

  • Is the file that contains references of all scripts that should be applied to the database in any environment.

ChangeSet Files:

  • Are all the files recorded in a Changelog
  • Changesets files can be written primarily in XML, YAML, JSON, SQL
    •  I chose for this example SQL.

Some Advices:

  • IDs cannot be repeated, otherwise they will not run
  • Scripts should be smalls
  • Should be added script Rollback whenever possible
  • Must be added new scripts on the changelog.xml
  • Everything that was executed is registered on table DATABASECHANGELOG

Sample:

changelog.xml


001.SAMPLE.sql


002.SAMPLE.sql

build.gradle

I created tasks for every environment I have and where liquibase should run the script.

With Gradle I need only choose a task as it is below:
  • To execute:
    • gradle task dev update
    • gradle task qa update
    • gradle task prod update

After that you can check in your database, that these scripts 001 and 002 were applied.

On the table DATABASECHANGELOG is possible check some records like these:



This sample above complete in my GitHub 

References:


Nenhum comentário:

Postar um comentário

Observação: somente um membro deste blog pode postar um comentário.