liquibase - 为postgresql外键创建索引

时间:2016-12-12 16:47:13

标签: mysql postgresql indexing foreign-keys liquibase

我们正在使用liquibase变更集来支持MySQL和PostgreSQL的使用;现在我偶然发现MySQL会自动为postgres创建外键索引。

问题:如何确保数据库架构具有所有外键的索引,而不管实际使用哪个数据库?

更新28.02.2017 以下是liquibase论坛中问题的链接:http://forum.liquibase.org/#Topic/49382000001637005

2 个答案:

答案 0 :(得分:1)

在这里查看'dbms'前置条件:http://www.liquibase.org/documentation/preconditions.html。您可以将所有特定于postgesql的代码放在那里。

答案 1 :(得分:0)

我将使用CustomChange-Command解决此问题:

public class AddForeignKeyConstraintWithIndex extends
liquibase.change.core.AddForeignKeyConstraintChange implements
liquibase.change.custom.CustomSqlChange {

@SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"})
private ResourceAccessor resourceAccessor;

@Override
public void setUp() throws SetupException {
}

@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {
    this.resourceAccessor = resourceAccessor;
}

@Override
public SqlStatement[] generateStatements(Database database) {
    SqlStatement[] result = super.generateStatements(database);
    // Für Postgres zusätzlich Index anlegen
    if (database instanceof PostgresDatabase) {
        AddColumnConfig columnConfig = new AddColumnConfig();
        columnConfig.setName(getBaseColumnNames());
        columnConfig.setComputed(Boolean.FALSE);

        SqlStatement createIndexStatement = new CreateIndexStatement(
                "ix_" + getConstraintName(),
                getBaseTableCatalogName(),
                getBaseTableSchemaName(),
                getBaseTableName(),
                Boolean.FALSE,
                null,
                columnConfig
        );
        List<SqlStatement> list = new ArrayList<>(Arrays.asList(result));
        list.add(createIndexStatement);

        return list.toArray(new SqlStatement[list.size()]);

    }
    return result;
}

然后您可以将此CustomChange称为此(使用与AddForeignKeyConstraint语句完全相同的参数):

<customChange
class="eu.***.***.AddForeignKeyConstraintWithIndex"
        baseTableName="tbl_interest_reference"
        baseColumnNames="customer_id"
        constraintName="finterest_ref_customer_fk"
        referencedTableName="tbl_customer"
        referencedColumnNames="customer_id"
    />