API with NestJS #76. Working with transactions using raw SQL queries

JavaScript NestJS SQL

This entry is part 76 of 168 in the API with NestJS

One of the challenges when working with databases is keeping the integrity of the data. In this article, we learn how to deal with it using transactions.

A transaction can contain multiple different instructions. The crucial thing about a transaction is that it either runs entirely or doesn’t run at all. Let’s revisit the most common example to understand the need for transactions.

Transferring money from one bank account to another consist of two steps:

  1. withdrawing money from the first account,
  2. adding the same amount of money to the second account.

The whole operation failing means the integrity of the data is still intact. The amount of money on both of the accounts remains intact. The worst scenario happens when just half of the above steps run successfully. Imagine the following situation:

  1. withdrawing the money reduces the amount of money in the first account,
  2. adding the money to the second account fails because the account was recently closed.

The above scenario causes us to lose the integrity of our data. A specific sum of the money disappeared from the bank and is in neither of the accounts.

ACID properties

Fortunately, we can deal with the above issue using transactions. It guarantees us the following properties:

Atomicity

The operations in the transaction form a single unit. Therefore, it either entirely succeeds or fails completely.

Consistency

A transaction progresses the database from one valid state to another.

Isolation

More than one transaction could occur in our database at the same time without having an invalid state of the data. For example, another transaction should detect the money in one bank account, but not in neither nor both.

Durability

When we commit the changes from the transaction, they need to persist permanently.

Writing transactions with PostgreSQL

Whenever we run a single query, PostgreSQL wraps it in a transaction that ensures all of the ACID properties. Besides that, we can run multiple queries in a transaction. To do that, we can use the and  statements.

With the statement, we initiate the transaction block. PostgreSQL executes all queries after the statement in a single transaction. When we run the statement, PostgreSQL stores our changes in the database.

In the above code, we first disconnect all posts from a given category. Then, we delete the category.

If deleting the category fails for any reason, the posts are not removed from the category. When that happens, we should discard the transaction using the statement. But, of course, we can also do that anytime we want to abort the current transaction.

Using transactions with node-postgres

We’ve used the node-postgres library in this series of articles to create a connection pool. This means that we have a pool of multiple clients connected to our database.

Using the same client instance for all of our queries within a transaction is crucial. To do that, we need to modify our class.

database.service.ts

When running , our query runs on any available client in the pool. This is fine if we don’t write transactions. To run a set of operations using a particular client, we need to get it using function.

Let’s use the above knowledge to delete rows from both and tables.

categories.repository.ts

A significant thing above is that we call the method when we don’t need a particular client anymore. Thanks to that, it returns to the pool and becomes available again.

Passing the client instance between methods

As our logic gets more complex, our transactions might occupy more than one method. To deal with this, we can pass the client instance as an argument.

In the previous article, we learned how to work with many-to-many relationships. When creating posts, we sent the following data through the API:

Let’s write a method that allows us to modify the above post. For example, imagine sending the following PUT request:

After analyzing the above payload, we can notice the following differences:

  • we need to remove the post from the and categories,
  • we have to add the post to the category with id .
posts.repository.ts

In the above function, we use the method that modifies the relationship between the post and the categories.

posts.repository.ts

A few important things are happening above:

  • we determine what categories we need to link and unlink from a post using the method,
  • we remove and add categories associated with the post,
  • we return the list of categories related to the post after the above operations.

First, let’s take a look at the method.

getDifferenceBetweenArrays.ts

Above, we return the elements present in the first array but absent from the second one.

The last part we need to analyze is how we remove and add categories to the post. Removing categories is very straightforward and involves a simple SQL query.

posts.repository.ts

On the other hand, adding categories to a post has a catch. If the user tries to use the id of a category that does not exist, PostgreSQL throws the foreign key violation error. In this example, we catch this error and assume that the user provided the wrong id.

posts.repository.ts

If you want to see the whole , check it out on GitHub.

To catch the above issue elegantly, we’ve added the appropriate error code to our enum.

postgresErrorCode.enum.ts

Thanks to all of the above, we can do the following actions in a single transaction:

  • update the title and content of the post
  • check the categories currently tied to the post,
  • remove and add categories to the post if necessary,
  • return the modified post together with the updated list of categories.

Summary

In this article, we’ve gone through the idea of transactions and learned why we might need them. We’ve also learned that we need to use a particular client from the connection pool for all queries in a particular transaction. To practice that, we first implemented a simple example. Then, we went through a more complicated transaction that involved passing the client between multiple methods. The above knowledge is crucial when caring about the integrity of our database.

Series Navigation<< API with NestJS #75. Many-to-many relationships using raw SQL queriesAPI with NestJS #77. Offset and keyset pagination with raw SQL queries >>
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments