2

I have the issue that a field called updated_at which the user freely selects a date to be stored, that if the user send 2021-08-11T21:59:59.999Z, this will be rounded to 2021-08-11 22:00:00.0 automatically, so the field is looking like this

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_at")
private Date updatedAt;

I read that changing the timestamp to timestamp(3) will solve the rounding problem, so I wrote a Liquibase script like this changeset

<changeSet id="10" author="autho2">
     <modifyDataType
             columnName="updated_at"
             newDataType="timestamp(3)"
             tableName="user_data"/>
 </changeSet>

However, I get error:

 liquibase.exception.DatabaseException: 
Invalid default value for 'updated_at' [Failed SQL:
 (1067) ALTER TABLE user_data MODIFY updated_at timestamp(3)]

What am I doing wrong or am i converting date to instance wrongly?

Catalina
  • 663
  • 5
  • 20

2 Answers2

4

When MODIFYing a column definition, you must include all attributes that you want to keep:

ALTER TABLE user_data
    MODIFY updated_at timestamp(3) 
    NULL                           -- if you you want it NULLable
    DEFAULT CURRENT_TIMESTAMP(3)   -- note this needs "(3)" too
    ON UPDATE CURRENT_TIMESTAMP(3) -- if you want
Rick James
  • 135,179
  • 13
  • 127
  • 222
2

Adding on to Rick James's answer: (Rick's SQL works like a charm)

To use it with Liquibase, you may try using :

1. <changeSet id="10" author="autho2">
     <sql>
         ALTER TABLE user_data
         MODIFY updated_at timestamp(3) 
         NULL                           -- if you you want it NULLable
         DEFAULT CURRENT_TIMESTAMP(3)   -- note this needs "(3)" too
         ON UPDATE CURRENT_TIMESTAMP(3); -- if you want
     <sql>
   </changeSet>
2. <changeSet id="10" author="autho2">
     <modifyDataType
             columnName="updated_at"
             newDataType="timestamp(3)"
             tableName="user_data"/>
     <modifySql>  
             <append  value="NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"/>
        </modifySql>
   </changeSet>

Before running liquibase update you can try using liquibase updateSQL and check the output SQL, if is the expected SQL you are going to run.

Rakhi Agrawal
  • 827
  • 7
  • 14