Skip to content
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

Always sort deletes before inserts for the same table to avoid deadlocks. #25952

Merged
merged 1 commit into from
Sep 10, 2021
Merged
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
Always sort deletes before inserts for the same table to avoid deadlo…
…cks.

This dependency isn't hard, so cycle breaking is introduced.
Make the implementations of Multigraph TopologicalSort and BatchingTopologicalSort more alike and faster

Fixes #14371
AndriySvyryd committed Sep 9, 2021
commit 4ecc826de0424e5804614f3fcd1864214c66624e
31 changes: 30 additions & 1 deletion src/EFCore.Relational/Update/Internal/CommandBatchPreparer.cs
Original file line number Diff line number Diff line change
@@ -287,7 +287,9 @@ protected virtual IReadOnlyList<List<IReadOnlyModificationCommand>> TopologicalS

AddUniqueValueEdges(modificationCommandGraph);

return modificationCommandGraph.BatchingTopologicalSort(FormatCycle);
AddSameTableEdges(modificationCommandGraph);

return modificationCommandGraph.BatchingTopologicalSort(static (_, _, edges) => edges.All(e => e is IEntityType), FormatCycle);
}

private string FormatCycle(IReadOnlyList<Tuple<IReadOnlyModificationCommand, IReadOnlyModificationCommand, IEnumerable<IAnnotatable>>> data)
@@ -765,5 +767,32 @@ private void AddUniqueValueEdges(Multigraph<IReadOnlyModificationCommand, IAnnot
}
}
}

private static void AddSameTableEdges(Multigraph<IReadOnlyModificationCommand, IAnnotatable> modificationCommandGraph)
{
var deletedDictionary = new Dictionary<(string, string?), List<IReadOnlyModificationCommand>>();

foreach (var command in modificationCommandGraph.Vertices)
{
if (command.EntityState == EntityState.Deleted)
{
deletedDictionary.GetOrAddNew((command.TableName, command.Schema)).Add(command);
}
}

foreach (var command in modificationCommandGraph.Vertices)
{
if (command.EntityState == EntityState.Added)
{
if (deletedDictionary.TryGetValue((command.TableName, command.Schema), out var deletedList))
{
foreach (var deleted in deletedList)
{
modificationCommandGraph.AddEdge(deleted, command, command.Entries[0].EntityType);
}
}
}
}
}
}
}
Loading