Liquibase: How to set the default value of a date column to be “now” in UTC format?

前端 未结 6 548
忘掉有多难
忘掉有多难 2021-01-07 16:20

How do you set the default value of a date column to be \"now\" in UTC format? I think the answer involves the defaultValueComputed attribute on the column elem

相关标签:
6条回答
  • 2021-01-07 16:46

    As liquibase is common changelog for any database, to make it generic you should not depend on any specific database like oracle, postegres, mysql instead it should be generic enough to work for any/every database.

    Below is how it should be implemented :

    <column name="time" type="${type.datetime}" defaultValueComputed="${column.datetime.defaultValue}"/>
    

    This should work for all databases, for oracle, it inserts SYSTIMESTAMP as DATA_DEFAULT.

    0 讨论(0)
  • 2021-01-07 16:46

    This worked for me:

    <property name="now" value="UNIX_TIMESTAMP()" dbms="mysql"/>
    <column name="ts" type="timestamp" valueDate="${now}"/>
    

    I found it thanks to this answer: https://stackoverflow.com/a/9100388/3107952

    0 讨论(0)
  • 2021-01-07 16:47

    In MySQL, to use a DATETIME column with fractions of second like DATETIME(6) (microseconds precision), use default value of NOW(6) (caution: CURRENT_TIMESTAMP(6) for some reason produces an error with me using liquibase 3.5.3):

    <column name="created_at" type="DATETIME(6)" defaultValueComputed="NOW(6)" >
       <constraints nullable="false" />
    </column>
    

    Note that the value will be stored internally in UTC, but read using the server's timezone settings (@@global.time_zone, @@session.time_zone).

    0 讨论(0)
  • 2021-01-07 17:01

    This works with SQlite:

    <column name="last_updated_at" type="TIMESTAMP" defaultValueComputed="CURRENT_TIMESTAMP">
                    <constraints nullable="false"/>
    </column>
    

    Adding '$now' didn't work for me. I am using SQlite as the DB.

    0 讨论(0)
  • 2021-01-07 17:05

    I used function the database vendor. For Oracle it`s a sysdate:

    <column name="create_date" type="DATETIME" valueDate="sysdate" defaultValueComputed="sysdate" />
    
    0 讨论(0)
  • 2021-01-07 17:07

    Maybe this topic in the liquibase forum will help?

    I think defaultValueComputed will take a database specific function to express "now". In mySQL it would be CURRENT_TIMESTAMP so it could look like this:

    <createTable tableName="D_UserSession">
        <column name="ts" type="TIMESTAMP" defaultValueComputed="CURRENT_TIMESTAMP"/>
    </createTable>
    

    (Copied from the forum post.)

    0 讨论(0)
提交回复
热议问题