Hi,
I'd like to have liquibase to automatically add indexes for all foreign keys created via <addForeignKeyConstraint /> statements.
We use MySQL and PostgreSQL, and for MySQL this is done by MySQL, but it is not done for PostgreSQL.
Is there a setting or a configuration so regardless whether MySQL or PostreSQL is used, we end up having indexes on all foreign keys?
My best solution I've come up so far would be to do this via the following CusomChange:
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;
}
However I doubt that is the best way to ensure indices are also created for postgres.
I'm happy for all suggestions,
best regards Sebastian