Skip to content

Commit c6a7c27

Browse files
committed
Use unnest + LATERAL join to fetch latest balances
Replace the multi-placeholder IN tuple query with an unnest($1, $2) approach and a LATERAL subquery to select the most recent balance per (account_hash, asset_id). Build separate accountHashes and assetIds arrays as query params instead of expanding pair placeholders. This simplifies parameter handling and reliably returns the latest balance (ORDER BY _id DESC LIMIT 1) for each requested pair.
1 parent 8928552 commit c6a7c27

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

packages/graphql/src/application/uc/IndexBalance.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,17 @@ export default class IndexBalance {
5353
pairs.map((p) => [`${p.accountHash}:${p.assetId}`, p]),
5454
).values(),
5555
];
56-
const placeholders = uniquePairs
57-
.map((_, i) => `($${i * 2 + 1}, $${i * 2 + 2})`)
58-
.join(', ');
59-
const params = uniquePairs.flatMap((p) => [p.accountHash, p.assetId]);
56+
const accountHashes = uniquePairs.map((p) => p.accountHash);
57+
const assetIds = uniquePairs.map((p) => p.assetId);
6058
const rows = await connection.query(
61-
`SELECT DISTINCT ON (account_hash, asset_id) account_hash, asset_id, balance
62-
FROM indexer.balance
63-
WHERE (account_hash, asset_id) IN (${placeholders})
64-
ORDER BY account_hash, asset_id, _id DESC`,
65-
params,
59+
`SELECT t.account_hash, t.asset_id, b.balance
60+
FROM unnest($1::text[], $2::text[]) AS t(account_hash, asset_id)
61+
JOIN LATERAL (
62+
SELECT balance FROM indexer.balance
63+
WHERE account_hash = t.account_hash AND asset_id = t.asset_id
64+
ORDER BY _id DESC LIMIT 1
65+
) b ON true`,
66+
[accountHashes, assetIds],
6667
);
6768
for (const row of rows) {
6869
balanceMap.set(

0 commit comments

Comments
 (0)