DEV Community

João Paulo
João Paulo

Posted on • Updated on

Must know concept for Backend Developers: Database transactions

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

Top comments (3)

Collapse
 
xiaome profile image
He

Thank you for your post, I learned new concept.
I'd like to collaborate with you in development

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
joaoreider profile image
João Paulo

Thank you for your comment! It really makes a difference. I've fixed it.