API with NestJS #123. SQL transactions with Kysely

NestJS SQL

This entry is part 123 of 175 in the API with NestJS

The integrity of our data should be one of the primary concerns of web developers. Thankfully, SQL databases equip us with tools that we can use to ensure the consistency and accuracy of our data.

You can see the complete code from this article in this repository.

One of the critical situations to consider is when two SQL queries depend on each other. A good example is transferring money from one bank account to another. Let’s imagine we have two bank accounts, each with $1000. Transferring $500 from one account to another consists of two steps:

  1. decreasing the amount of money in the first account by $500,
  2. increasing the second account’s balance by $500.

If the first operation fails, the data integrity remains intact, and the total sum of money in both accounts is $2000. The worst situation would be if half of the above steps run successfully:

  1. we withdraw the $500 from the first account,
  2. we fail to add the money to the second account because it was closed recently.

In the above scenario, we lose the integrity of our data. The money in the two accounts now adds up to only $1500, and the $500 we lost is in neither of the accounts.

Transactions and the ACID properties

Thankfully, we can solve the above issue with transactions. A transaction can consist of more than one SQL query and guarantees the following:

Atomicity

A particular transaction either succeeds completely or entirely fails.

Consistency

The transaction moves the database from one valid state to another

Isolation

Multiple transactions can run concurrently without the risk of losing the consistency of our data. In our case, the second transaction should see the transferred money in one of the accounts but not both.

Durability

The changes made to the database by the transaction persist permanently as soon as we commit them.

Writing transactions with PostgreSQL

To start the transaction block, we need to start with the statement. Below, we should write the queries we want to contain in the transaction and finish with the keyword to store our changes.

Thanks to wrapping our queries in a transaction, we can revert the whole operation if transferring the money to the second account fails for any reason. To do that, we need the keyword.

Transactions with Kysely

To wrap multiple queries in a transaction when using Kysely, we need the function. Let’s create a transaction that deletes rows both from the and tables.

categories.repository.ts

If any error is thrown inside the callback function we pass to , Kysely rolls back the transaction.

When working with PostgreSQL, we manage a pool of multiple clients connected to our database. It is essential to use the  instead of when making the SQL queries that are part of the transaction. Thanks to that, we ensure that we use the same client instance for all our queries within the transaction.

Passing the transaction across different methods

As our application gets more complex, the transactions might span over more than one method in our repository. To deal with this, we can pass the transaction instance as an argument.

In the previous parts of this series, we implemented a many-to-many relationship. When creating articles, we send the following data through the API:

Let’s implement a way to change the categories assigned to a particular article using a PUT request:

After a closer inspection, we can notice the following differences between the initial data of the article and the modified version:

  • the categories with IDs and are removed,
  • the category with ID is added.

To implement the above functionality, we need to adjust our method.

articles.repository.ts

Above, we use the method that modifies the relationship between the article and categories.

articles.repository.ts

In the method, we perform a series of actions:

  • we check which categories we need to attach and detach from the article using the function,
  • we remove and add categories related to the article,
  • we return the list of categories associated with the article after the above operations.

The function returns the elements present in the first array but absent from the second one.

getDifferenceBetweenArrays.ts

Detaching categories from articles is straightforward and involves a single SQL query.

articles.repository.ts

There is a catch when attaching the categories to the article. If the user provides the ID of the category that does not exist, PostgreSQL throws the foreign key violation error, and we need to handle it.

articles.repository.ts

We must add the appropriate error code to our enum to react to the foreign key violation.

articles.repository.ts

Thanks to all of the above, we can update an article’s title, content, and categories in a single transaction.

Summary

In this article, we’ve gone through the concept of transactions and why we might need them. We also learned how to use them with Kysely by implementing both a simple and a more complex example that involves multiple methods.

Thanks to the above knowledge, we now know how to ensure the integrity of our database. We also learned how to handle a foreign key constraint violation when implementing the above examples. Managing constraints and error handling is an important topic for SQL and Kysely, and it deserves a separate article. Stay tuned!

Series Navigation<< API with NestJS #122. Many-to-many relationships with Kysely and PostgreSQLAPI with NestJS #124. Handling SQL constraints with Kysely >>
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments