Skip to content

Instantly share code, notes, and snippets.

@DeadAlready
Last active January 26, 2018 15:12
Show Gist options
  • Save DeadAlready/75c02f220967ce7fa854ec0c01b3c9b6 to your computer and use it in GitHub Desktop.
Save DeadAlready/75c02f220967ce7fa854ec0c01b3c9b6 to your computer and use it in GitHub Desktop.
An example of a transaction
'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