Preconditions

Preconditions are changelog or changeset tags which control the execution of an update based on the state of the database.

Uses

You can use preconditions to:

  • Document what assumptions the author 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 dropTable.
  • Control what changesets are run and not run based on the state of the database.

You can use all Liquibase preconditions in XML, YAML, and JSON changelogs. The only supported precondition for SQL changelogs is sqlCheck. For a list of preconditions, see Available preconditions.

Syntax

You can use one <preConditions> tag per changeset and one overarching <preConditions> tag in the changelog (outside any changeset). In XML, YAML, and JSON changelogs, you can use conditional logic to add multiple preconditions within a single <preConditions> tag.

Preconditions at the changelog level are applied to all changesets, not just those listed in the current changelog or its child changelogs.

Multiple preconditions

In XML, JSON, and YAML changelogs, you can set multiple preconditions in one <preConditions> tag by using nestable AND, OR, and NOT conditional logic tags. If no conditional tags are specified, the default value is AND.

Liquibase uses lazy evaluation (call-by-need) when running preconditions. For example, if the first condition of an AND expression fails, Liquibase does not evaluate the second condition. If the first condition of an OR expression succeeds, Liquibase does not evaluate the second condition.

  • XML:

    <preConditions>
        <or>
            <CONDITION_1>
            <CONDITION_2>
        </or>
    </preConditions>
  • JSON:

    {
      "preConditions": [
        {
          "or": [
            {
              {CONDITION_1},
              {CONDITION_2}
            }
          ]
        }
      ]
    }
  • YAML:

    - preConditions:
        - or:
            - CONDITION_1
            - CONDITION_2

Examples

The following syntax example will check that the update is running on Oracle and with the SYSTEM user but will only generate a warning message if the precondition fails:

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

The following will require running the changelog on Oracle or MySQL:

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

You can also see the precondition running as SYSTEM if executing against an Oracle database or running as SA if executing against a MS SQL database.

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

Handling failures and errors

Liquibase defines two types of preconditions:

  • Precondition failures which represent that the check failed
  • Precondition errors that are the exceptions thrown in the execution of a check

The process of both can be controlled through the onFail and onError attributes on the <preConditions> tag.

Available attributes

Attribute Description
onError Controls what happens if there is an error checking whether the precondition passed or not.
onErrorMessage Provides a custom message to output when preconditions fail. Since 2.0
onFail Controls what happens if the preconditions check fails.
onFailMessage Provides a custom message to output when preconditions fail. Since 2.0
onSqlOutput Controls how preconditions are evaluated in the update-sql mode for XML, YAML, and JSON changelogs. Since 1.9.5
onUpdateSql Controls how preconditions are evaluated in the update-sql mode for formatted SQL changelogs.

onFail/onError values

Value Description
CONTINUE Skips over the changeset. Execution of the changeset will be attempted again on the next update. Continues with the changelog.
HALT Halts the execution of the entire changelog (default). HALT can be put outside a changeset (e.g. at the beginning of the changelog).
MARK_RAN Skips over the changeset but mark it as executed. Continues with the changelog.
WARN Sends a warning and continues executing the changeset / changelog as normal. WARN can be put outside a changeset (e.g. at the beginning of the changelog).

onSqlOutput/onUpdateSql values

Value Description
FAIL Fails the preCondition in the update-sql mode.
IGNORE Ignores the preCondition in the update-sql mode (default).
TEST Runs the changeset in the update-sql mode.

Available preconditions

The examples of preconditions shown in the table doesn't include the schemaName attribute. It is best practice not to keep the schemaName in the changeset and rely on the default schema except for times you don’t want to create something in the default schema.

Additionally, you can include the onError or onFail attributes with the WARN, HALT, CONTINUE, or MARK_RAN value in the preconditions tag, however, the CONTINUE and MARK_RAN options can only be applied to preconditions inside a changeset.

You can use any precondition mentioned in the following table:

Precondition Description Attribute
dbms

Defines if the database executed against matches the type specified.

<preConditions onFail="WARN">
  <or>
    <dbms  type="oracle"  />
    <dbms  type="mysql"  />
  </or>
</preConditions>
type – the type of database expected. Multiple dbms values can be specified using comma-separated values. (required)
changeLogPropertyDefined

Checks whether given changelog attribute is present. It fails if the value is not the same as given.

<preConditions onFail="WARN">
    <changeLogPropertyDefined property="myproperty"/>
    <changeLogPropertyDefined property="myproperty" value="requiredvalue"/>
</preConditions>

  • property – the name of the property to check. (required)
  • value – the required value for a given property.
changeSetExecuted

Defines if the specified changeset has already been executed.

<preConditions onFail="HALT">
    <changeSetExecuted id="1" author="liquibase" changelog-file="changelog.xml" />
</preConditions>
  • Id – the changeset id. (required)
  • author – the changeset author. (required)
  • changelog-file – the file name (including searchPath relative path) of the changeset. (required)
sqlCheck

Executes an SQL string and checks the returned value. The SQL must return a single row with a single value.

  • To check a number 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.
<preConditions onFail="WARN">
    <sqlCheck expectedResult="1">
        SELECT COUNT(1) FROM pg_tables WHERE TABLENAME = 'myRequiredTable'
    </sqlCheck>
</preConditions>
expectedResult – the value to compare the SQL result to. (required)
rowCount

Checks that the number of rows in a table matches an expected value.

<preConditions>
    <rowCount expectedRows="5" tableName="person"/>
</preConditions>
  • expectedRows – the number of rows the user expects in a table (required)
  • tableName – the name of the column's table (required)
runningAs

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

<preConditions  onFail="WARN">
    <dbms  type="oracle"  />
    <runningAs  username="SYSTEM"  />
</preConditions>
username – the database user script which is expected to run as. (required)
columnExists

Defines if the specified column exists in the database.

<preConditions onFail="WARN">
    <columnExists tableName="table1" columnName="column1" />
</preConditions>
  • schemaName – the name of the table's schema.
  • tableName – the name of the column's table. (required)
  • columnName – the name of the column. (required)
foreignKeyConstraintExists

Defines if the specified foreign key exists in the database.

<preConditions onFail="WARN">
    <foreignKeyConstraintExists foreignKeyName="PK_2354" />
</preConditions>
  • schemaName – the name of the foreign key's schema.
  • foreignKeyName – the name of the foreign key. (required)
indexExists

Defines if the specified index exists in the database. You can either specify the indexName attribute or tableName and columnNames attributes.

<preConditions onFail="WARN">
    <indexExists indexName="originindex"/>
</preConditions>
<preConditions onFail="WARN">
    <indexExists tableName="MY_NEW_TABLE" columnNames="ID"/>
</preConditions>

Note: There are a few databases where the indexName is not unique, that's why both indexName and tableName can be used.

<preConditions onFail="WARN">
    <indexExists indexName="originindex" tableName="MY_NEW_TABLE"/>
</preConditions>
  • schemaName – the name of the index's schema.
  • indexName – the name of the index.
  • tableName – the name of the table.
  • columnNames – the name of the column.
primaryKeyExists

Defines if the specified primary key exists in the database.

<preConditions onFail="HALT">
    <primaryKeyExists primaryKeyName="ID_2354" tableName="table1" />
</preConditions>
  • schemaName – the name of the primary key's schema.
  • primaryKeyName – the name of the primary key constraint.
  • tableName – the name of the table containing primary key.
    (tableName or primaryKeyName is required)
sequenceExists

Defines if the specified sequence exists in the database.

<preConditions onFail="WARN">
    <sequenceExists sequenceName="idnumber" />
</preConditions>
  • schemaName – the name of the sequences' schema.
  • sequenceName – the name of the sequence. (required)
tableExists

Defines if the specified table exists in the database.

<changeSet author="author" id="1">
   <preConditions onFail="MARK_RAN">
       <not>
           <tableExists tableName="MY_NEW_TABLE"/>
       </not> 
   </preConditions>
       <createTable tableName="MY_NEW_TABLE">
           <column name="IDX" type="${integer.type}">
               <constraints nullable="false"/> 
           </column>
           <column name="INTVAL" type="${integer.type}"/>
       </createTable>
</changeSet>
  • schemaName – the name of the table's schema.
  • tableName – the name of the table. (required)
uniqueConstraintExists

Checks for the existence of unique constraints before running the update. (since Liquibase 4.9.0)

<preConditions>
<uniqueConstraintExists constraintName="uq_constraint_name" tableName="test_table"/>
</preConditions>

<preConditions>
<uniqueConstraintExists tableName="test_table" columnNames="first_name, last_name"/>
</preConditions>
  • constraintName – the name of the unique constraint
  • tableName – the name of the column's table (required)
  • columnNames – the name of the column
viewExists

Defines if the specified view exists in the database.

<preConditions onFail="HALT">
    <viewExists viewName="liquibase" />
</preConditions>
  • schemaName – the name of the view's schema.
  • viewName – the name of the view. (required)
customPrecondition

Can be created by adding a class that implements the liquibase.precondition.CustomPrecondition interface. Parameters on custom classes are set through reflection based on the <param> sub-tags. Pass parameters as strings to the custom precondition.

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

className – the name of the custom precondition class. (required)

The customPrecondition sub-tags:

  • param – the parameter to pass to the custom precondition.
  • name – the name of the parameter to set. (required)
  • value – a string value to set parameter to. (required)