Skip to content

Batch root inserts across aggregates #1228

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ private void execute(DbAction<?> action, JdbcAggregateChangeExecutionContext exe
try {
if (action instanceof DbAction.InsertRoot) {
executionContext.executeInsertRoot((DbAction.InsertRoot<?>) action);
} else if (action instanceof DbAction.BatchInsertRoot<?>) {
executionContext.executeBatchInsertRoot((DbAction.BatchInsertRoot<?>) action);
} else if (action instanceof DbAction.Insert) {
executionContext.executeInsert((DbAction.Insert<?>) action);
} else if (action instanceof DbAction.BatchInsert) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,20 @@ <T> void executeInsertRoot(DbAction.InsertRoot<T> insert) {
add(new DbActionExecutionResult(insert, id));
}

<T> void executeBatchInsertRoot(DbAction.BatchInsertRoot<T> batchInsertRoot) {

List<DbAction.InsertRoot<T>> inserts = batchInsertRoot.getActions();
List<InsertSubject<T>> insertSubjects = inserts.stream()
.map(insert -> InsertSubject.describedBy(insert.getEntity(), Identifier.empty())).collect(Collectors.toList());

Object[] ids = accessStrategy.insert(insertSubjects, batchInsertRoot.getEntityType(),
batchInsertRoot.getBatchValue());

for (int i = 0; i < inserts.size(); i++) {
add(new DbActionExecutionResult(inserts.get(i), ids.length > 0 ? ids[i] : null));
}
}

<T> void executeInsert(DbAction.Insert<T> insert) {

Identifier parentKeys = getParentKeys(insert, converter);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,32 @@ void batchInsertOperation_withoutGeneratedIds() {
assertThat(content.id).isNull();
}

@Test // GH-537
void batchInsertRootOperation_withGeneratedIds() {

when(accessStrategy.insert(singletonList(InsertSubject.describedBy(root, Identifier.empty())), DummyEntity.class, IdValueSource.GENERATED))
.thenReturn(new Object[] { 123L });
executionContext.executeBatchInsertRoot(new DbAction.BatchInsertRoot<>(singletonList(new DbAction.InsertRoot<>(root, IdValueSource.GENERATED))));

List<DummyEntity> newRoots = executionContext.populateIdsIfNecessary();

assertThat(newRoots).containsExactly(root);
assertThat(root.id).isEqualTo(123L);
}

@Test // GH-537
void batchInsertRootOperation_withoutGeneratedIds() {

when(accessStrategy.insert(singletonList(InsertSubject.describedBy(root, Identifier.empty())), DummyEntity.class, IdValueSource.PROVIDED))
.thenReturn(new Object[] { null });
executionContext.executeBatchInsertRoot(new DbAction.BatchInsertRoot<>(singletonList(new DbAction.InsertRoot<>(root, IdValueSource.PROVIDED))));

List<DummyEntity> newRoots = executionContext.populateIdsIfNecessary();

assertThat(newRoots).containsExactly(root);
assertThat(root.id).isNull();
}

@Test // GH-1201
void updates_whenReferencesWithImmutableIdAreInserted() {

Expand All @@ -177,7 +203,8 @@ void updates_whenReferencesWithImmutableIdAreInserted() {
Identifier identifier = Identifier.empty().withPart(SqlIdentifier.quoted("DUMMY_ENTITY"), 123L, Long.class);
when(accessStrategy.insert(contentImmutableId, ContentImmutableId.class, identifier, IdValueSource.GENERATED))
.thenReturn(456L);
executionContext.executeInsert(createInsert(rootUpdate, "contentImmutableId", contentImmutableId, null, IdValueSource.GENERATED));
executionContext.executeInsert(
createInsert(rootUpdate, "contentImmutableId", contentImmutableId, null, IdValueSource.GENERATED));

List<DummyEntity> newRoots = executionContext.populateIdsIfNecessary();
assertThat(newRoots).containsExactly(root);
Expand All @@ -197,7 +224,6 @@ void populatesIdsIfNecessaryForAllRootsThatWereProcessed() {
when(accessStrategy.insert(content1, Content.class, createBackRef(123L), IdValueSource.GENERATED)).thenReturn(11L);
executionContext.executeInsert(createInsert(rootUpdate1, "content", content1, null, IdValueSource.GENERATED));


DummyEntity root2 = new DummyEntity();
DbAction.InsertRoot<DummyEntity> rootInsert2 = new DbAction.InsertRoot<>(root2, IdValueSource.GENERATED);
when(accessStrategy.insert(root2, DummyEntity.class, Identifier.empty(), IdValueSource.GENERATED)).thenReturn(456L);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,18 @@ public BatchInsert(List<Insert<T>> actions) {
}
}

/**
* Represents a batch insert statement for a multiple entities that are aggregate roots.
*
* @param <T> type of the entity for which this represents a database interaction.
* @since 3.0
*/
final class BatchInsertRoot<T> extends BatchWithValue<T, InsertRoot<T>, IdValueSource> {
public BatchInsertRoot(List<InsertRoot<T>> actions) {
super(actions, InsertRoot::getIdValueSource);
}
}

/**
* An action depending on another action for providing additional information like the id of a parent entity.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public class SaveBatchingAggregateChange<T> implements BatchingAggregateChange<T
Comparator.comparing(PersistentPropertyPath::getLength);

private final Class<T> entityType;
private final List<DbAction.WithRoot<?>> rootActions = new ArrayList<>();
private final List<DbAction<?>> rootActions = new ArrayList<>();
private final List<DbAction.InsertRoot<T>> insertRootBatchCandidates = new ArrayList<>();
private final Map<PersistentPropertyPath<RelationalPersistentProperty>, Map<IdValueSource, List<DbAction.Insert<Object>>>> insertActions = //
new HashMap<>();
private final Map<PersistentPropertyPath<RelationalPersistentProperty>, List<DbAction.Delete<?>>> deleteActions = //
Expand All @@ -69,11 +70,15 @@ public void forEachAction(Consumer<? super DbAction<?>> consumer) {
Assert.notNull(consumer, "Consumer must not be null.");

rootActions.forEach(consumer);
if (insertRootBatchCandidates.size() > 1) {
consumer.accept(new DbAction.BatchInsertRoot<>(insertRootBatchCandidates));
} else {
insertRootBatchCandidates.forEach(consumer);
}
deleteActions.entrySet().stream().sorted(Map.Entry.comparingByKey(pathLengthComparator.reversed()))
.forEach((entry) -> entry.getValue().forEach(consumer));
insertActions.entrySet().stream().sorted(Map.Entry.comparingByKey(pathLengthComparator))
.forEach((entry) -> entry.getValue()
.forEach((idValueSource, inserts) -> {
insertActions.entrySet().stream().sorted(Map.Entry.comparingByKey(pathLengthComparator)).forEach((entry) -> entry
.getValue().forEach((idValueSource, inserts) -> {
if (inserts.size() > 1) {
consumer.accept(new DbAction.BatchInsert<>(inserts));
} else {
Expand All @@ -86,28 +91,44 @@ public void forEachAction(Consumer<? super DbAction<?>> consumer) {
public void add(RootAggregateChange<T> aggregateChange) {

aggregateChange.forEachAction(action -> {
if (action instanceof DbAction.WithRoot<?> rootAction) {
if (action instanceof DbAction.UpdateRoot<?> rootAction) {
commitBatchCandidates();
rootActions.add(rootAction);
} else if (action instanceof DbAction.Insert<?>) {
} else if (action instanceof DbAction.InsertRoot<?> rootAction) {
if (!insertRootBatchCandidates.isEmpty() && !insertRootBatchCandidates.get(0).getIdValueSource().equals(rootAction.getIdValueSource())) {
commitBatchCandidates();
}
//noinspection unchecked
insertRootBatchCandidates.add((DbAction.InsertRoot<T>) rootAction);
} else if (action instanceof DbAction.Insert<?> insertAction) {
// noinspection unchecked
addInsert((DbAction.Insert<Object>) action);
addInsert((DbAction.Insert<Object>) insertAction);
} else if (action instanceof DbAction.Delete<?> deleteAction) {
addDelete(deleteAction);
}
});
}

private void commitBatchCandidates() {

if (insertRootBatchCandidates.size() > 1) {
rootActions.add(new DbAction.BatchInsertRoot<>(List.copyOf(insertRootBatchCandidates)));
} else {
rootActions.addAll(insertRootBatchCandidates);
}
insertRootBatchCandidates.clear();
}

private void addInsert(DbAction.Insert<Object> action) {

PersistentPropertyPath<RelationalPersistentProperty> propertyPath = action.getPropertyPath();
insertActions.merge(propertyPath,
new HashMap<>(singletonMap(action.getIdValueSource(), new ArrayList<>(singletonList(action)))),
(map, mapDefaultValue) -> {
map.merge(action.getIdValueSource(), new ArrayList<>(singletonList(action)),
(actions, listDefaultValue) -> {
actions.add(action);
return actions;
});
map.merge(action.getIdValueSource(), new ArrayList<>(singletonList(action)), (actions, listDefaultValue) -> {
actions.add(action);
return actions;
});
return map;
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ static Class<?> actualEntityType(DbAction a) {
@Nullable
static IdValueSource insertIdValueSource(DbAction<?> action) {

if (action instanceof DbAction.InsertRoot) {
return ((DbAction.InsertRoot<?>) action).getIdValueSource();
} else if (action instanceof DbAction.Insert) {
return ((DbAction.Insert<?>) action).getIdValueSource();
if (action instanceof DbAction.WithEntity<?>) {
return ((DbAction.WithEntity<?>) action).getIdValueSource();
} else if (action instanceof DbAction.BatchInsert) {
return ((DbAction.BatchInsert<?>) action).getBatchValue();
} else if (action instanceof DbAction.BatchInsertRoot<?>) {
return ((DbAction.BatchInsertRoot<?>) action).getBatchValue();
} else {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public void newReferenceTriggersDeletePlusInsert() {
DbActionTestSupport::isWithDependsOn, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, SingleReferenceEntity.class, "", SingleReferenceEntity.class, false, null), //
tuple(UpdateRoot.class, SingleReferenceEntity.class, "", SingleReferenceEntity.class, false, IdValueSource.PROVIDED), //
tuple(Delete.class, Element.class, "other", null, false, null), //
tuple(Insert.class, Element.class, "other", Element.class, true, IdValueSource.GENERATED) //
);
Expand Down Expand Up @@ -371,7 +371,7 @@ public void cascadingReferencesTriggerCascadingActionsForUpdate() {
DbActionTestSupport::isWithDependsOn, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, CascadingReferenceEntity.class, "", CascadingReferenceEntity.class, false, null), //
tuple(UpdateRoot.class, CascadingReferenceEntity.class, "", CascadingReferenceEntity.class, false, IdValueSource.PROVIDED), //
tuple(Delete.class, Element.class, "other.element", null, false, null),
tuple(Delete.class, CascadingReferenceMiddleElement.class, "other", null, false, null),
tuple(Insert.class, CascadingReferenceMiddleElement.class, "other", CascadingReferenceMiddleElement.class,
Expand Down Expand Up @@ -530,7 +530,7 @@ public void mapTriggersDeletePlusInsert() {
DbActionTestSupport::extractPath, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, MapContainer.class, null, "", null), //
tuple(UpdateRoot.class, MapContainer.class, null, "", IdValueSource.PROVIDED), //
tuple(Delete.class, Element.class, null, "elements", null), //
tuple(Insert.class, Element.class, "one", "elements", IdValueSource.GENERATED) //
);
Expand All @@ -553,7 +553,7 @@ public void listTriggersDeletePlusInsert() {
DbActionTestSupport::extractPath, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, ListContainer.class, null, "", null), //
tuple(UpdateRoot.class, ListContainer.class, null, "", IdValueSource.PROVIDED), //
tuple(Delete.class, Element.class, null, "elements", null), //
tuple(Insert.class, Element.class, 0, "elements", IdValueSource.GENERATED) //
);
Expand All @@ -578,7 +578,7 @@ public void multiLevelQualifiedReferencesWithId() {
DbActionTestSupport::extractPath, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, ListMapContainer.class, null, null, "", null), //
tuple(UpdateRoot.class, ListMapContainer.class, null, null, "", IdValueSource.PROVIDED), //
tuple(Delete.class, Element.class, null, null, "maps.elements", null), //
tuple(Delete.class, MapContainer.class, null, null, "maps", null), //
tuple(Insert.class, MapContainer.class, 0, null, "maps", IdValueSource.PROVIDED), //
Expand Down Expand Up @@ -606,7 +606,7 @@ public void multiLevelQualifiedReferencesWithOutId() {
DbActionTestSupport::extractPath, //
DbActionTestSupport::insertIdValueSource) //
.containsExactly( //
tuple(UpdateRoot.class, NoIdListMapContainer.class, null, null, "", null), //
tuple(UpdateRoot.class, NoIdListMapContainer.class, null, null, "", IdValueSource.PROVIDED), //
tuple(Delete.class, NoIdElement.class, null, null, "maps.elements", null), //
tuple(Delete.class, NoIdMapContainer.class, null, null, "maps", null), //
tuple(Insert.class, NoIdMapContainer.class, 0, null, "maps", IdValueSource.NONE), //
Expand Down
Loading