我正在尝试解决以下有关 Liquibase 架构 XML 脚本的难题。我的目标是使用 Liquibase 架构为 PostgreSQL 表创建新索引,并满足以下条件
执行以下脚本
例如
<changeSet author="ABC" id="11111111">
<preConditions onFail="MARK_RAN">
<tableExists tableName="XYZ"/>
<columnExists tableName="XYZ"
columnName="point" />
<!-- Check if the index exists -->
<not>
<indexExists indexName="idx_XYZ"/>
<not>
</preConditions>
<!-- Drop the index if it exists -->
<dropIndex tableName="XYZ" indexName="idx_XYZ" />
<!-- Create the new index -->
<createIndex indexName="idx_XYZ"
tableName="XYZ" unique="false">
<column name="point" />
</createIndex>
</changeSet>
错误: -E- [liquischema] Liquibase 中发生错误: -E- [liquischema] liquibase.exception.LiquibaseException:liquibase.exception.MigrationFailedException:变更集 schema/migrations/0021_CreateIndex.xml::11111111::ABC 迁移失败: 原因:liquibase.exception.DatabaseException:错误:索引“idx_XYZ”不存在[失败的SQL:(0)DROP INDEX public.idx_XYZ] 我- [liquischema] 完成了。关闭连接...
如果我答对了你的问题,那么通过制作两个单独的变更集应该非常简单:
如果索引已存在,脚本应删除现有索引 然后创建一个新的。
<changeSet id="foo" author="bar">
<preConditions onFail="MARK_RAN">
<indexExists indexName="idx_XYZ"/>
</preConditions>
<dropIndex tableName="XYZ" indexName="idx_XYZ"/>
<createIndex indexName="idx_XYZ" tableName="XYZ" unique="false">
<column name="point"/>
</createIndex>
</changeSet>
如果索引不存在,脚本应跳过删除索引 条件并继续创建新索引。
<changeSet id="foo1" author="bar">
<preConditions onFail="MARK_RAN">
<not>
<indexExists indexName="idx_XYZ"/>
</not>
</preConditions>
<createIndex indexName="idx_XYZ" tableName="XYZ" unique="false">
<column name="point"/>
</createIndex>
</changeSet>
重要的是,脚本不应停止 Liquibase 模式 处决。即使指定的条件失败,脚本也应该 继续运行后续任务。
由于
onFail="MARK_RAN"
,执行不会停止。
如果索引首先存在:
如果索引一开始就不存在: