From 3e082df21d4488042598cf6655935d7ebc501a20 Mon Sep 17 00:00:00 2001 From: ta264 Date: Tue, 1 Sep 2020 21:26:36 +0100 Subject: [PATCH] Fixed: Error fetching paged records from API without a sort key [common] --- .../Datastore/BasicRepositoryFixture.cs | 26 +++++++++++++++---- .../Datastore/BasicRepository.cs | 5 ++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs index 0740fa7ca..4618026e5 100644 --- a/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs +++ b/src/NzbDrone.Core.Test/Datastore/BasicRepositoryFixture.cs @@ -291,16 +291,32 @@ namespace NzbDrone.Core.Test.Datastore Subject.All().ToList().Should().BeEmpty(); } - [Test] - public void get_paged_should_work() + [TestCase(1, 2)] + [TestCase(2, 2)] + [TestCase(3, 1)] + public void get_paged_should_work(int page, int count) + { + Subject.InsertMany(_basicList); + var data = Subject.GetPaged(new PagingSpec() { Page = page, PageSize = 2, SortKey = "LastExecution", SortDirection = SortDirection.Descending }); + + data.Page.Should().Be(page); + data.PageSize.Should().Be(2); + data.TotalRecords.Should().Be(_basicList.Count); + data.Records.Should().BeEquivalentTo(_basicList.OrderByDescending(x => x.LastExecution).Skip((page - 1) * 2).Take(2)); + } + + [TestCase(1, 2)] + [TestCase(2, 2)] + [TestCase(3, 1)] + public void get_paged_should_work_with_null_sort_key(int page, int count) { Subject.InsertMany(_basicList); - var data = Subject.GetPaged(new PagingSpec() { Page = 0, PageSize = 2, SortKey = "LastExecution", SortDirection = SortDirection.Descending }); + var data = Subject.GetPaged(new PagingSpec() { Page = page, PageSize = 2, SortDirection = SortDirection.Descending }); - data.Page.Should().Be(0); + data.Page.Should().Be(page); data.PageSize.Should().Be(2); data.TotalRecords.Should().Be(_basicList.Count); - data.Records.Should().BeEquivalentTo(_basicList.OrderByDescending(x => x.LastExecution).Take(2)); + data.Records.Should().BeEquivalentTo(_basicList.OrderByDescending(x => x.Id).Skip((page - 1) * 2).Take(2)); } } } diff --git a/src/NzbDrone.Core/Datastore/BasicRepository.cs b/src/NzbDrone.Core/Datastore/BasicRepository.cs index 3f2b02a35..8367acf05 100644 --- a/src/NzbDrone.Core/Datastore/BasicRepository.cs +++ b/src/NzbDrone.Core/Datastore/BasicRepository.cs @@ -407,6 +407,11 @@ namespace NzbDrone.Core.Datastore { AddFilters(builder, pagingSpec); + if (pagingSpec.SortKey == null) + { + pagingSpec.SortKey = $"{_table}.{_keyProperty.Name}"; + } + var sortDirection = pagingSpec.SortDirection == SortDirection.Descending ? "DESC" : "ASC"; var pagingOffset = (pagingSpec.Page - 1) * pagingSpec.PageSize; builder.OrderBy($"{pagingSpec.SortKey} {sortDirection} LIMIT {pagingSpec.PageSize} OFFSET {pagingOffset}");