Wednesday, November 6, 2024

How Do I initialize/deploy data to production using Liquibase?

 I encountered a situation recently where I added a field to a table, and needed to update data due to that field.

I realized manually doing this when I deployed was obviously a bad idea, so I did some research into how liquibase works, and my solution was pretty easy using this method 

But, I had some challenges

  1. How do I ensure that my script won't get overwritten when someone is working on a separate branch?
  2. How do I ensure that my script will only be run once and not multiple times?
Here is my solution:

We have a requirement that all branches be named after the support/dev ticket # you're working on.   So, for argument sake, let's pretend I'm working on Ticket 1234, and my branch is called Ticket_1234.

Our back-end liquibase changelogs are stored in GIT in CHANGELOGS\DB folder. 
There are 4 steps I did
  1. Created a folder within my CHANGELOGS\DB called SCRIPTS
  2. Added a line at the end of my controller.xml
    <include file="scripts.xml"/>
  3. To ensure uniqueness, our format for a script file is script_<ticket#>_<script#>.sql.  So in this example, my first script would be script_1234_1.sql.  If I made a second one, script_1234_2.sql, etc., and we save the script in the SCRIPTS directory
  4. Created a new file called scripts.xml.  We match the changeset ID # to the script #, so when liquibase runs it, it stores it in the DBCHANGELOG table, and this way, we won't encounter any duplications when deploying.  Sample File Below

    <?xml version="1.0" encoding="UTF-8"?>
    <databaseChangeLog
      xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
                          http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
     
      <changeSet author="scott" id="script_1234_1">
            <sqlFile dbms="!h2, oracle, mysql"
                encoding="UTF-8"
                endDelimiter="/"
                path="SCRIPTS/script_1234_1.sql"
                relativeToChangelogFile="true"
                splitStatements="true"
                stripComments="true"/>
      </changeSet>
    </databaseChangeLog>

Happy Coding!

No comments:

How Generative AI can save you time programming menial tasks

 To paraphrase the rock band Staind, It's been a while since I blogged.  And since every tech blog these days is talking about AI, I fig...