Skip to content

Add an IncludeAll Comparator

Prerequisites

Implementing Liquibase extensions requires an understanding of Java. You will be creating classes, overriding methods, and working with inheritance hierarchies.

Project Setup

If you have not already created a repository to hold your code, see Your First Extension in the Getting Started guide.

Overview

By default, Liquibase's [includeAll] tag will sort files in alphanumeric order. If you would like a different ordering, you can specify the resourceComparator attribute pointing to a class that implements the java.util.Comparator interface.

Your compare method will be passed the path to the files to sort.

Note

If you would like to control the filtering of files included, see Add an IncludeAll Filter

Example

Suppose your changelog files are named like 1-create-table.sql, 23-add-age.sql, 1037-rest-age.sql where there is always a number before a hyphen, but the number is not zero-padded and so does not work well with the default alphanumeric sorting.

If you create a class like this:

package com.example.includeall;

import java.util.Comparator;

public class NumberComparator implements Comparator<String> {

    @Override
    public int compare(String path1, String path2) {
        Integer path1Number = extractFileNumber(path1);
        Integer path2Number = extractFileNumber(path2);

        return path1Number.compareTo(path2Number);
    }

    private Integer extractFileNumber(String path1) {
        return Integer.valueOf(path1.replaceFirst("-.*", ""));
    }
}

and add it to your Liquibase classpath, you can reference it in the resourceComparator attribute on your includeAll like this:

<?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">
    <includeAll path="com/example/changelogs/" resourceComparator="com.example.includeall.NumberComparator"/>
</databaseChangeLog>

Tip

Unlike other extensions, there is no need to register your class in the META-INF/services directory.