I have a table like the following:
transaction_id
user_id
other_user_id
trans_type
amount
This table is used to maintain the account transa
The problem is that the concept of the "user account" is "scattered" through many rows in your table. With the current representation, I think you can't "lock the user account" (so to speak), so you are open to race conditions when modifying them.
A possible solution would be to have another table with user accounts, and lock a row in that table , so anybody needing to modify the account can try to obtain the lock, do the operation, and release the lock.
For instance:
begin transaction;
update db.accounts set lock=1 where account_id='Bob' and lock=0;
if (update is NOT successful) # lock wasn't on zero
{
rollback;
return;
}
if (Bob hasn't enough funds)
{
rollback;
return;
}
insert into db.transactions value (?, 'Bob', 'Alice', 'Sent', -3000);
insert into db.transactions value (?, 'Alice', 'Bob', 'Received', 3000);
update db.accounts set lock=0 where account_id='Bob' and lock=1;
commit;
... or something like that.