// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.schema;

import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
import com.google.gwtorm.schema.sql.DialectPostgreSQL;
import com.google.gwtorm.schema.sql.SqlDialect;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;

import java.sql.SQLException;
import java.sql.Statement;

public class Schema_102 extends SchemaVersion {
  @Inject
  Schema_102(Provider<Schema_101> prior) {
    super(prior);
  }

  @Override
  protected void migrateData(ReviewDb db, UpdateUI ui)
      throws OrmException, SQLException {
    JdbcSchema schema = (JdbcSchema) db;
    SqlDialect dialect = schema.getDialect();
    try (Statement stmt = schema.getConnection().createStatement()) {
      stmt.executeUpdate("DROP INDEX changes_byProjectOpen");
      if (dialect instanceof DialectPostgreSQL) {
        stmt.executeUpdate("CREATE INDEX changes_byProjectOpen"
            + " ON changes (dest_project_name, last_updated_on)"
            + " WHERE open = 'Y'");
      } else {
        stmt.executeUpdate("CREATE INDEX changes_byProjectOpen"
            + " ON changes (open, dest_project_name, last_updated_on)");
      }
    }
  }
}

@@ -1011,16 +1011,70 @@
 atement;
+%0Aimport java.util.regex.Pattern;%0Aimport java.util.Set;
 %0A%0Apublic
@@ -1453,24 +1453,615 @@
 tement()) %7B%0A
+      // Drop left over indexes that were missed to be removed in schema 84.%0A      // See %22Delete SQL index support%22 commit for more details:%0A      // d4ae3a16d5e1464574bd04f429a63eb9c02b3b43%0A      Pattern pattern =%0A          Pattern.compile(%22%5Echanges_(allOpen%7CallClosed%7CbyBranchClosed)$%22,%0A              Pattern.CASE_INSENSITIVE);%0A      Set%3CString%3E listIndexes = dialect.listIndexes(%0A          schema.getConnection(), %22changes%22);%0A      for (String index : listIndexes) %7B%0A        if (pattern.matcher(index).matches()) %7B%0A          stmt.executeUpdate(%22DROP INDEX %22 + index);%0A        %7D%0A      %7D%0A%0A
       stmt.e

Drop left over SQL indexes that prevent removal of sortkey