order all zap recipients

This commit is contained in:
keyan 2024-07-26 12:25:48 -05:00
parent 3d1f7834ca
commit 4964e2c7d1

View File

@ -74,23 +74,22 @@ export async function onPaid ({ invoice, actIds }, { models, tx }) {
SELECT "userId", ((${itemAct.msats}::BIGINT * pct) / 100)::BIGINT AS msats SELECT "userId", ((${itemAct.msats}::BIGINT * pct) / 100)::BIGINT AS msats
FROM "ItemForward" FROM "ItemForward"
WHERE "itemId" = ${itemAct.itemId}::INTEGER WHERE "itemId" = ${itemAct.itemId}::INTEGER
ORDER BY "userId" ASC -- order to prevent deadlocks
), total_forwarded AS ( ), total_forwarded AS (
SELECT COALESCE(SUM(msats), 0) as msats SELECT COALESCE(SUM(msats), 0) as msats
FROM forwardees FROM forwardees
), forward AS ( ), recipients AS (
UPDATE users SELECT "userId", msats FROM forwardees
SET UNION
msats = users.msats + forwardees.msats, SELECT ${itemAct.item.userId}::INTEGER as "userId",
"stackedMsats" = users."stackedMsats" + forwardees.msats ${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT as msats
FROM forwardees ORDER BY "userId" ASC -- order to prevent deadlocks
WHERE users.id = forwardees."userId"
) )
UPDATE users UPDATE users
SET SET
msats = msats + ${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT, msats = users.msats + recipients.msats,
"stackedMsats" = "stackedMsats" + ${itemAct.msats}::BIGINT - (SELECT msats FROM total_forwarded)::BIGINT "stackedMsats" = users."stackedMsats" + recipients.msats
WHERE id = ${itemAct.item.userId}::INTEGER` FROM recipients
WHERE users.id = recipients."userId"`
// perform denomormalized aggregates: weighted votes, upvotes, msats, lastZapAt // perform denomormalized aggregates: weighted votes, upvotes, msats, lastZapAt
// NOTE: for the rows that might be updated by a concurrent zap, we use UPDATE for implicit locking // NOTE: for the rows that might be updated by a concurrent zap, we use UPDATE for implicit locking