]> source.dussan.org Git - sonarqube.git/commitdiff
New attempt to speed-up db tests
authorSimon Brandhof <simon.brandhof@sonarsource.com>
Wed, 21 Jan 2015 19:17:37 +0000 (20:17 +0100)
committerSimon Brandhof <simon.brandhof@sonarsource.com>
Wed, 21 Jan 2015 19:23:54 +0000 (20:23 +0100)
TRUNCATE is slow, even of empty tables, so it must be executed only if count(*)>0

sonar-core/src/test/java/org/sonar/core/persistence/DatabaseCommands.java

index 52db5b3a811e7a9792805b51e080ed44b9bf66ab..ff04b1ad7ed18bcae49048ee587faa0d2de6f2fc 100644 (file)
@@ -137,11 +137,13 @@ public abstract class DatabaseCommands {
       statement = connection.createStatement();
       for (String table : DatabaseVersion.TABLES) {
         try {
-          statement.executeUpdate(getTruncateCommand(table));
-          connection.commit();
+          if (countRows(connection, table)>0) {
+            statement.executeUpdate(getTruncateCommand(table));
+            connection.commit();
+          }
         } catch (Exception e) {
-          // ignore
           connection.rollback();
+          throw new IllegalStateException("Fail to truncate table " + table, e);
         }
       }
     } finally {
@@ -150,6 +152,24 @@ public abstract class DatabaseCommands {
     }
   }
 
+  private int countRows(Connection connection, String table) throws SQLException {
+    Statement stmt = connection.createStatement();
+    ResultSet rs = null;
+    try {
+      rs = stmt.executeQuery("select count(*) from " + table);
+      if (rs.next()) {
+        return rs.getInt(1);
+      }
+
+    } catch (SQLException ignored) {
+      // probably because table does not exist. That's the case with H2 tests.
+    } finally {
+      DbUtils.closeQuietly(rs);
+      DbUtils.closeQuietly(stmt);
+    }
+    return 0;
+  }
+
   public void resetPrimaryKeys(DataSource dataSource) throws SQLException {
     Connection connection = dataSource.getConnection();
     connection.setAutoCommit(false);