Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
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)
11
UPDATE transaction.userwallethistory uwh
12
JOIN (
13
    SELECT id,
14
           SUM(amount) OVER (PARTITION BY wallet_id ORDER BY id) AS cumulative_balance
15
    FROM transaction.userwallethistory
16
) calc ON uwh.id = calc.id
17
SET uwh.running_balance = calc.cumulative_balance;
18
 
19
-- Step 3: Add index for efficient lookups by wallet_id + timestamp (used by wallet statement)
20
-- Not strictly required since the existing query already works, but helps if you ever
21
-- query running_balance directly
22
-- ALTER TABLE transaction.userwallethistory ADD INDEX idx_uwh_wallet_timestamp (wallet_id, timestamp);