Liquibase® version 3.8.5 is now available! Get it for free.
2018 XML Announcement
News All Previous Posts >>

Subscribe for email updates

- and/or -

Preconditions

Preconditions can be attached to change logs or changesets to control the execution of an update based on the state of the database.

There are several reasons to use preconditions, including:

  • Document what assumptions the writers of the changelog had when creating it.
  • Enforce that those assumptions are not violated by users running the changelog.
  • Perform data checks before performing an unrecoverable change such as drop_Table
  • Control what changeSets are run and not run based on the state of the database.

If desired, a precondition can be the only tag in a <changeSet>.

Preconditions at the changelog level apply to all changeSets, not just those listed in the current changelog or its child changelogs.

Sample With Preconditions

<?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-3.8.xsd">
    <preConditions>
        <dbms type="oracle" />
        <runningAs username="SYSTEM" />
    </preConditions>

    <changeSet id="1" author="bob">
        <preConditions onFail="WARN">
            <sqlCheck expectedResult="0">select count(*) from oldtable</sqlCheck>
        </preConditions>
        <comment>Comments should go after preCondition. If they are before then liquibase usually gives error.</comment>
        <dropTable tableName="oldtable"/>
    </changeSet>
</databaseChangeLog>

The above changelog will only run if the database executed against is Oracle and the database user executing the script is “SYSTEM”. It will also only run the drop_Table command if there are no values in the “oldtable”.

Handling Failures and Errors

Liquibase distinguishes between precondition “failures” (check failed) and “errors” (exception thrown in execution of check) and the reaction to both can be controlled via the “onFail” and “onError” attributes on the <preConditions> tag. Since 1.8

Available attributes

AttributeDescription
onFailWhat to do when preconditions fail (see below).
onErrorWhat to do when preconditions error (see below).
onSqlOutputWhat to do in updateSQL mode (see below). Since 1.9.5
onFailMessageCustom message to output when preconditions fail. Since 2.0
onErrorMessageCustom message to output when preconditions fail. Since 2.0

Possible onFail/onError values

ValueDescription
HALTImmediately halt the execution of the entire change log. [DEFAULT]
CONTINUESkip over the *changeSet*. Execution of the change set will be attempted again on the next update. Continue with the *changelog*.
MARK_RANSkip over the change set, but mark it as executed. Continue with the change log.
WARNOutput a warning and continue executing the *changeSet*/*changelog* as normal.

Outside a changeSet (e.g. at the beginning of the change log), only HALT and WARN are possible values.

Possible onSqlOutput values

ValueDescription
TESTRun the changeSet in updateSQL mode.
FAILFail the preCondition in updateSQL mode.
IGNOREIgnore the preCondition in updateSQL mode (default).

AND/OR/NOT Logic

Conditional logic can be applied to preconditions using nestable <and>, <or> and <not> tags. If no conditional tags are specified, it defaults to AND.

Examples:

    <preConditions onFail="WARN">
        <dbms type="oracle" />
        <runningAs username="SYSTEM" />
    </preConditions>

Will check that the update is running on Oracle AND with the SYSTEM user, but will only generate a warning if the precondition fails.

 <preConditions>
     <dbms type="oracle" />
     <dbms type="mysql" />
 </preConditions>

Will require running on Oracle AND MySQL, which will always be false, unless a huge and unexpected merger takes place.

 <preConditions>
     <or>
         <dbms type="oracle" />
         <dbms type="mysql" />
     </or>
 </preConditions>

Will require running on Oracle OR MySQL which makes more sense than the above example.

 <preConditions>
     <or>
         <and>
            <dbms type="oracle" />
            <runningAs username="SYSTEM" />
         </and>
         <and>
            <dbms type="mssql" />
            <runningAs username="sa" />
         </and>
     </or>
 </preConditions>

Will require running as SYSTEM if executing against an Oracle database or running as SA if running against a MS-SQL database.

Available Preconditions

<dbms>

Passes if the database executed against matches the type specified.

Available Attributes

AttributeDescription
typeType of database expected. Multiple dbms values can be specified using comma separated values. required

<runningAs>

Passes if the database user executed under matches the username specified.

Available Attributes

AttributeDescription
usernameDatabase user script is expected to run as. required

<changeSetExecuted>

Passes if the specified change set has already been executed. Since 1.8

Available Attributes

AttributeDescription
idChange set "id". required
authorChange set "author". required
changeLogFileFile name (including classpath relative path) of change set. required

<columnExists>

Passes if the specified column exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the table's schema. required
tableNameName of the column's table. required
columnNameName of column. required

<tableExists>

Passes if the specified table exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the table's schema. required*
tableNameName of the table. required

<viewExists>

Passes if the specified view exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the view's schema. required
viewNameName of the view. required

<foreignKeyConstraintExists>

Passes if the specified foreign key exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the foreign key's schema. required
foreignKeyNameName of the foreign key. required

<indexExists>

Passes if the specified index exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the index's schema. required
indexNameName of the index. required

<sequenceExists>

Passes if the specified sequence exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the sequences's schema. required
sequenceNameName of the sequence. required

<primaryKeyExists>

Passes if the specified primary key exists in the database. Since 1.8

Available Attributes

AttributeDescription
schemaNameName of the primary key's schema.
primaryKeyNameName of the primary key. tableName OR primaryKeyName required
tableNameName of the table containing primary key. tableName OR primaryKeyName required Since 1.9

<sqlCheck>

Executes an SQL string and checks the returned value. The SQL must return a single row with a single value. To check numbers of rows, use the “count” SQL function. To check for ranges of values, perform the check in the SQL and return a value that can be easily compared against.

<sqlCheck expectedResult="1">SELECT COUNT(1) FROM pg_tables WHERE TABLENAME = 'myRequiredTable'</sqlCheck>

Available Attributes

AttributeDescription
expectedResultValue to compare the SQL result to. required

<changeLogPropertyDefined>

Checks whether given changelog parameter is present. If a value is also given, it only fails, if the value is not the same as given. Since 2.0

<changeLogPropertyDefined property="myproperty"/>
<changeLogPropertyDefined property="myproperty" value="requiredvalue"/>

Available Attributes

AttributeDescription
propertyName of the property to check for. required
valueRequired value for given property.

<customPrecondition>

Custom preconditions can be created by creating a class that implements the liquibase.precondition.CustomPrecondition interface. Parameters on custom classes are set through reflection based on the <param> sub-tags. Parameters are passed as strings to the custom precondition.

<customPrecondition className="com.example.CustomTableCheck">
    <param name="tableName" value="our_table"/>
    <param name="count" value="42"/>
</customPrecondition>

Available Attributes

AttributeDescription
classNameName of custom precondition class. required

Available Sub-Tags

AttributeDescription
paramParameter to pass to the custom precondition.
Available “param” sub-tag Attributes
AttributeDescription
nameName of the parameter to set. required
valueString value to set parameter to. required

Implementation Notes

Preconditions are checked at the beginning of the execution of a particular changelog. If you use the “include” tag and only have preconditions on the child changelog, those preconditions will not be checked until the migrator reaches that file. This behavior may change in future releases, so don’t rely on this behavior.