Skip to content

Commit

Permalink
Merge pull request #86 from hunsra/hunsra-multiple-order-fix
Browse files Browse the repository at this point in the history
fix: #85
  • Loading branch information
acupofjose authored Jan 8, 2024
2 parents 20240e6 + 99704ec commit ce5f7d9
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
25 changes: 19 additions & 6 deletions Postgrest/Table.cs
Original file line number Diff line number Diff line change
Expand Up @@ -655,15 +655,28 @@ public string GenerateUrl()
foreach (var parsedFilter in _filters.Select(PrepareFilter))
query.Add(parsedFilter.Key, parsedFilter.Value);

foreach (var orderer in _orderers)
if (_orderers.Count > 0)
{
var nullPosAttr = orderer.NullPosition.GetAttribute<MapToAttribute>();
var orderingAttr = orderer.Ordering.GetAttribute<MapToAttribute>();
var order = new StringBuilder();

if (nullPosAttr == null || orderingAttr == null) continue;
foreach (var orderer in _orderers)
{
var nullPosAttr = orderer.NullPosition.GetAttribute<MapToAttribute>();
var orderingAttr = orderer.Ordering.GetAttribute<MapToAttribute>();

if (nullPosAttr == null || orderingAttr == null) continue;

if (order.Length > 0)
order.Append(",");

var selector = !string.IsNullOrEmpty(orderer.ForeignTable)
? orderer.ForeignTable + "(" + orderer.Column + ")"
: orderer.Column;

order.Append($"{selector}.{orderingAttr.Mapping}.{nullPosAttr.Mapping}");
}

var key = !string.IsNullOrEmpty(orderer.ForeignTable) ? $"{orderer.ForeignTable}.order" : "order";
query.Add(key, $"{orderer.Column}.{orderingAttr.Mapping}.{nullPosAttr.Mapping}");
query.Add("order", order.ToString());
}

if (!string.IsNullOrEmpty(_columnQuery))
Expand Down
17 changes: 15 additions & 2 deletions PostgrestTests/ClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -424,13 +424,26 @@ public async Task TestOrderBy()
{
var client = new Client(BaseUrl);

// Test with a single orderer specified
var orderedResponse = await client.Table<User>().Order("username", Ordering.Descending).Get();
var unorderedResponse = await client.Table<User>().Get();

var supaOrderedUsers = orderedResponse.Models;
var linqOrderedUsers = unorderedResponse.Models.OrderByDescending(u => u.Username).ToList();

CollectionAssert.AreEqual(linqOrderedUsers, supaOrderedUsers);
CollectionAssert.AreEqual(linqOrderedUsers, orderedResponse.Models);

// Test with multiple orderers specified
var multipleOrderedResponse = await client.Table<User>()
.Order(u => u.Username!, Ordering.Descending)
.Order(u => u.Status!, Ordering.Descending)
.Get();

linqOrderedUsers = unorderedResponse.Models
.OrderByDescending(u => u.Username)
.ThenByDescending(u => u.Status)
.ToList();

CollectionAssert.AreEqual(linqOrderedUsers, multipleOrderedResponse.Models);
}

[TestMethod("limit: basic")]
Expand Down

0 comments on commit ce5f7d9

Please sign in to comment.