Nest.js Tutorial

Working with transactions using raw SQL queries

Marcin Wanago
JavaScriptNestJSSQL

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:

  • withdrawing money from the first account,
  • 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:

  • withdrawing the money reduces the amount of money in the first account,
  • 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 BEGIN and COMMIT statements.

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

1BEGIN;
2  --Disconnecting posts from a given category
3  DELETE FROM categories_posts
4    WHERE category_id=1;
5  --Deleting the category from the database
6  DELETE FROM categories
7    WHERE id=1;
8COMMIT;

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 ROLLBACK 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 DatabaseService class.

database.service.ts
1import { Inject, Injectable } from '@nestjs/common';
2import { Pool } from 'pg';
3import { CONNECTION_POOL } from './database.module-definition';
4 
5@Injectable()
6class DatabaseService {
7  constructor(@Inject(CONNECTION_POOL) private readonly pool: Pool) {}
8 
9  async runQuery(query: string, params?: unknown[]) {
10    return this.pool.query(query, params);
11  }
12 
13  async getPoolClient() {
14    return this.pool.connect();
15  }
16}
17 
18export default DatabaseService;

When running this.pool.query(), 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 this.pool.connect() function.

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

categories.repository.ts
1import { Injectable, NotFoundException } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3 
4@Injectable()
5class CategoriesRepository {
6  constructor(private readonly databaseService: DatabaseService) {}
7  
8  async delete(id: number) {
9    const poolClient = await this.databaseService.getPoolClient();
10 
11    try {
12      await poolClient.query('BEGIN;');
13 
14      // Disconnecting posts from a given category
15      await poolClient.query(
16        `
17        DELETE FROM categories_posts
18          WHERE category_id=$1; 
19        `,
20        [id],
21      );
22 
23      // Disconnecting posts from a given category
24      const categoriesResponse = await poolClient.query(
25        `
26        DELETE FROM categories
27          WHERE id=$1;
28        `,
29        [id],
30      );
31 
32      if (categoriesResponse.rowCount === 0) {
33        throw new NotFoundException();
34      }
35 
36      await poolClient.query(`
37        COMMIT;
38      `);
39    } catch (error) {
40      await poolClient.query(`
41        ROLLBACK;
42      `);
43      throw error;
44    } finally {
45      poolClient.release();
46    }
47  }
48 
49  // ...
50}
51 
52export default CategoriesRepository;

A significant thing above is that we call the release() 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:

1{
2  "title": "My first post",
3  "content": "Hello world!",
4  "categoryIds": [1, 2, 3]
5}

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

1{
2  "title": "My modified post",
3  "content": "Hello world!",
4  "categoryIds": [2, 4]
5}

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

  • we need to remove the post from the 1 and 3 categories,
  • we have to add the post to the category with id 4.
posts.repository.ts
1import { Injectable, NotFoundException } from '@nestjs/common';
2import DatabaseService from '../database/database.service';
3import PostDto from './post.dto';
4import PostWithCategoryIdsModel from './postWithCategoryIds.model';
5 
6@Injectable()
7class PostsRepository {
8  constructor(private readonly databaseService: DatabaseService) {}
9 
10  async update(id: number, postData: PostDto) {
11    const client = await this.databaseService.getPoolClient();
12 
13    try {
14      await client.query('BEGIN;');
15 
16      const databaseResponse = await client.query(
17        `
18        UPDATE posts
19        SET title = $2, post_content = $3
20        WHERE id = $1
21        RETURNING *
22    `,
23        [id, postData.title, postData.content],
24      );
25      const entity = databaseResponse.rows[0];
26      if (!entity) {
27        throw new NotFoundException();
28      }
29 
30      const newCategoryIds = postData.categoryIds || [];
31 
32      const categoryIds = await this.updateCategories(
33        client,
34        id,
35        newCategoryIds,
36      );
37 
38      return new PostWithCategoryIdsModel({
39        ...entity,
40        category_ids: categoryIds,
41      });
42    } catch (error) {
43      await client.query('ROLLBACK;');
44      throw error;
45    } finally {
46      client.release();
47    }
48  }
49  
50  // ...
51}
52 
53export default PostsRepository;

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

posts.repository.ts
1import {
2  Injectable,
3} from '@nestjs/common';
4import DatabaseService from '../database/database.service';
5import { PoolClient } from 'pg';
6import getDifferenceBetweenArrays from '../utils/getDifferenceBetweenArrays';
7 
8@Injectable()
9class PostsRepository {
10  constructor(private readonly databaseService: DatabaseService) {}
11 
12  private async getCategoryIdsRelatedToPost(
13    client: PoolClient,
14    postId: number,
15  ): Promise<number[]> {
16    const categoryIdsResponse = await client.query(
17      `
18      SELECT ARRAY(
19        SELECT category_id FROM categories_posts
20        WHERE post_id = $1
21      ) AS category_ids
22    `,
23      [postId],
24    );
25    return categoryIdsResponse.rows[0].category_ids;
26  }
27 
28  private async updateCategories(
29    client: PoolClient,
30    postId: number,
31    newCategoryIds: number[],
32  ) {
33    const existingCategoryIds = await this.getCategoryIdsRelatedToPost(
34      client,
35      postId,
36    );
37 
38    const categoryIdsToRemove = getDifferenceBetweenArrays(
39      existingCategoryIds,
40      newCategoryIds,
41    );
42 
43    const categoryIdsToAdd = getDifferenceBetweenArrays(
44      newCategoryIds,
45      existingCategoryIds,
46    );
47 
48    await this.removeCategoriesFromPost(client, postId, categoryIdsToRemove);
49    await this.addCategoriesToPost(client, postId, categoryIdsToAdd);
50 
51    return this.getCategoryIdsRelatedToPost(client, postId);
52  }
53  
54  // ...
55}
56 
57export default PostsRepository;

A few important things are happening above:

  • we determine what categories we need to link and unlink from a post using the getDifferenceBetweenArrays 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 getDifferenceBetweenArrays method.

getDifferenceBetweenArrays.ts
1function getDifferenceBetweenArrays<ListType extends unknown>(
2  firstArray: ListType[],
3  secondArray: unknown[],
4): ListType[] {
5  return firstArray.filter((arrayElement) => {
6    return !secondArray.includes(arrayElement);
7  });
8}
9 
10export default getDifferenceBetweenArrays;

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
1import {
2  BadRequestException,
3  Injectable,
4} from '@nestjs/common';
5import { PoolClient } from 'pg';
6import PostgresErrorCode from '../database/postgresErrorCode.enum';
7import isRecord from '../utils/isRecord';
8 
9@Injectable()
10class PostsRepository {
11 
12  private async removeCategoriesFromPost(
13    client: PoolClient,
14    postId: number,
15    categoryIdsToRemove: number[],
16  ) {
17    if (!categoryIdsToRemove.length) {
18      return;
19    }
20    return client.query(
21      `
22      DELETE FROM categories_posts WHERE post_id = $1 AND category_id = ANY($2::int[])
23    `,
24      [postId, categoryIdsToRemove],
25    );
26  }
27 
28  // ...
29}
30 
31export default PostsRepository;

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
1import {
2  BadRequestException,
3  Injectable,
4} from '@nestjs/common';
5import { PoolClient } from 'pg';
6import PostgresErrorCode from '../database/postgresErrorCode.enum';
7import isRecord from '../utils/isRecord';
8 
9@Injectable()
10class PostsRepository {
11 
12  private async addCategoriesToPost(
13    client: PoolClient,
14    postId: number,
15    categoryIdsToAdd: number[],
16  ) {
17    if (!categoryIdsToAdd.length) {
18      return;
19    }
20    try {
21      await client.query(
22        `
23      INSERT INTO categories_posts (
24        post_id, category_id
25      )
26        SELECT $1 AS post_id, unnest($2::int[]) AS category_id
27    `,
28        [postId, categoryIdsToAdd],
29      );
30    } catch (error) {
31      if (
32        isRecord(error) &&
33        error.code === PostgresErrorCode.ForeignKeyViolation
34      ) {
35        throw new BadRequestException('Category not found');
36      }
37      throw error;
38    }
39  }
40 
41  // ...
42}
43 
44export default PostsRepository;
If you want to see the whole PostsRepository, check it out on GitHub.

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

postgresErrorCode.enum.ts
1enum PostgresErrorCode {
2  UniqueViolation = '23505',
3  ForeignKeyViolation = '23503',
4}
5 
6export default PostgresErrorCode;

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.