Last active
January 26, 2018 15:12
-
-
Save DeadAlready/75c02f220967ce7fa854ec0c01b3c9b6 to your computer and use it in GitHub Desktop.
An example of a transaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const {query} = require('./mysql-wrapper'); | |
const sql = ` | |
START TRANSACTION; | |
# Calculate balance | |
SELECT @balance := SUM(amount) FROM transactions WHERE accountId = 1 FOR UPDATE; | |
# Compare balance with the amount we want to withdraw | |
SET @finalAmount = IF(@balance >= 100, -100, NULL); | |
# If our balance was too low then this will fail as NULL is not allowed as transaction amount | |
INSERT INTO transactions (amount, accountId) VALUES (@finalAmount, 1); | |
COMMIT; | |
`; | |
query({sql}) | |
.then(result => { | |
console.log('Success', result); | |
}) | |
.catch(err => { | |
console.error('Failed', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment