SQL 16 MySQL Transactions
SQL 16 MySQL Transactions
http://en.wikipedia.org/wiki/
Transaction_processing
Transactions and MySQL
ATM ATM
Bank
Balance:
200
ATM ATM
Balance:
200
Bank
Balance:
200
ATM ATM
Balance: Balance:
200 200
Bank
Balance:
200
ATM ATM
Balance: Balance:
200 200
Bank
Balance:
100
ATM ATM
Balance: Balance:
100 200
$100
Bank
Balance:
100
ATM ATM
Balance: Balance:
100 100
$100 $100
Bank
Balance:
100
ATM ATM
Balance: Balance:
100 100
• SELECT .... FOR UPDATE – Reads and locks row (or rows)
mysql>
BEGIN;
SELECT balance FROM accounts WHERE number=12345 FOR UPDATE;
UPDATE accounts SET balance=balance+25 WHERE number=12345;
COMMIT;
mysql>
mysql> BEGIN;
mysql> UPDATE accounts SET balance=balance-250 WHERE number=12345;
mysql> UPDATE accounts SET balance=balance+250 WHERE number=67890;
mysql> SELECT * FROM accounts;
+--------+---------+
| number | balance |
+--------+---------+
| 12345 | 800 |
| 67890 | 390 |
+--------+---------+
mysql> ROLLBACK;
Query OK, 0 rows affected (0.34 sec)
SELECT waits
Transaction started
but not committed.
SELECT timeout
Transaction started
but not committed.
UPDATE waits
Transaction
committed.
UPDATE completes
instantly
Balances properly
reflect both
reductions
Transaction Deadlock
• Deadlocks are avoided by making sure all transactions take locks in the
same order - this way one will “win” at the beginning.
Start two
transactions and lock
two accounts
Attempt to lock an
account but need to
wait....
Attempt to lock an
already locked
account - deadlock
First transaction
aborted so second
select immediately
gets lock
tsugi/samples/rps/play.php
$pdo->beginTransaction();
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ( $row == FALSE ) {
$pdo->rollBack();
} else {
$stmt1->execute(array(":U2ID" => $_SESSION['id'], ":PLAY" => $play,
":GUID" => $row['rps_guid']));
$pdo->commit();
}
Transaction Trade-offs
• Transactions are essential in situations where data is read, updated, and
written in a way that timing is critical.
• But transactions incur a cost because they lock areas of the database
and pause other operations waiting for the transaction to finish.
• M ySQL transactions
• Transaction trade-offs
Acknowledgements / Contributions
These slides are Copyright 2010- Charles R. Severance (www.dr- Continue new Contributors and Translators here
chuck.com) as part of www.wa4e.com and made available under a
Creative Commons Attribution 4.0 License. Please maintain this
last slide in all copies of the document to comply with the
attribution requirements of the license. If you make a change, feel
free to add your name and organization to the list of contributors on
this page as you republish the materials.