Have you had experience working with transaction management mechanisms in SQL databases?
sobes.tech AI
Answer from AI
Yes, managing transactions is an important aspect of working with SQL databases to ensure data integrity.
A transaction is a sequence of operations that are executed as a single unit: either all operations complete successfully (commit), or in case of an error, all changes are rolled back (rollback).
In Node.js, libraries such as sequelize or knex are often used to manage transactions. Here's an example using knex:
const knex = require('knex')({ client: 'pg', connection: process.env.PG_CONNECTION_STRING });
async function transferFunds(fromAccount, toAccount, amount) {
await knex.transaction(async trx => {
const fromBalance = await trx('accounts').where('id', fromAccount).select('balance').first();
if (fromBalance.balance < amount) throw new Error('Insufficient funds');
await trx('accounts').where('id', fromAccount).decrement('balance', amount);
await trx('accounts').where('id', toAccount).increment('balance', amount);
});
}
In this example, all operations within the transaction will either succeed together or, in case of an error, all changes will be rolled back, ensuring data consistency.
Thus, experience working with transactions includes understanding ACID properties and knowing how to use APIs for managing commit and rollback.