Skip to content

Instantly share code, notes, and snippets.

@israelalagbe
Created October 12, 2023 18:23
Show Gist options
  • Save israelalagbe/7b159b9d72440fd67fd032c339e35318 to your computer and use it in GitHub Desktop.
Save israelalagbe/7b159b9d72440fd67fd032c339e35318 to your computer and use it in GitHub Desktop.
Select For Update Transaction using Sequelize Sample
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'root', 'password', {
host: 'localhost',
dialect: 'mysql'
});
const Account = sequelize.define('account', {
balance: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0
}
});
async function updateBalance(accountId, amount) {
const transaction = await sequelize.transaction();
try {
// Lock the account row for update
const account = await Account.findOne({
where: { id: accountId },
lock: transaction.LOCK.UPDATE,
transaction
});
console.log('Account balance before update:', account.balance);
await new Promise(resolve => setTimeout(resolve, 2000));
// Update the balance
account.balance += amount;
// Save and commit
await account.save({ transaction });
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
// Usage
(async () => {
await sequelize.sync({ force: true });
await Account.create({ balance: 100 });
// Transaction 1
updateBalance(1, -100).then(() => {
console.log('Transaction 1 completed');
}).catch(console.error);
// Transaction 2
updateBalance(1, 100).then(() => {
console.log('Transaction 2 completed');
}).catch(console.error);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment