From ad9e709d96a4c8635f52e9ee8623fa805e628de6 Mon Sep 17 00:00:00 2001 From: Taloth Saldono Date: Sun, 15 Nov 2020 13:16:15 +0100 Subject: [PATCH] Fixed duplicate UpdateHistory items --- .../146_cleanup_duplicates_updatehistory.cs | 59 +++++++++++++++++++ .../Update/History/UpdateHistoryRepository.cs | 4 +- 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 src/NzbDrone.Core/Datastore/Migration/146_cleanup_duplicates_updatehistory.cs 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();