0

我有这样的情况:

  1. 有现有的表
  2. 需要使用添加新列
  3. 列的类型是 TIMESTAMP

代码:

<changeSet author="name" id="bla-bla-bla">
    <addColumn tableName="table_name">
        <column name="new_col_name" type="TIMESTAMP"/>
    </addColumn>
</changeSet>

这段代码创建列,很酷!但!它还将所有现有行的默认值设置为 0000-00-00 00:00:00。

但我需要保留所有现有行而不做任何更改。并且应该只为新行设置 TIMESTAMPS。

4

2 回答 2

3

A TIMESTAMP column in MySQL defaults to NOT NULL and that dreaded zero date as the default value (See the manual for details).

The only way I can see how to avoid this, is to modify the generated SQL to include the DEFAULT NULL clause in the changeset.

<addColumn tableName="foo">
    <column name="new_date" type="TIMESTAMP"/>
</addColumn>
<modifySql>
     <replace replace="TIMESTAMP" with="TIMESTAMP NULL DEFAULT NULL"/>
</modifySql>

Specifying defaultValueDate="NULL" does not seem to work. I guess that's because Liquibase does not know about the timestamp quirks of MySQL and thinks it's no necessary to state the obvious - that a column should be filled with NULL.

Edit

I forgot that this will not work for new rows of course. There are two ways to re-apply the default value using Liquibase:

Adding a second changeSet that changes the default value to CURRENT_TIMESTAMP:

<sql>
     alter table foo modify new_date timestamp null default current_timestamp
</sql>

Or by not using DEFAULT NULL when adding the column, but then running a statement that sets all (existing) rows back to NULL. A sql tag with update foo set new_date = null.

于 2012-11-22T14:54:37.820 回答
0

再一次,我需要修改这段代码。想法是一样的,如何创建新的 Timestamp 列,但所有现有行都应使用当前时间戳进行修改,并且在更新期间仅修改一次,但所有新行都应使用创建时间戳。代码:

<changeSet author="name" id="bla-bla-bla">
    <addColumn tableName="table_name">
        <column name="new_col_name" type="TIMESTAMP"/>
    </addColumn>
</changeSet>

此代码为所有现有行创建带有 0000-00-00 时间戳的列。

于 2012-12-21T09:18:53.003 回答