如何使用 liquibase 在 Java 中将旧数据库架构更新为新数据库架构

How to update old database schema to new one in Java with liquibase

我和我的团队与其他团队分开开展过一个项目。 该团队在这个项目上工作了 2 年,现在他们离开了,把整个项目留给了我们,在过去的 2 个月里,我们不得不了解这个项目并添加一些功能(比如多货币、新的入职流程等)和这个features 意味着数据库中的新列、新表等。 我们需要在不破坏任何东西的情况下将旧的生产数据库更新为新的(我们不能只是删除它并使用新脚本重新开始)。 我们想在 Java Spring 中为这个和将来的其他迁移创建一些通用脚本,比如 "take this table and add this column if it doesn't exists, but if it exists and it is empty/null, add this data in it (for example, phone_number that every user needs to have and if it is not present, add something autoincrement: 000000001, 00000002 etc., and after that we need to ask users to verify their phone and override that 0000001, 0000002)"。 因此,我们可以让旧模式看起来与新模式完全一样,我们想要创建一个接口或其他东西来使这些迁移更通用。 您认为如何最好地解决这个问题?

谢谢!

既然您知道 "old schema" 需要什么改变,并且您愿意实施它们 - Liquibase 看起来是一个方便的解决方案。

您应该编写必要的 changeSets 来更新您的架构。

Liquibase 提供 lot of changes,足以编写基本迁移内容的脚本。

要添加新的 table,您可以使用 createTable change:

<changeSet id="foo" author="bar">
    <preConditions onFail="MARK_RAN">
        <not>
            <tableExists tableName="your_table"/>
        </not>
    </preConditions>
    <createTable tableName="your_table">
        <!-- your columns here -->
    </createTable>
</changeSet>

要添加列,您可以使用 addColumn change:

<changeSet id="foo2" author="bar">
    <preConditions onFail="MARK_RAN">
        <not>
            <columnExists tableName="your_table" columnName="your_column"/>
        </not>
    </preConditions>
    <addColumn tableName="your_table">
        <column name="your_column" type="integer">
            <constraints nullable="false"/>
        </column>
    </addColumn>
</changeSet>

对于数据更新,您可以使用 update change:

<changeSet id="foo3" author="bar">
    <preConditions onFail="MARK_RAN">
        <columnExists tableName="your_table" columnName="your_column"/>
    </preConditions>
    <update tableName="your_table">
        <column name="your_column" value="123"/>
        <where>your_column IS NULL</where>
    </update>
</changeSet>

对于基本的 SQL 请求,您可以使用 sql change:

<changeSet id="foo4" author="bar">
    <preConditions onFail="MARK_RAN">
        <sqlCheck expectedResult="1">
            <!-- something like -->
            SELECT * from your_table where your_column = 100;
        </sqlCheck>
    </preConditions>
    <sql>DELETE FROM your_table WHERE your_column=100</sql>
</changeSet>

等等等等。您将所有 changeSet 捆绑到 databaseChangeLog,将 changeLogs 添加到您的应用程序,然后您就可以开始 "old schema" 更新了!