Skip to content

Commit

Permalink
Merge branch 'change-modification-order-when-deleted' of https://gith…
Browse files Browse the repository at this point in the history
…ub.com/gridsuite/network-modification-server into change-modification-order-when-deleted
  • Loading branch information
etiennehomer committed Oct 15, 2024
2 parents f71b73e + 14368c8 commit 388fcda
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 22 deletions.
1 change: 0 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ public ResponseEntity<Void> stashNetworkModifications(
networkModificationService.stashNetworkModifications(groupUuid, networkModificationUuids);
networkModificationService.reorderNetworkModifications(groupUuid, Boolean.FALSE);
} else {
networkModificationService.restoreNetworkModifications(networkModificationUuids, groupUuid);
networkModificationService.restoreNetworkModifications(groupUuid, networkModificationUuids);
networkModificationService.reorderNetworkModifications(groupUuid, Boolean.TRUE);
}
return ResponseEntity.ok().build();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package org.gridsuite.modification.server.migration;

import liquibase.change.custom.CustomTaskChange;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.CustomChangeException;
import liquibase.exception.DatabaseException;
import liquibase.exception.SetupException;
import liquibase.exception.ValidationErrors;
import liquibase.resource.ResourceAccessor;
import org.apache.commons.lang3.tuple.Pair;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;

public class ModificationOrderMigration implements CustomTaskChange {

@Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try {
ResultSet groupIds = connection.createStatement().executeQuery("select distinct group_id from modification");
while (groupIds.next()) {
UUID groupId = UUID.fromString(groupIds.getString(1));
reorderNetworkModifications(groupId, true, connection);
reorderNetworkModifications(groupId, false, connection);
}
} catch (SQLException | DatabaseException e) {
throw new CustomChangeException(e);
}
}

private void reorderNetworkModifications(UUID groupId, boolean stashed, JdbcConnection connection) throws SQLException, DatabaseException {
List<UUID> entities = findAllByGroupId(groupId, stashed, connection);
List<Pair<UUID, Integer>> entitiesToUpdate = new ArrayList<>();
if (!entities.isEmpty()) {
if (Boolean.TRUE.equals(stashed)) {
IntStream.range(1, entities.size() + 1)
.forEach(i -> entitiesToUpdate.add(Pair.of(entities.get(i - 1), -i)));
} else {
IntStream.range(0, entities.size())
.forEach(i -> entitiesToUpdate.add(Pair.of(entities.get(i), i)));
}
}
saveAll(entitiesToUpdate, connection);
}

private List<UUID> findAllByGroupId(UUID groupId, boolean stashed, JdbcConnection connection) throws DatabaseException, SQLException {
ResultSet resultSet = connection.createStatement().executeQuery(String.format("SELECT id FROM modification m WHERE m.group_id = '%s' AND m.stashed = %b order by modifications_order", groupId, stashed));
List<UUID> entities = new ArrayList<>();
while (resultSet.next()) {
entities.add(UUID.fromString(resultSet.getString(1)));
}
return entities;
}

private void saveAll(List<Pair<UUID, Integer>> entities, JdbcConnection connection) throws DatabaseException, SQLException {
Statement statement = connection.createStatement();
entities.forEach(pair -> {
try {
statement.addBatch(String.format("UPDATE modification SET modifications_order=%d WHERE id = '%s'", pair.getValue(), pair.getKey()));
} catch (SQLException e) {
throw new RuntimeException(e);
}

});
statement.executeBatch();
}

@Override
public String getConfirmationMessage() {
return "";
}

@Override
public void setUp() throws SetupException {

}

@Override
public void setFileOpener(ResourceAccessor resourceAccessor) {

}

@Override
public ValidationErrors validate(Database database) {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public interface ModificationRepository extends JpaRepository<ModificationEntity
List<ModificationEntity> findAllBaseByGroupIdReverse(UUID uuid);

@Query(value = "SELECT m FROM ModificationEntity m WHERE m.group.id = ?1 AND m.stashed = ?2 order by m.modificationsOrder")
List<ModificationEntity> findAllStashedByGroupId(@Param("groupId") UUID groupId, @Param("stashed") Boolean stashed);
List<ModificationEntity> findAllByGroupId(@Param("groupId") UUID groupId, @Param("stashed") Boolean stashed);

@Query(value = "SELECT new ModificationEntity(m.id, m.type) FROM ModificationEntity m WHERE m.id IN (?1)")
List<ModificationEntity> findMetadataIn(List<UUID> uuids);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,6 @@ private void saveModificationsNonTransactional(UUID groupUuid, List<? extends Mo
for (ModificationEntity m : modifications) {
modificationGroupEntity.addModification(m);
m.setModificationsOrder(order);
// We need here to call the save() method on the modification entity cause the ids of the ModificationEntity's are used in further treatments in the same transaction.
// As we generate the id in Java with @GeneratedValue(strategy = GenerationType.AUTO), saving the entity in the JPA world is enough to generate the id (no need to flush it).
// Without the saving, the id generation would be done only at the flush() and wouldn't be available for the further treatments.
order++;
}
modificationRepository.saveAll(modifications);
Expand Down Expand Up @@ -420,36 +417,37 @@ public List<ModificationInfos> getActiveModificationsInfos(@NonNull UUID groupUu
@Transactional
public void stashNetworkModifications(@NonNull List<UUID> modificationUuids, int stashedModificationCount) {
int stashModificationOrder = -stashedModificationCount - 1;
List<ModificationEntity> modificationEntities = new ArrayList<>();
for (UUID modificationUuid : modificationUuids) {
ModificationEntity modificationEntity = this.modificationRepository
.findById(modificationUuid)
.orElseThrow(() -> new NetworkModificationException(MODIFICATION_NOT_FOUND, String.format(MODIFICATION_NOT_FOUND_MESSAGE, modificationUuid)));
modificationEntity.setStashed(true);
modificationEntity.setModificationsOrder(stashModificationOrder);
this.modificationRepository.save(modificationEntity);
modificationEntities.add(modificationEntity);
stashModificationOrder--;
}
this.modificationRepository.saveAll(modificationEntities);
}

@Transactional
public void reorderNetworkModifications(UUID groupId, Boolean stashed) {
List<ModificationEntity> entities = this.modificationRepository.findAllStashedByGroupId(groupId, stashed);
if (entities.isEmpty()) {
return;
}
if (Boolean.TRUE.equals(stashed)) {
IntStream.range(1, entities.size() + 1)
.forEach(i -> entities.get(i - 1).setModificationsOrder(-i));
} else {
IntStream.range(0, entities.size())
.forEach(i -> entities.get(i).setModificationsOrder(i));
List<ModificationEntity> entities = this.modificationRepository.findAllByGroupId(groupId, stashed);
if (!entities.isEmpty()) {
if (Boolean.TRUE.equals(stashed)) {
IntStream.range(1, entities.size() + 1)
.forEach(i -> entities.get(i - 1).setModificationsOrder(-i));
} else {
IntStream.range(0, entities.size())
.forEach(i -> entities.get(i).setModificationsOrder(i));
}
}
this.modificationRepository.saveAll(entities);
}

@Transactional
public void restoreNetworkModifications(@NonNull List<UUID> modificationUuids, int unStashedSize) {
int modificationOrder = unStashedSize;
public void restoreNetworkModifications(@NonNull List<UUID> modificationUuids, int unstashedSize) {
int modificationOrder = unstashedSize;
List<ModificationEntity> modifications = modificationRepository.findAllByIdInReverse(modificationUuids);
if (modifications.size() != modificationUuids.size()) {
throw new NetworkModificationException(MODIFICATION_NOT_FOUND);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public void reorderNetworkModifications(UUID groupId, Boolean stashed) {
}

@Transactional
public void restoreNetworkModifications(@NonNull List<UUID> modificationUuids, UUID groupUuid) {
public void restoreNetworkModifications(UUID groupUuid, @NonNull List<UUID> modificationUuids) {
networkModificationRepository.restoreNetworkModifications(modificationUuids,
networkModificationRepository.getModificationsCount(groupUuid, false));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
<changeSet author="etienne lesot" id="1726146482277-3">
<customChange class="org.gridsuite.modification.server.migration.ModificationOrderMigration"/>
</changeSet>
</databaseChangeLog>
3 changes: 3 additions & 0 deletions src/main/resources/db/changelog/db.changelog-master.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,6 @@ databaseChangeLog:
- include:
relativeToChangelogFile: true
file: changesets/changelog_20240912T130742Z.xml
- include:
relativeToChangelogFile: true
file: changesets/changelog_20241015T130742Z.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1316,7 +1316,7 @@ public void testStaticVarCompensatorCreation() {
.build().toEntity();

networkModificationRepository.saveModifications(TEST_GROUP_ID, List.of(createStaticVarCompensator1, createStaticVarCompensator2, createStaticVarCompensator3));
assertRequestsCount(1, 3, 1, 0);
assertRequestsCount(2, 3, 0, 0);

List<ModificationInfos> modificationInfos = networkModificationRepository.getModifications(TEST_GROUP_ID, true, true);
assertEquals(3, modificationInfos.size());
Expand All @@ -1331,7 +1331,7 @@ public void testStaticVarCompensatorCreation() {

SQLStatementCountValidator.reset();
networkModificationRepository.deleteModifications(TEST_GROUP_ID, List.of(createStaticVarCompensator2.getId(), createStaticVarCompensator3.getId()));
assertRequestsCount(4, 0, 1, 2);
assertRequestsCount(4, 0, 0, 2);

SQLStatementCountValidator.reset();
assertEquals(1, networkModificationRepository.getModifications(TEST_GROUP_ID, true, true).size());
Expand Down

0 comments on commit 388fcda

Please sign in to comment.