I have a simple power system as users can borrow to each other:
mysql_query("INSERT INTO power (sender, receiver, amount)
VALUES ('$sender', '$receiver', '$amount')");
mysql_query("UPDATE users SET power=power-$amount WHERE user_id='$sender'");
mysql_query("UPDATE users SET power=power+$amount WHERE user_id='$receiver'");
I check if the sender has enough credit to transfer by a SELECT query before running the above-mentioned set of queries.
Issues 1: I think, it is better to put all these four queries into a Transaction; as InnoDB ACID will guarantee a safer performance. What will be the best transaction to do so?
Issue 2: power is unsigned int. If by any chance (even unlikely), user does not have enough credit power-$amount will not set 0; instead it will be cycled through the largest value of int(), which is 4294967295. This means that the user will be granted almost unlimited power (credit).
First of all, don’t bother with this:
That leaves you open to a race condition that you’ll have to deal with anyway. Instead, set up constraints in your database to make it impossible to get into an invalid state.
Don’t do that either, there’s no need. A 4 byte signed integer should have more than enough space on the positive side; if it doesn’t, you can switch to a signed 8 byte integer. The reason you want a signed value is that it makes integrity checking fairly easy: if a balance drops below zero then something is wrong. If you use an unsigned value, you’d have to reserve
4294967295-n(for somen) to detect underflow and overflow instead of a simple< 0.As far as constraining your data is concerned, normally you’d use a CHECK constraint like this:
but MySQL doesn’t support CHECK constraints. However, you can write a BEFORE INSERT OR UPDATE trigger that can check that
new.power >= 0and raise an exception if it isn’t.Now you have a
userstable that doesn’t allow invalidpowervalues so we’re done with issue 2.On to issue 1: transactions. Yes, you absolutely do want to use a transaction for the transfer. You’ll want a sequence like this:
start transactionINSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')UPDATE users SET power=power-$amount WHERE user_id='$sender'UPDATE users SET power=power+$amount WHERE user_id='$receiver'rollbackto the database and tell the user what went wrong.committo the database.The transaction will ensure that all three operations will either succeed or fail as a single unit and the CHECK constraint (implemented as a trigger) ensures that no one can give away more power than they have.