001package io.ebeaninternal.dbmigration.ddlgeneration.platform.util;
002
003import java.util.ArrayList;
004import java.util.List;
005
006/**
007 * The indexes held on the table.
008 * <p>
009 * Used to detect when we don't need to add an index on the foreign key columns
010 * when there is an existing unique constraint with the same columns.
011 */
012public class IndexSet {
013
014  private List<IndexColumns> indexes = new ArrayList<>();
015
016  /**
017   * Clear the indexes (for each table).
018   */
019  public void clear() {
020    indexes.clear();
021  }
022
023  /**
024   * Add an index for the given column.
025   */
026  public void add(String column) {
027    indexes.add(new IndexColumns(column));
028  }
029
030  /**
031   * Return true if an index should be added for the given columns.
032   * <p>
033   * Returning false indicates there is an existing index (unique constraint) with these columns
034   * and that an extra index should not be added.
035   * </p>
036   */
037  public boolean add(String[] columns) {
038    IndexColumns newIndex = new IndexColumns(columns);
039    for (IndexColumns indexe : indexes) {
040      if (indexe.isMatch(newIndex)) {
041        return false;
042      }
043    }
044    indexes.add(newIndex);
045    return true;
046  }
047
048  /**
049   * Add the externally created unique constraint here so that we check later if foreign key indexes
050   * don't need to be created (as the columns match this unique constraint).
051   */
052  public void add(IndexColumns index) {
053    indexes.add(index);
054  }
055
056  public boolean contains(String column) {
057
058    for (IndexColumns index : indexes) {
059      if (index.isMatch(column)) {
060        return true;
061      }
062    }
063    return false;
064  }
065
066  public boolean contains(List<String> columns) {
067
068    for (IndexColumns index : indexes) {
069      if (index.isMatch(columns)) {
070        return true;
071      }
072    }
073    return false;
074  }
075
076  public List<IndexColumns> getIndexes() {
077    return indexes;
078  }
079
080}