8 min read

SQL transactions with Kysely

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…

September 4, 2023

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 BEGIN statement. Below, we should write the queries we want to contain in the transaction and finish with the COMMIT keyword to store our changes.

BEGIN;
 
UPDATE bank_accounts
SET balance = 500
WHERE id = 1;
 
UPDATE bank_accounts
SET balance = 1500
WHERE id = 2;
 
COMMIT;

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 ROLLBACK keyword.

Transactions with Kysely#

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

categories.repository.ts#
import { Database } from "../database/database"
import { Injectable, NotFoundException } from "@nestjs/common"
import { Category } from "./category.model"
@Injectable()
export class CategoriesRepository {
  constructor(private readonly database: Database) {}
  async delete(id: number) {
    const databaseResponse = await this.database.transaction().execute(async (transaction) => {
      await transaction.deleteFrom("categories_articles").where("category_id", "=", id).execute()
      const deleteCategoryResponse = await transaction
        .deleteFrom("categories")
        .where("id", "=", id)
        .returningAll()
        .executeTakeFirst()
      if (!deleteCategoryResponse) {
        throw new NotFoundException()
      }
      return deleteCategoryResponse
    })
    return new Category(databaseResponse)
  } // ...
}

If any error is thrown inside the callback function we pass to execute, 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 transaction instead of this.database 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.

Previously, we implemented a many-to-many relationship. When creating articles, we send the following data through the API:

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

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

{
  "title": "My modified article",
  "content": "Hello world!",
  "categoryIds": [2, 4]
}

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 1 and 3 are removed,
  • the category with ID 4 is added.

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

articles.repository.ts#
import { Database } from "../database/database"
import { Injectable, NotFoundException } from "@nestjs/common"
import { ArticleDto } from "./dto/article.dto"
import { ArticleWithCategoryIds } from "./articleWithCategoryIds.model"
@Injectable()
export class ArticlesRepository {
  constructor(private readonly database: Database) {}
  async update(id: number, data: ArticleDto) {
    const databaseResponse = await this.database.transaction().execute(async (transaction) => {
      const updateArticleResponse = await transaction
        .updateTable("articles")
        .set({
          title: data.title,
          article_content: data.content,
        })
        .where("id", "=", id)
        .returningAll()
        .executeTakeFirst()
      if (!updateArticleResponse) {
        throw new NotFoundException()
      }
      const newCategoryIds = data.categoryIds || []
      const categoryIds = await this.updateCategoryIds(transaction, id, newCategoryIds)
      return {
        ...updateArticleResponse,
        category_ids: categoryIds,
      }
    })
    return new ArticleWithCategoryIds(databaseResponse)
  } // ...
}

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

articles.repository.ts#
import { Database, Tables } from "../database/database"
import { Injectable } from "@nestjs/common"
import { Transaction } from "kysely"
import { getDifferenceBetweenArrays } from "../utils/getDifferenceBetweenArrays"
@Injectable()
export class ArticlesRepository {
  constructor(private readonly database: Database) {}
  private async getCategoryIdsRelatedToArticle(
    transaction: Transaction<Tables>,
    articleId: number,
  ): Promise<number[]> {
    const categoryIdsResponse = await transaction
      .selectFrom("categories_articles")
      .where("article_id", "=", articleId)
      .selectAll()
      .execute()
    return categoryIdsResponse.map((response) => response.category_id)
  }
  private async updateCategoryIds(
    transaction: Transaction<Tables>,
    articleId: number,
    newCategoryIds: number[],
  ) {
    const existingCategoryIds = await this.getCategoryIdsRelatedToArticle(transaction, articleId)
    const categoryIdsToRemove = getDifferenceBetweenArrays(existingCategoryIds, newCategoryIds)
    const categoryIdsToAdd = getDifferenceBetweenArrays(newCategoryIds, existingCategoryIds)
    await this.removeCategoriesFromArticle(transaction, articleId, categoryIdsToRemove)
    await this.addCategoriesToArticle(transaction, articleId, categoryIdsToAdd)
    return this.getCategoryIdsRelatedToArticle(transaction, articleId)
  } // ...
}

In the updateCategoryIds method, we perform a series of actions:

  • we check which categories we need to attach and detach from the article using the getDifferenceBetweenArrays 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 getDifferenceBetweenArrays function returns the elements present in the first array but absent from the second one.

getDifferenceBetweenArrays.ts#
export function getDifferenceBetweenArrays<ListType>(
  firstArray: ListType[],
  secondArray: unknown[],
): ListType[] {
  return firstArray.filter((arrayElement) => {
    return !secondArray.includes(arrayElement)
  })
}

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

articles.repository.ts#
import { Database, Tables } from "../database/database"
import { Injectable } from "@nestjs/common"
import { sql, Transaction } from "kysely"
@Injectable()
export class ArticlesRepository {
  constructor(private readonly database: Database) {}
  private async removeCategoriesFromArticle(
    transaction: Transaction<Tables>,
    articleId: number,
    categoryIdsToRemove: number[],
  ) {
    if (!categoryIdsToRemove.length) {
      return
    }
    return transaction
      .deleteFrom("categories_articles")
      .where((expressionBuilder) => {
        return expressionBuilder("article_id", "=", articleId).and(
          "category_id",
          "=",
          sql`ANY(${categoryIdsToRemove}::int[])`,
        )
      })
      .execute()
  } // ...
}

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#
import { Database, Tables } from "../database/database"
import { BadRequestException, Injectable } from "@nestjs/common"
import { Transaction } from "kysely"
import { isRecord } from "../utils/isRecord"
import { PostgresErrorCode } from "../database/postgresErrorCode.enum"
@Injectable()
export class ArticlesRepository {
  constructor(private readonly database: Database) {}
  private async addCategoriesToArticle(
    transaction: Transaction<Tables>,
    articleId: number,
    categoryIdsToAdd: number[],
  ) {
    if (!categoryIdsToAdd.length) {
      return
    }
    try {
      await transaction
        .insertInto("categories_articles")
        .values(
          categoryIdsToAdd.map((categoryId) => {
            return {
              article_id: articleId,
              category_id: categoryId,
            }
          }),
        )
        .execute()
    } catch (error) {
      if (isRecord(error) && error.code === PostgresErrorCode.ForeignKeyViolation) {
        throw new BadRequestException("Category not found")
      }
      throw error
    }
  } // ...
}

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

articles.repository.ts#
export enum PostgresErrorCode {
  UniqueViolation = '23505',
  ForeignKeyViolation = '23503',
}

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!

SQL transactions with Kysely | NestJS.io