| 36513 |
amit |
1 |
-- Migration: Add running_balance column to userwallethistory
|
|
|
2 |
-- Purpose: Store wallet balance after each transaction for instant ledger display
|
|
|
3 |
-- Date: 2026-05-10
|
|
|
4 |
|
|
|
5 |
-- Step 1: Add the column
|
|
|
6 |
ALTER TABLE transaction.userwallethistory
|
|
|
7 |
ADD COLUMN running_balance BIGINT NOT NULL DEFAULT 0;
|
|
|
8 |
|
|
|
9 |
-- Step 2: Backfill running_balance for all existing rows
|
|
|
10 |
-- Computes cumulative sum of amount per wallet_id ordered by id (chronological)
|
| 36515 |
amit |
11 |
-- Uses session variables (MySQL 5.7 compatible, no window functions)
|
|
|
12 |
SET @running := 0;
|
|
|
13 |
SET @prev_wallet := 0;
|
|
|
14 |
|
| 36513 |
amit |
15 |
UPDATE transaction.userwallethistory uwh
|
|
|
16 |
JOIN (
|
|
|
17 |
SELECT id,
|
| 36515 |
amit |
18 |
@running := IF(@prev_wallet = wallet_id, @running + amount, amount) AS cumulative_balance,
|
|
|
19 |
@prev_wallet := wallet_id
|
| 36513 |
amit |
20 |
FROM transaction.userwallethistory
|
| 36515 |
amit |
21 |
ORDER BY wallet_id, id
|
| 36513 |
amit |
22 |
) calc ON uwh.id = calc.id
|
|
|
23 |
SET uwh.running_balance = calc.cumulative_balance;
|
|
|
24 |
|
|
|
25 |
-- Step 3: Add index for efficient lookups by wallet_id + timestamp (used by wallet statement)
|
|
|
26 |
-- Not strictly required since the existing query already works, but helps if you ever
|
|
|
27 |
-- query running_balance directly
|
|
|
28 |
-- ALTER TABLE transaction.userwallethistory ADD INDEX idx_uwh_wallet_timestamp (wallet_id, timestamp);
|