aboutsummaryrefslogtreecommitdiffstats
path: root/sonar-db/src/test/java/org/sonar/db/DatabaseCommands.java
blob: 9ec7da2b031d55f24212393cf59688012128d9db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
 * SonarQube
 * Copyright (C) 2009-2016 SonarSource SA
 * mailto:contact AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.db;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringUtils;
import org.dbunit.dataset.datatype.DefaultDataTypeFactory;
import org.dbunit.dataset.datatype.IDataTypeFactory;
import org.dbunit.dataset.datatype.ToleratedDeltaMap;
import org.dbunit.ext.h2.H2DataTypeFactory;
import org.dbunit.ext.mssql.MsSqlDataTypeFactory;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;
import org.dbunit.ext.oracle.Oracle10DataTypeFactory;
import org.dbunit.ext.postgresql.PostgresqlDataTypeFactory;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.MsSql;
import org.sonar.db.dialect.MySql;
import org.sonar.db.dialect.Oracle;
import org.sonar.db.dialect.PostgreSql;
import org.sonar.db.version.SqTables;

public abstract class DatabaseCommands {
  private final IDataTypeFactory dbUnitFactory;

  private DatabaseCommands(DefaultDataTypeFactory dbUnitFactory) {
    this.dbUnitFactory = dbUnitFactory;

    // Hack for MsSQL failure in IssueMapperTest.
    // All the Double fields should be listed here.
    dbUnitFactory.addToleratedDelta(new ToleratedDeltaMap.ToleratedDelta("issues", "effort_to_fix", 0.0001));
  }

  public final IDataTypeFactory getDbUnitFactory() {
    return dbUnitFactory;
  }

  abstract List<String> resetSequenceSql(String table, int minSequenceValue);

  String truncateSql(String table) {
    return "TRUNCATE TABLE " + table;
  }

  boolean useLoginAsSchema() {
    return false;
  }

  public static DatabaseCommands forDialect(Dialect dialect) {
    DatabaseCommands command = ImmutableMap.of(
      org.sonar.db.dialect.H2.ID, H2,
      MsSql.ID, MSSQL,
      MySql.ID, MYSQL,
      Oracle.ID, ORACLE,
      PostgreSql.ID, POSTGRESQL).get(dialect.getId());

    return Preconditions.checkNotNull(command, "Unknown database: " + dialect);
  }

  private static final DatabaseCommands H2 = new DatabaseCommands(new H2DataTypeFactory()) {
    @Override
    List<String> resetSequenceSql(String table, int minSequenceValue) {
      return Arrays.asList("ALTER TABLE " + table + " ALTER COLUMN ID RESTART WITH " + minSequenceValue);
    }
  };

  private static final DatabaseCommands POSTGRESQL = new DatabaseCommands(new PostgresqlDataTypeFactory()) {
    @Override
    List<String> resetSequenceSql(String table, int minSequenceValue) {
      return Arrays.asList("ALTER SEQUENCE " + table + "_id_seq RESTART WITH " + minSequenceValue);
    }
  };

  private static final DatabaseCommands ORACLE = new DatabaseCommands(new Oracle10DataTypeFactory()) {
    @Override
    List<String> resetSequenceSql(String table, int minSequenceValue) {
      String sequence = StringUtils.upperCase(table) + "_SEQ";
      return Arrays.asList(
        "DROP SEQUENCE " + sequence,
        "CREATE SEQUENCE " + sequence + " INCREMENT BY 1 MINVALUE 1 START WITH " + minSequenceValue);
    }

    @Override
    String truncateSql(String table) {
      return "TRUNCATE TABLE " + table + " REUSE STORAGE";
    }

    @Override
    boolean useLoginAsSchema() {
      return true;
    }
  };

  private static final DatabaseCommands MSSQL = new DatabaseCommands(new MsSqlDataTypeFactory()) {
    @Override
    public void resetPrimaryKeys(DataSource dataSource) {
    }

    @Override
    List<String> resetSequenceSql(String table, int minSequenceValue) {
      return null;
    }

    @Override
    protected boolean shouldTruncate(Connection connection, String table) throws SQLException {
      // truncate all tables on mssql, else unexpected errors in some tests
      return true;
    }
  };

  private static final DatabaseCommands MYSQL = new DatabaseCommands(new MySqlDataTypeFactory()) {
    @Override
    public void resetPrimaryKeys(DataSource dataSource) {
    }

    @Override
    List<String> resetSequenceSql(String table, int minSequenceValue) {
      return null;
    }
  };

  public void truncateDatabase(DataSource dataSource) throws SQLException {
    Connection connection = dataSource.getConnection();
    Statement statement = null;
    try {
      connection.setAutoCommit(false);
      statement = connection.createStatement();
      for (String table : SqTables.TABLES) {
        try {
          if (shouldTruncate(connection, table)) {
            statement.executeUpdate(truncateSql(table));
            connection.commit();
          }
        } catch (Exception e) {
          connection.rollback();
          throw new IllegalStateException("Fail to truncate table " + table, e);
        }
      }
    } finally {
      DbUtils.closeQuietly(connection);
      DbUtils.closeQuietly(statement);
    }
  }

  protected boolean shouldTruncate(Connection connection, String table) throws SQLException {
    Statement stmt = connection.createStatement();
    ResultSet rs = null;
    try {
      rs = stmt.executeQuery("select count(1) from " + table);
      if (rs.next()) {
        return rs.getInt(1) > 0;
      }

    } catch (SQLException ignored) {
      // probably because table does not exist. That's the case with H2 tests.
    } finally {
      DbUtils.closeQuietly(rs);
      DbUtils.closeQuietly(stmt);
    }
    return false;
  }

  public void resetPrimaryKeys(DataSource dataSource) throws SQLException {
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
      connection = dataSource.getConnection();
      connection.setAutoCommit(false);

      statement = connection.createStatement();
      for (String table : SqTables.TABLES) {
        try {
          resultSet = statement.executeQuery("SELECT CASE WHEN MAX(ID) IS NULL THEN 1 ELSE MAX(ID)+1 END FROM " + table);
          resultSet.next();
          int maxId = resultSet.getInt(1);
          resultSet.close();

          for (String resetCommand : resetSequenceSql(table, maxId)) {
            statement.executeUpdate(resetCommand);
          }
          connection.commit();
        } catch (Exception e) {
          connection.rollback(); // this table has no primary key
        }
      }
    } finally {
      DbUtils.closeQuietly(connection, statement, resultSet);
    }
  }
}