Must know concept for Backend Developers: Database transactions

Joรฃo Paulo - Sep 2 - - Dev Community

Imagine you want to transfer money to your mother. You will need to withdraw money from your account and send it to hers.

You withdraw the money from your account, but when you go to make the transfer, the operation fails. You check your account and the money is no longer there, but it also hasn't reached your mother's account.

How can you prevent this from happening? Database transactions

What is?

A database transaction is a sequence of operations performed within a database management system as a single logical unit of work.

Transactions are closely related to database integrity and ensure the consistent state of a database even in the event of failure.

How it works?

The flow is simple and usually adopts an all or nothing policy:

  1. Begin the transaction
  2. Execute the operations (data manipulations, queries, etc)
  3. If no errors, commit the transaction, if an error occurs, rollback.

Database-transactions

Typescript Example:

  async create(transaction: Transaction, payable: Payable): Promise<Transaction> {
    return this.prisma.$transaction(async (prisma) => {
      const createdTransaction = await prisma.transaction.create({
        data: {
          ...transaction,
        },
      });

      await prisma.payable.create({
        data: {
          ...payable,
        },
      });

      return createdTransaction;
    });
  }
Enter fullscreen mode Exit fullscreen mode
. . . . . .
Terabox Video Player