Skip to content
Merged
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 @@ -248,7 +248,15 @@ public static async ValueTask<Page<T>> ToPageAsync<T>(

if (builder.Count == 0)
{
return Page<T>.Empty;
if (includeTotalCount)
{
TryGetQueryInterceptor()?.OnBeforeExecute(originalQuery);
totalCount = await originalQuery.CountAsync(cancellationToken).ConfigureAwait(false);
}

return totalCount is null
? Page<T>.Empty
: Page<T>.Create([], false, false, _ => string.Empty, totalCount);
}

if (isBackward)
Expand Down Expand Up @@ -534,14 +542,18 @@ public static async ValueTask<Dictionary<TKey, Page<TValue>>> ToBatchPageAsync<T
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
var totalCount = counts?.GetValueOrDefault(item.Key) ?? batchExpression.Cursor?.TotalCount;

if (item.Items.Count == 0)
{
map.Add(item.Key, Page<TValue>.Empty);
var page = totalCount is null
? Page<TValue>.Empty
: Page<TValue>.Create([], false, false, _ => string.Empty, totalCount);
map.Add(item.Key, page);
continue;
}

var itemCount = requestedCount > item.Items.Count ? item.Items.Count : requestedCount;
var totalCount = counts?.GetValueOrDefault(item.Key) ?? batchExpression.Cursor?.TotalCount;
var pageIndex = CreateIndex(arguments, batchExpression.Cursor, totalCount);

if (valueSelector is not null)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,288 @@
using System.Data.Common;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using XunitTestContext = Xunit.TestContext;

namespace GreenDonut.Data;

public class PagingTotalCountTests
{
[Fact]
public async Task ToPageAsync_Should_ReturnZeroTotalCount_When_FilteredDataSetIsEmpty()
{
await using var database = await TestDatabase.CreateAsync(2);

var page = await database.Query.Where(t => t.Id < 0).ToPageAsync(
new PagingArguments(first: 2, includeTotalCount: true),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 0,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 2
}
""");
}

[Fact]
public async Task ToPageAsync_Should_PreserveCursorTotalCount_When_CountIsNotRequested()
{
await using var database = await TestDatabase.CreateAsync(2);
var firstPage = await database.Query.ToPageAsync(
new PagingArguments(first: 2) { EnableRelativeCursors = true },
XunitTestContext.Current.CancellationToken);
var cursor = firstPage.CreateCursor(firstPage.Last!.Value, 0);
database.ResetCountQueryCount();

var page = await database.Query.ToPageAsync(
new PagingArguments(first: 2, after: cursor),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 2,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 0
}
""");
}

[Fact]
public async Task ToPageAsync_Should_ReturnDataSetCount_When_PageAfterLastItemIsEmpty()
{
await using var database = await TestDatabase.CreateAsync(2);
var firstPage = await database.Query.ToPageAsync(
new PagingArguments(first: 2),
XunitTestContext.Current.CancellationToken);
var cursor = firstPage.CreateCursor(firstPage.Last!.Value);
database.ResetCountQueryCount();

var page = await database.Query.ToPageAsync(
new PagingArguments(first: 2, after: cursor, includeTotalCount: true),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 2,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 2
}
""");
}

[Fact]
public async Task ToPageAsync_Should_ReturnDataSetCount_When_PageBeforeFirstItemIsEmpty()
{
await using var database = await TestDatabase.CreateAsync(2);
var firstPage = await database.Query.ToPageAsync(
new PagingArguments(first: 2),
XunitTestContext.Current.CancellationToken);
var cursor = firstPage.CreateCursor(firstPage.First!.Value);
database.ResetCountQueryCount();

var page = await database.Query.ToPageAsync(
new PagingArguments(last: 2, before: cursor, includeTotalCount: true),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 2,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 2
}
""");
}

[Fact]
public async Task ToPageAsync_Should_LeaveTotalCountUnknown_When_CountIsNotRequested()
{
await using var database = await TestDatabase.CreateAsync(0);

var page = await database.Query.ToPageAsync(
new PagingArguments(first: 2),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": null,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 0
}
""");
}

[Fact]
public async Task ToPageAsync_Should_UseCombinedCountQuery_When_PageIsNotEmpty()
{
await using var database = await TestDatabase.CreateAsync(2);

var page = await database.Query.ToPageAsync(
new PagingArguments(first: 1, includeTotalCount: true),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(page, database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 2,
"HasNextPage": true,
"HasPreviousPage": false,
"Items": [
1
],
"CountQueryCount": 1
}
""");
}

[Fact]
public async Task ToBatchPageAsync_Should_PreserveTotalCount_When_PageAfterLastItemIsEmpty()
{
await using var database = await TestDatabase.CreateAsync(2);
var firstPage = await database.Query.ToPageAsync(
new PagingArguments(first: 2),
XunitTestContext.Current.CancellationToken);
var cursor = firstPage.CreateCursor(firstPage.Last!.Value);
database.ResetCountQueryCount();

var pages = await database.Query.ToBatchPageAsync(
t => t.GroupId,
new PagingArguments(first: 2, after: cursor, includeTotalCount: true),
XunitTestContext.Current.CancellationToken);

CreateSnapshot(pages[1], database.CountQueryCount).MatchInlineSnapshot(
"""
{
"TotalCount": 2,
"HasNextPage": false,
"HasPreviousPage": false,
"Items": [],
"CountQueryCount": 1
}
""");
}

private static object CreateSnapshot(Page<Item> page, int countQueryCount)
=> new
{
page.TotalCount,
page.HasNextPage,
page.HasPreviousPage,
Items = page.Select(t => t.Id).ToArray(),
CountQueryCount = countQueryCount
};

private sealed class TestDatabase : IAsyncDisposable
{
private readonly SqliteConnection _connection;
private readonly CommandCounter _commandCounter;
private readonly PagingContext _context;

private TestDatabase(
SqliteConnection connection,
CommandCounter commandCounter,
PagingContext context)
{
_connection = connection;
_commandCounter = commandCounter;
_context = context;
}

public IQueryable<Item> Query => _context.Items.OrderBy(t => t.Id);

public int CountQueryCount => _commandCounter.Count;

public static async Task<TestDatabase> CreateAsync(int itemCount)
{
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync(XunitTestContext.Current.CancellationToken);

var commandCounter = new CommandCounter();
var options = new DbContextOptionsBuilder<PagingContext>()
.UseSqlite(connection)
.AddInterceptors(commandCounter)
.Options;
var context = new PagingContext(options);
await context.Database.EnsureCreatedAsync(XunitTestContext.Current.CancellationToken);

for (var i = 1; i <= itemCount; i++)
{
context.Items.Add(new Item { Id = i, GroupId = 1 });
}

await context.SaveChangesAsync(XunitTestContext.Current.CancellationToken);
commandCounter.Reset();
return new TestDatabase(connection, commandCounter, context);
}

public void ResetCountQueryCount() => _commandCounter.Reset();

public async ValueTask DisposeAsync()
{
await _context.DisposeAsync();
await _connection.DisposeAsync();
}
}

private sealed class PagingContext(DbContextOptions<PagingContext> options) : DbContext(options)
{
public DbSet<Item> Items => Set<Item>();
}

private sealed class Item
{
public int Id { get; set; }

public int GroupId { get; set; }
}

private sealed class CommandCounter : DbCommandInterceptor
{
public int Count { get; private set; }

public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
CountQuery(command);
return result;
}

public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result,
CancellationToken cancellationToken = default)
{
CountQuery(command);
return ValueTask.FromResult(result);
}

public void Reset() => Count = 0;

private void CountQuery(DbCommand command)
{
if (command.CommandText.Contains("COUNT(", StringComparison.OrdinalIgnoreCase))
{
Count++;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ public override IReadOnlyList<PageEdge<TNode>>? Edges
/// Identifies the total count of items in the connection.
/// </summary>
[GraphQLDescription("Identifies the total count of items in the connection.")]
public int TotalCount => _page.TotalCount ?? -1;
[GraphQLType<NonNullType<IntType>>]
public int? TotalCount => _page.TotalCount;

/// <summary>
/// Converts a <see cref="Page{TNode}"/> to a <see cref="PageConnection{TNode}"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,8 @@ namespace TestNamespace
var naming = field.Context.Naming;

configuration.Description = GetDescription("Identifies the total count of items in the connection.", false, field.Context.Options.UseXmlDocumentation);
configuration.Type = global::HotChocolate.Types.Descriptors.TypeReference.Create(
typeInspector.GetTypeRef(typeof(int), HotChocolate.Types.TypeContext.Output),
new global::HotChocolate.Language.NonNullTypeNode(new global::HotChocolate.Language.NamedTypeNode("int")));
configuration.ResultType = typeof(int);
configuration.Type = typeInspector.GetTypeRef(typeof(global::HotChocolate.Types.NonNullType<global::HotChocolate.Types.IntType>), HotChocolate.Types.TypeContext.Output);
configuration.ResultType = typeof(int?);
configuration.DeclaringType = context.ThisType;

configuration.SetSourceGeneratorFlags();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,10 +136,8 @@ namespace TestNamespace
var naming = field.Context.Naming;

configuration.Description = GetDescription("Identifies the total count of items in the connection.", false, field.Context.Options.UseXmlDocumentation);
configuration.Type = global::HotChocolate.Types.Descriptors.TypeReference.Create(
typeInspector.GetTypeRef(typeof(int), HotChocolate.Types.TypeContext.Output),
new global::HotChocolate.Language.NonNullTypeNode(new global::HotChocolate.Language.NamedTypeNode("int")));
configuration.ResultType = typeof(int);
configuration.Type = typeInspector.GetTypeRef(typeof(global::HotChocolate.Types.NonNullType<global::HotChocolate.Types.IntType>), HotChocolate.Types.TypeContext.Output);
configuration.ResultType = typeof(int?);
configuration.DeclaringType = context.ThisType;

configuration.SetSourceGeneratorFlags();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,8 @@ namespace TestNamespace
var naming = field.Context.Naming;

configuration.Description = GetDescription("Identifies the total count of items in the connection.", false, field.Context.Options.UseXmlDocumentation);
configuration.Type = global::HotChocolate.Types.Descriptors.TypeReference.Create(
typeInspector.GetTypeRef(typeof(int), HotChocolate.Types.TypeContext.Output),
new global::HotChocolate.Language.NonNullTypeNode(new global::HotChocolate.Language.NamedTypeNode("int")));
configuration.ResultType = typeof(int);
configuration.Type = typeInspector.GetTypeRef(typeof(global::HotChocolate.Types.NonNullType<global::HotChocolate.Types.IntType>), HotChocolate.Types.TypeContext.Output);
configuration.ResultType = typeof(int?);
configuration.DeclaringType = context.ThisType;

configuration.SetSourceGeneratorFlags();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,8 @@ namespace TestNamespace
var naming = field.Context.Naming;

configuration.Description = GetDescription("Identifies the total count of items in the connection.", false, field.Context.Options.UseXmlDocumentation);
configuration.Type = global::HotChocolate.Types.Descriptors.TypeReference.Create(
typeInspector.GetTypeRef(typeof(int), HotChocolate.Types.TypeContext.Output),
new global::HotChocolate.Language.NonNullTypeNode(new global::HotChocolate.Language.NamedTypeNode("int")));
configuration.ResultType = typeof(int);
configuration.Type = typeInspector.GetTypeRef(typeof(global::HotChocolate.Types.NonNullType<global::HotChocolate.Types.IntType>), HotChocolate.Types.TypeContext.Output);
configuration.ResultType = typeof(int?);
configuration.DeclaringType = context.ThisType;

configuration.SetSourceGeneratorFlags();
Expand Down
Loading