Liquibase snapshotReference with diff and diffChangelog commands

The diff and diffChangelog commands provided by Liquibase are used to inspect the difference between the source and target database. the snapshotReference command generates the state of the source database in a file format, this file can also be used with diff and diffChangelog instead of the actual target database.

execute the below script into the database

create database appleDbSource;
use appleDbSource;
create table apple (apple_id bigint not null AUTO_INCREMENT , apple_name varchar(255), available CHAR(1), current_date_time datetime default now(), primary key (apple_id), CONSTRAINT uqniue_apple_name UNIQUE (apple_name)) engine=InnoDB;
insert into  apple (apple_name, available, current_date_time) values ("Macintosh", 'Y',  now());
insert into  apple (apple_name, available, current_date_time) values ("Fuji", 'Y',  now());
commit;
create database appleDbTarget;
commit;

liquibase.properties (update changeLog File file format with SQL, XML, YAML, JSON as per changelog.mysql.)

liquibase.command.referenceUrl =jdbc:mysql://localhost:3306/appleDbSource?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true
liquibase.command.referenceUsername= root
liquibase.command.referencePassword= rootroot
snapshotFormat=json
outputFile=SourceDbSnapshot.json

To create a snapshot of the current database, execute the command

liquibase snapshotReference

it will create a file named SourceDbSnapshot.json

Compare SnapshotReference with another Database

The snapshot command saves the current state of the source database in JSON file format. Since this JSON file contains the exact state of the database, it can be used to compare the state with another database via diff or diffChangelog command.

To compare the generated SourceDbSnapshot.json file with the actual database, update the liquibase.propertie

# target db
liquibase.command.url=jdbc:mysql://localhost:3306/appleDbTarget?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true

#  source db

liquibase.command.referenceUrl = offline:mysql?snapshot=SourceDbSnapshot.json
liquibase.command.referenceUsername= root
liquibase.command.referencePassword= rootroot

To generate the difference in missing objects between the source and target databases, run the command

liquibase diff

To generate the ChangeLog of missing objects between the source and target databases, run the command

liquibase diffChangeLog

follow us on