Skip to content

Commit

Permalink
Optimize token balances filter
Browse files Browse the repository at this point in the history
  • Loading branch information
Groxan committed Nov 24, 2023
1 parent 3f36cd2 commit da14a8d
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion Tzkt.Api/Repositories/TokensRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,35 @@ async Task<IEnumerable<dynamic>> QueryTokenBalancesAsync(TokenBalanceFilter filt
return (new string[1] { @"tb.""Id""" }, @"tb.""Id""");
}

using var db = GetConnection();

#region optimizations
if (filter.balance?.Gt == "0" && filter.balance.Ne == null)
{
filter.balance.Gt = null;
filter.balance.Ne = "0";
}
if (filter.token?.contract?.Eq != null && filter.token.tokenId?.Eq != null && filter.token.id?.Eq == null)
{
var row = await db.QueryFirstOrDefaultAsync("""
SELECT "Id"
FROM "Tokens"
WHERE "ContractId" = @contractId
AND "TokenId" = @tokenId
LIMIT 1
""", new { contractId = filter.token.contract.Eq.Value, tokenId = filter.token.tokenId.Eq });

if (row == null)
return Enumerable.Empty<dynamic>();

filter.token.contract.Eq = null;
filter.token.tokenId.Eq = null;

filter.token.id ??= new();
filter.token.id.Eq = (long)row.id;
}
#endregion

var sql = new SqlBuilder($@"
SELECT {select} FROM ""TokenBalances"" as tb
INNER JOIN ""Tokens"" AS t ON t.""Id"" = tb.""TokenId""")
Expand Down Expand Up @@ -384,7 +413,6 @@ async Task<IEnumerable<dynamic>> QueryTokenBalancesAsync(TokenBalanceFilter filt
_ => TryMetaSort(x)
}, @"tb.""Id""");

using var db = GetConnection();
return await db.QueryAsync(sql.Query, sql.Params);
}

Expand Down

0 comments on commit da14a8d

Please sign in to comment.