Liquibase preconditions: How do I check for a column being non-nullable?

泄露秘密 提交于 2019-12-05 04:44:15

Can be done with sqlCheck.

  • For MySql

    <preConditions onFail="MARK_RAN" onError="CONTINUE">
        <sqlCheck expectedResult="NO">
            SELECT is_Nullable
            FROM  INFORMATION_SCHEMA.COLUMNS 
            WHERE table_name='<table_name>' 
            AND column_name='<column_name>' 
        </sqlCheck>   
    </preConditions>
    
  • For Oracle:

    <preConditions onFail="MARK_RAN" onError="CONTINUE">
        <sqlCheck expectedResult="N">
            SELECT Nullable
            FROM user_tab_columns
            WHERE table_name = '<table_name>'
            AND column_name = '<column_name>'
        </sqlCheck>
    </preConditions>
    
  • For SQL Server:

    <preConditions onFail="MARK_RAN" onError="CONTINUE">
        <sqlCheck expectedResult="0">
          SELECT is_nullable 
          FROM sys.columns
          WHERE  object_id = OBJECT_ID('<table_name>')  
          AND name = '<column_name>' 
        </sqlCheck>
    </preConditions>
    

Revising my answer. Liquibase supports an add not null constraint operation as follows:

<changeSet author="me" id="example-001">
    <addNotNullConstraint 
        tableName="mytable"    
        columnName="mycol"
        columnDataType="VARCHAR(10)"
        defaultNullValue="NULL"/>
</changeSet>

This automatically handles columns that are null, in my example populating them with the text string "NULL".

I don't think this changeset requires a pre-condition. Worst case you'd re-apply the existing column constraint, once. Liquibase tracks all changsets and ensures they are not executed again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!