diff --git a/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs b/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs new file mode 100644 index 000000000..4eeeb717f --- /dev/null +++ b/src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Data; +using System.Linq; +using FluentMigrator; +using NzbDrone.Common.Extensions; +using NzbDrone.Core.Datastore.Migration.Framework; + +namespace NzbDrone.Core.Datastore.Migration +{ + [Migration(146)] + public class cleanup_duplicates_updatehistory : NzbDroneMigrationBase + { + protected override void LogDbUpgrade() + { + Execute.WithConnection(CleanupUpdateHistory); + } + + private void CleanupUpdateHistory(IDbConnection conn, IDbTransaction tran) + { + var toDelete = new List(); + + using (var cmdQuery = conn.CreateCommand()) + { + cmdQuery.Transaction = tran; + cmdQuery.CommandText = "SELECT Id, Version FROM UpdateHistory WHERE EventType = 2 ORDER BY Date"; + + var lastVersion = string.Empty; + using (var reader = cmdQuery.ExecuteReader()) + { + while (reader.Read()) + { + var id = reader.GetInt32(0); + var version = reader.GetString(1); + + if (lastVersion == version) + { + toDelete.Add(id); + } + + lastVersion = version; + } + } + } + + if (toDelete.Any()) + { + using (var cmdDelete = conn.CreateCommand()) + { + var ids = toDelete.Select(v => v.ToString()).Join(", "); + + cmdDelete.Transaction = tran; + cmdDelete.CommandText = $"DELETE FROM UpdateHistory WHERE Id IN ({ids})"; + + cmdDelete.ExecuteNonQuery(); + } + } + } + } +} \ No newline at end of file diff --git a/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs b/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs index 20ea5a239..66ae01fbd 100644 --- a/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs +++ b/src/NzbDrone.Core/Update/History/UpdateHistoryRepository.cs @@ -26,7 +26,7 @@ namespace NzbDrone.Core.Update.History public UpdateHistory LastInstalled() { var history = Query.Where(v => v.EventType == UpdateHistoryEventType.Installed) - .OrderBy(v => v.Date) + .OrderByDescending(v => v.Date) .Take(1) .FirstOrDefault(); @@ -36,7 +36,7 @@ namespace NzbDrone.Core.Update.History public UpdateHistory PreviouslyInstalled() { var history = Query.Where(v => v.EventType == UpdateHistoryEventType.Installed) - .OrderBy(v => v.Date) + .OrderByDescending(v => v.Date) .Skip(1) .Take(1) .FirstOrDefault();