Sobes.tech
Junior — Middle

Have you worked with transaction management mechanisms when executing SQL queries?

sobes.tech AI

Answer from AI

Yes, transaction management mechanisms are often used in Node.js when working with databases, especially with relational DBMSs (e.g., PostgreSQL, MySQL).

Transactions ensure the atomicity of operations — either all changes are successfully applied, or in case of an error, they are rolled back to maintain data integrity.

An example using the pg library for PostgreSQL:

const { Client } = require('pg');

async function runTransaction() {
  const client = new Client();
  await client.connect();

  try {
    await client.query('BEGIN');
    await client.query('INSERT INTO users(name) VALUES($1)', ['Alice']);
    await client.query('UPDATE accounts SET balance = balance - 100 WHERE user_id = $1', [1]);
    await client.query('COMMIT');
  } catch (e) {
    await client.query('ROLLBACK');
    throw e;
  } finally {
    await client.end();
  }
}

Thus, transactions allow controlling the execution of multiple related queries as a single operation.

Have you worked with transaction management… - sobes.tech