DEV Community

Nipu Chakraborty
Nipu Chakraborty

Posted on • Updated on

Database Transactions

What is Transaction?

A database transaction is a unit of work performed on a database that consists of multiple steps or operations. It is a fundamental concept in database systems and ensures the consistency and reliability of data.

In a transaction, a set of database operations is grouped together to form a single logical unit. These operations can include inserting, updating, deleting, or retrieving data from one or multiple database tables. The transaction can involve changes to multiple records or tables, and it represents a specific task or business operation.

Transactions follow the ACID properties, which stands for:

  1. Atomicity: A transaction is atomic, meaning that it is treated as a single indivisible unit of work. It either executes in its entirety, or none of its operations are applied to the database. If any operation fails within the transaction, the entire transaction is rolled back, and the database is restored to its state before the transaction started.

  2. Consistency: A transaction brings the database from one consistent state to another consistent state. It ensures that all integrity constraints, rules, and relationships defined in the database schema are maintained during the transaction. If a transaction violates any constraints, the database reverts to its original state.

  3. Isolation: Transactions execute in isolation from each other, as if they were the only ones operating on the database. This property ensures that concurrent transactions do not interfere with each other's intermediate results. It prevents issues such as dirty reads (reading uncommitted data), non-repeatable reads (reading different data in subsequent reads), and phantom reads (reading new rows that appear during a transaction).

  4. Durability: Once a transaction is committed and changes are applied to the database, they are permanent and survive any subsequent system failures. The committed data is stored securely and can be recovered in case of a crash, power outage, or any other catastrophic event.

Database transactions are crucial for maintaining data integrity, ensuring data consistency, and providing concurrency control in multi-user environments. They allow complex operations and modifications to be performed reliably and accurately on a database, even in the presence of concurrent access by multiple users or applications.

Let see an example with typescript and TypeORM

before start make a User entity with username, email and password

import { createConnection, getConnection } from "typeorm";
import { User } from "./entities/User";

async function performTransaction(): Promise<void> {
  // Create a new database connection
  const connection = await createConnection();

  // Start a transaction
  await connection.transaction(async (entityManager) => {
    try {
      // Create a new user
      const newUser = new User();
      newUser.username = "JohnDoe";
      newUser.email = "johndoe@example.com";
      newUser.password = "password123";

      // Save the user in the transaction
      await entityManager.save(newUser);

      // Update the user's email
      newUser.email = "john.doe@example.com";

      // Save the updated user in the transaction
      await entityManager.save(newUser);

      // Commit the transaction
      await entityManager.commit();

      console.log("Transaction committed successfully.");
    } catch (error) {
      // Rollback the transaction if an error occurs
      await entityManager.rollback();
      console.error("Transaction rolled back due to an error:", error);
    }
  });

  // Close the connection
  await getConnection().close();
}

// Call the transaction function
performTransaction().catch((error) => {
  console.error("Error occurred:", error);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)