SlideShare a Scribd company logo
Successful DB migrations
with Liquibase
By Illia Seleznov
Who am I?
Lead Software Engineer at EPAM Systems
More than 7 years in commercial java development
2 project from scratch to production
Speaker experience at Epam events, Logeek Night,
UADEVCLUB.
DB management
Scripts structure
Migration process
Database migration tools
Liquibase is open sources
Founded in 2006 year
Author is Nathan Voxland
Github: https://github.com/liquibase
Liquibase script formats
XML
JSON
YAML
SQL
ChangeSet
<changeSet id="1" author="illia_seleznov">
<createTable tableName="person">
<column name="id" type="int" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="state" type="char(2)"/>
</createTable>
</changeSet>
Bundled Changes
ADD AUTO INCREMENT
ADD COLUMN
ADD DEFAULT VALUE
ADD FOREIGN KEY CONSTRAINT
ADD LOOKUP TABLE
ADD NOT NULL CONSTRAINT
ADD PRIMARY KEY
ADD UNIQUE CONSTRAINT
ALTER SEQUENCE
CREATE INDEX
CREATE PROCEDURE
CREATE SEQUENCE
CREATE TABLE
CREATE VIEW
CUSTOM CHANGE
DELETE
DROP ALL FOREIGN KEY
CONSTRAINTS
DROP COLUMN
DROP DEFAULT VALUE
DROP FOREIGN KEY
CONSTRAINT
DROP INDEX
DROP NOT NULL CONSTRAINT
DROP PRIMARY KEY
DROP PROCEDURE
DROP SEQUENCE
DROP TABLE
DROP UNIQUE CONSTRAINT
DROP VIEW
EMPTY
EXECUTE COMMAND
INSERT
LOAD DATA
LOAD UPDATE DATA
MERGE COLUMNS
MODIFY DATA TYPE
RENAME COLUMN
RENAME TABLE
RENAME VIEW
SQL
SQL FILE
STOP
TAG DATABASE
UPDATE
Changesets
Changelog
Example
<databaseChangeLog ...>
<include file="create_customer_table.xml" relativeToChangelogFile="true"/>
<include file="add_default_customer.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
File structure
/db-migrations
/sprint-1
/2017-03-02--01-initial-schema-import.xml
/2017-03-04--01-notifications.xml
/changelog-v.1.0-cumulative.xml
/sprint-2
...
/changelog-v.2.0-cumulative.xml
/changelog.xml
Liquibase is just a jar file
java -jar
liquibase.jar [options] [command] [command parameters]
Example
java -jar liquibase.jar
--driver=oracle.jdbc.OracleDriver
--classpath=pathtoclasses:jdbcdriver.jar
--changeLogFile=com/example/db.changelog.xml
--url="jdbc:oracle:thin:@localhost:1521:oracle"
--username=scott
--password=tiger
update
Liquibase.properties file
1.Create liquibase.properties file near liquibase.jar
2.Add all connection data to this file
driver: org.mariadb.jdbc.Driver
url: jdbc:mariadb://localhost:3306/liquibase_demo
username: liquibase
password: qwerty
classpath: /home/illcko/liquibase/dbdrivers/mariadb-java-client-1.4.6.jar
Easy command line
java -jar liquibase.jar --
changeLogFile=changelogs/xml/master.xml //options
dropAll update //command
 Successful DB migrations with Liquibase
Liquibase system tables
SQL also here
SQL as changelog file
Include sql file
SQL tag in changeset
SQL as changelog file
--liquibase formatted sql
--changeset seleznov:1
create table test1 (
id int primary key,
name varchar(255)
);
--changeset seleznov:3 dbms:oracle
create sequence seq_test;
SQL as file
<changeSet id="do_smth" author="Illia_Seleznov">
<sqlFile encoding="utf8"
endDelimiter="/"
path="sql/do_smth.sql"
relativeToChangelogFile="true"
splitStatements="true"
stripComments="true"/>
</changeSet>
SQL as part of changeset
<changeSet id="drop_storage_with_index_data" author="Illia_Seleznov">
<sql splitStatements="false">
<![CDATA[
DECLARE
filter_count number;
BEGIN
...
END;
]]>
</sql>
</changeSet>
Changeset attributes
id
author
runAlways
runOnChange
context
failOnError
Contexts
context=”!test”
context=”v1.0 or map”
context=”!qa and !master”
“test, qa” is the same as “test OR qa”
“test, qa and master” is the same as “(test) OR (qa and
Sub-tags
comments
preConditions
validCheckSum(not recommended)
rollback
Preconditions
<changeSet id="1" author="bob">
<preConditions onError="MARK_RAN">
<tableExists tableName="angry_devops"/>
</preConditions>
<comment>Comments should go after preCondition</comment>
<createTable tableName="angry_devops">
<column name="angry" type="int"/>
</createTable>
</changeSet>
AND/OR/NOT Logic
<preConditions>
<or>
<and>
<dbms type="oracle" />
<runningAs username="SYSTEM" />
</and>
<and>
<dbms type="mssql" />
<runningAs username="sa" />
</and>
</or>
</preConditions>
Available Preconditions
<dbms>
<runningAs>
<changeSetExecuted>
<columnExists>
<tableExists>
<viewExists>
<foreignKeyConstraintExists>
<indexExists>
<sequenceExists>
<primaryKeyExists>
<sqlCheck>
<changeLogPropertyDefined>
<customPrecondition>
Update commands
update
updateCount <value>
updateSQL
updateCountSQL <value>
Diff commands
diff [diff parameters]
diffChangeLog [diff parameters]
Exclude from diff
● Non-foreign key constraints (check, etc)
● Stored Procedures
● Data type length
Documentation commands
dbDoc <outputDirectory> - generates Javadoc-like
documentation based on current database and change log.
java -jar liquibase.jar --changeLogFile=changelogs/xml/master.xml dbDoc ../doc
Maintenance commands
tag <tag>
tagExists <tag>
status
validate
changelogSync
changelogSyncSQL
markNextChangeSetRan
listLocks
releaseLocks
dropAll
clearCheckSums
generateChangeLog
Rollback commands
rollback <tag>
rollbackToDate <date/time>
rollbackCount <value>
rollbackSQL <tag>
rollbackToDateSQL <date/time>
rollbackCountSQL <value>
futureRollbackSQL
updateTestingRollback
RollBack
<changeset id="init-1" author="illia_seleznov">
<insert tablename="Person">
<column name="name" value="John Doe">
</column>
</insert>
<rollback>
DELETE FROM Person WHERE name LIKE 'John Doe';
</rollback>
</changeset>
Liquibase maven plugin
<plugin>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-maven-plugin</artifactId>
<version>3.0.5</version>
<configuration>
<propertyFile>src/main/resources/liquibase/liquibase.properties</propertyFile>
</configuration>
<executions>
<execution>
<phase>process-resources</phase>
<goals>
<goal>update</goal>
</goals>
</execution>
</executions>
</plugin>
Execute maven liquibase command
mvn liquibase:command
profile with liquibase plugin
Liquibase with Spring-boot
Add liquibase dependency to pom
Add master changelog location to properties
liquibase.change-log=classpath:db-migration/master.xml
No magic, just bean!
@Bean
public SpringLiquibase liquibase() {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDropFirst(true);
liquibase.setChangeLog(changeLog);
liquibase.setDataSource(dataSource);
liquibase.setContexts("test");
return liquibase;
}
 Successful DB migrations with Liquibase
Repository tests with liquibase
@Before
public void init() throws LiquibaseException, SQLException {
Database database = DatabaseFactory.getInstance()...
liquibase = new Liquibase(...);
liquibase.update("test");
}
@After
public void after() throws LiquibaseException {
liquibase.rollback(1, "test");
}
Insert by XML
<changeSet author="liquibase-docs" id="insert-example">
<insert tableName="person">
<column name="address" type="varchar(255)"/>
<column name="city" type="varchar(55)"/>
</insert>
</changeSet>
Load data
<loadData encoding="UTF-8" file="config/liquibase/users.csv"
separator=";" tableName="jhi_user">
<column name="activated" type="boolean"/>
</loadData>
id;login;PASSWORD;first_name;last_name;email;activated;lang_key;created_by
1;system;123;System;System;system@localhost;true;en;system
2;123;Anonymous;User;anonymous@localhost;true;en;system
Liquibase is not just for db
<changeSet id="1" author="bob">
<customChange class="com.seleznov.liquibase.example.CustomProcessor">
<param name="relativePath" value="example.json"/>
</customChange>
</changeSet>
Custom change interface
interface CustomTaskChange extends CustomChange {
String getConfirmationMessage();
void setUp() throws SetupException;
void setFileOpener(ResourceAccessor var1);
ValidationErrors validate(Database var1);
void execute(Database var1) throws CustomChangeException;
}
Replication
Replication file structure
/db-migrations
/sprint-1
/ddl
…
master_ddl.xml
/dml
…
master_dml.xml
/master-sprint-1.xml
/master.xml
Common changeset
<databaseChangeLog>
<changeSet id="1" author="bob">
<alterTable/>
<createIndex/>
<addPrimaryKey/>
</changeSet>
</databaseChangeLog>
Why does not devops sleep?
Solution
1.Comment problem changelog in master changelog
2.Create new changelog with several changesets for each
ddl action
3.Use precondition to each of them
Best practice
Don’t write changesets with a lot of ddl commands
Use precondition for every ddl change
The best of liquibase features
Automation of database migration
Synchronization scripts with db
Same scripts for different databases and contexts
Automation of tests dataset for DAO
Something to read
http://www.liquibase.org/
https://liquibase.jira.com/wiki/display/CONTRIB/LiquiBa
se+Extensions+Portal
https://www.youtube.com/watch?v=ByagQCx7m04&t=53
79s
Contacts
https://github.com/manbe/liquibase-demo
manbe@mail.com
https://www.facebook.com/IlliaSeleznov

More Related Content

PPTX
Liquibase
ODP
Liquibase & Flyway @ Baltic DevOps
PPTX
Database versioning with liquibase
PPTX
Continuous DB Changes Delivery With Liquibase
PPT
LiquiBase
PPTX
Liquibase
PDF
Simplify CDC Pipeline with Spark Streaming SQL and Delta Lake
PPTX
Survey of some free Tools to enhance your SQL Tuning and Performance Diagnost...
Liquibase
Liquibase & Flyway @ Baltic DevOps
Database versioning with liquibase
Continuous DB Changes Delivery With Liquibase
LiquiBase
Liquibase
Simplify CDC Pipeline with Spark Streaming SQL and Delta Lake
Survey of some free Tools to enhance your SQL Tuning and Performance Diagnost...

What's hot (20)

PPTX
Automate DBA Tasks With Ansible
PDF
Mastering PostgreSQL Administration
 
PPTX
Database Change Management as a Service
PDF
Modularized ETL Writing with Apache Spark
PDF
Oracle Enterprise Manager Cloud Control 13c for DBAs
PDF
Get to know PostgreSQL!
PDF
MySQL GTID Concepts, Implementation and troubleshooting
PPTX
Mongo DB 완벽가이드 - 4장 쿼리하기
PPTX
Maxscale 소개 1.1.1
PDF
監査ログをもっと身近に!〜統合監査のすすめ〜
PPTX
Liquibase case study
PPTX
Oracle Database: Checklist Connection Issues
ODP
OpenGurukul : Database : PostgreSQL
PPT
Bootstrap Components Quick Overview
PDF
Exadata master series_asm_2020
PDF
Introduction to elasticsearch
PDF
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
PDF
Accelerating Data Ingestion with Databricks Autoloader
PPTX
Tuning PostgreSQL for High Write Throughput
PDF
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Automate DBA Tasks With Ansible
Mastering PostgreSQL Administration
 
Database Change Management as a Service
Modularized ETL Writing with Apache Spark
Oracle Enterprise Manager Cloud Control 13c for DBAs
Get to know PostgreSQL!
MySQL GTID Concepts, Implementation and troubleshooting
Mongo DB 완벽가이드 - 4장 쿼리하기
Maxscale 소개 1.1.1
監査ログをもっと身近に!〜統合監査のすすめ〜
Liquibase case study
Oracle Database: Checklist Connection Issues
OpenGurukul : Database : PostgreSQL
Bootstrap Components Quick Overview
Exadata master series_asm_2020
Introduction to elasticsearch
Elasticsearch Tutorial | Getting Started with Elasticsearch | ELK Stack Train...
Accelerating Data Ingestion with Databricks Autoloader
Tuning PostgreSQL for High Write Throughput
Tanel Poder - Troubleshooting Complex Oracle Performance Issues - Part 2
Ad

Similar to Successful DB migrations with Liquibase (20)

PPTX
Liquibase for java developers
PPTX
Liquibase migration for data bases
PDF
Liquibase få kontroll på dina databasförändringar
PPTX
Schema migration in agile environmnets
PPTX
Liquibase Integration with MuleSoft
PPTX
Liquidating database frustrations with liquibase
PPTX
MuleSoft integration with Liquibase | Mysore MuleSoft Meetup #3
PDF
Leveraging Open Source for Database Development: Database Version Control wit...
PDF
Liquibase - Open Source version control for your database
PPTX
Li liq liqui liquibase
PPT
Liquibase – a time machine for your data
ODP
Handling Database Deployments
PPT
Evolutionary Database Design
PPTX
Database change management with Liquibase
KEY
Sane SQL Change Management with Sqitch
KEY
Agile Database Development with Liquibase
KEY
Database Refactoring With Liquibase
KEY
Simple SQL Change Management with Sqitch
PDF
Introduction To Liquibase
PPT
Refactoring database
Liquibase for java developers
Liquibase migration for data bases
Liquibase få kontroll på dina databasförändringar
Schema migration in agile environmnets
Liquibase Integration with MuleSoft
Liquidating database frustrations with liquibase
MuleSoft integration with Liquibase | Mysore MuleSoft Meetup #3
Leveraging Open Source for Database Development: Database Version Control wit...
Liquibase - Open Source version control for your database
Li liq liqui liquibase
Liquibase – a time machine for your data
Handling Database Deployments
Evolutionary Database Design
Database change management with Liquibase
Sane SQL Change Management with Sqitch
Agile Database Development with Liquibase
Database Refactoring With Liquibase
Simple SQL Change Management with Sqitch
Introduction To Liquibase
Refactoring database
Ad

Recently uploaded (20)

PPT
Mechanical Engineering MATERIALS Selection
PDF
composite construction of structures.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
Project quality management in manufacturing
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Mechanical Engineering MATERIALS Selection
composite construction of structures.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Geodesy 1.pptx...............................................
UNIT 4 Total Quality Management .pptx
Foundation to blockchain - A guide to Blockchain Tech
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Project quality management in manufacturing
bas. eng. economics group 4 presentation 1.pptx
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...

Successful DB migrations with Liquibase

Editor's Notes

  • #7: java -jar liquibase.jar --changeLogFile=changelogs/yaml/master.yaml update java -jar liquibase.jar --changeLogFile=changelogs/json/master.json update
  • #17: java -jar liquibase.jar --changeLogFile=changelogs/yaml/master.yaml update java -jar liquibase.jar --changeLogFile=changelogs/json/master.json update java -jar liquibase.jar --changeLogFile=changelogs/xml/master.xml update
  • #25: mvn liquibase:update -Dliquibase.contexts=test
  • #31: java -jar liquibase.jar --driver=org.mariadb.jdbc.Driver --url=jdbc:mariadb://localhost:3306/liquibase_2 --username=liquibase --referencePassword=qwerty diffChangeLog --referenceUrl=jdbc:mariadb://localhost:3306/liquibase_demo --referenceUsername=liquibase --referencePassword=qwerty > diff.sql
  • #33: java -jar liquibase.jar --changeLogFile=changelogs/xml/master.xml dbDoc ../doc
  • #35: java -jar liquibase.jar --changeLogFile=changelogs/xml/master.xml rollbackCount 1
  • #36: java -jar liquibase.jar --changeLogFile=changelogs/xml/master.xml rollbackCount 1