import org.sonar.db.version.Select;
import org.sonar.db.version.SqlStatement;
-import static com.google.common.base.Preconditions.checkState;
-import static org.apache.commons.lang.StringUtils.isNotBlank;
+import static org.apache.commons.lang.StringUtils.isBlank;
public class PopulateProfileKeyOfActivities extends BaseDataChange {
massUpdate.update("update activities set profile_key=?, data_field=? where id=?");
massUpdate.rowPluralName("activities");
massUpdate.execute(PopulateProfileKeyOfActivities::handle);
+
+ // SONAR-8534 delete orphans
+ context.prepareUpsert("delete from activities where profile_key is null")
+ .execute()
+ .commit();
}
private static boolean handle(Select.Row row, SqlStatement update) throws SQLException {
String data = row.getString(2);
Map<String, String> fields = KeyValueFormat.parse(data);
String profileKey = fields.remove("profileKey");
- checkState(isNotBlank(profileKey), "No profile key found in db row of activities.data_field", id);
-
+ if (isBlank(profileKey)) {
+ return false;
+ }
update.setString(1, profileKey);
update.setString(2, KeyValueFormat.format(fields));
update.setInt(3, id);
-
return true;
}
}
}
@Test
- public void fail_if_activity_data_is_not_well_formatted() throws SQLException {
- expectedException.expect(IllegalStateException.class);
- expectedException.expectMessage("Error during processing of row: ");
-
+ public void delete_the_rows_of_ACTIVITIES_that_do_not_have_profileKey() throws SQLException {
db.executeInsert(ACTIVITIES_TABLE, "data_field", "key=fakeKey");
underTest.execute();
+
+ assertThat(db.countRowsOfTable(ACTIVITIES_TABLE)).isEqualTo(0);
+ }
+
+ @Test
+ public void delete_the_rows_of_ACTIVITIES_that_have_empty_profileKey() throws SQLException {
+ insertActivity("");
+
+ underTest.execute();
+
+ assertThat(db.countRowsOfTable(ACTIVITIES_TABLE)).isEqualTo(0);
+ }
+
+ @Test
+ public void delete_the_rows_of_ACTIVITIES_that_have_blank_profileKey() throws SQLException {
+ insertActivity(" ");
+
+ underTest.execute();
+
+ assertThat(db.countRowsOfTable(ACTIVITIES_TABLE)).isEqualTo(0);
}
private void assertCountActivitiesWithProfile(String profileKey, int expectedNumberOfActivities) {