Path: redb/redb.Tests.Integration/Tests/Unit/MsSqlProFoldOrderSqlTests.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Tests.Integration/Tests/Unit/MsSqlProFoldOrderSqlTests.cs
----
using redb.Core.Query.Models;
using redb.MSSql.Pro.Query;
using redb.MSSql.Sql;
namespace redb.Tests.Integration.Tests.Unit;
///
/// The SQL Server pivot folds a collection field into one text with STRING_AGG over its element rows. Without an
/// order the rows are joined as the plan reads them, so equal lists could give different texts and DistinctBy or
/// OrderBy over the whole field depended on the plan. Every fold of the flat pivot names its order: a list by its
/// index as a number, a dictionary by its key.
///
public class MsSqlProFoldOrderSqlTests
{
private const string Order = "WITHIN GROUP (ORDER BY TRY_CAST(v2._array_index AS bigint), v2._array_index)";
[Fact]
public void EveryCollectionFoldOfThePivot_NamesItsOrder()
{
var fields = new List
{
new(101, "String", "_String", "Tags", IsArray: true),
new(102, "ListItem", "_ListItem", "Codes.Value", IsArray: true, ListItemProp: ListItemProperty.Value),
new(103, "ListItem", "_ListItem", "Codes.Alias", IsArray: true, ListItemProp: ListItemProperty.Alias),
new(104, "String", "_String", "Title"),
};
var sql = new PvtSqlGenerator(new MsSqlDialect()).GeneratePvtCte(fields, "1=1", "@p0").CteSql;
CountOf(sql, "STRING_AGG(").Should().Be(3, "the three collection fields are folded");
CountOf(sql, Order).Should().Be(3, "each fold joins its elements in index order");
}
private static int CountOf(string text, string part)
{
var count = 0;
for (var at = text.IndexOf(part, StringComparison.Ordinal); at >= 0; at = text.IndexOf(part, at + part.Length, StringComparison.Ordinal))
count++;
return count;
}
}