Search code examples
database-migrationliquibaseliquibase-hibernate

Database Migration from one version to another using Liquibase


I rolled out the first version of application and a Postgres server is set up for the same.

I am planning to roll out my second version of my application which has structural changes in my tables.

For example : I had App table with a column called version , now I have another column called releaseVersion and I have to apply alter to add this column.In such a case, how can I use liquibase to generate/apply the migration script?

Is liquibase capable of such migration.?

In short, for my first version I created my table using the DDL

CREATE TABLE App (version varchar); // I manually generated this using liquibase offline mode and my metadata.

Now I have my db with above column.

And I need to generate the alter to add column using liquibase. Something like this

ALTER TABLE App ADD releaseVersion varchar;

Is it possible using Liquibase as it is the industry standard for migration.

I used liquibase:diff, but it is only capable of creating the difference changelog from two databases (target db and base db). In my case, there is only a production database.


Solution

  • Yes, it's possible.

    Create a changeSet like:

    <changeSet author="foo" id="bar">
        <preConditions onFail="MARK_RAN">
            <and>
                <columnExists tableName="App" columnName="version"/>
                <not>
                    <columnExists tableName="App" columnName="releaseVersion"/>
                </not>
            </and>
        </preConditions>
        <renameColumn tableName="App" oldColumnName="version" newColumnName="releaseVersion" columnDataType="varchar(100)"/>
    </changeSet>
    

    and apply it, using liquibase update command.

    If you need to just add a new column, then your changeSet will look like this:

    <changeSet id="foo" author="bar">
        <preConditions onFail="MARK_RAN">
            <not>
                <columnExists tableName="App" columnName="releaseVersion"/>
            </not>
        </preConditions>
        <addColumn tableName="App">
            <column name="releaseVersion" type="varchar(100)"/>
        </addColumn>
    </changeSet>