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:
- decreasing the amount of money in the first account by $500,
- 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:
- we withdraw the $500 from the first account,
- 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.
1BEGIN;
2
3UPDATE bank_accounts
4SET balance = 500
5WHERE id = 1;
6
7UPDATE bank_accounts
8SET balance = 1500
9WHERE id = 2;
10
11COMMIT;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.
1import { Database } from '../database/database';
2import { Injectable, NotFoundException } from '@nestjs/common';
3import { Category } from './category.model';
4
5@Injectable()
6export class CategoriesRepository {
7 constructor(private readonly database: Database) {}
8
9 async delete(id: number) {
10 const databaseResponse = await this.database
11 .transaction()
12 .execute(async (transaction) => {
13 await transaction
14 .deleteFrom('categories_articles')
15 .where('category_id', '=', id)
16 .execute();
17
18 const deleteCategoryResponse = await transaction
19 .deleteFrom('categories')
20 .where('id', '=', id)
21 .returningAll()
22 .executeTakeFirst();
23
24 if (!deleteCategoryResponse) {
25 throw new NotFoundException();
26 }
27 return deleteCategoryResponse;
28 });
29 return new Category(databaseResponse);
30 }
31
32 // ...
33}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.
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:
1{
2 "title": "My first article",
3 "content": "Hello world!",
4 "categoryIds": [1, 2, 3]
5}Let’s implement a way to change the categories assigned to a particular article using a PUT request:
1{
2 "title": "My modified article",
3 "content": "Hello world!",
4 "categoryIds": [2, 4]
5}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.
1import { Database } from '../database/database';
2import { Injectable, NotFoundException } from '@nestjs/common';
3import { ArticleDto } from './dto/article.dto';
4import { ArticleWithCategoryIds } from './articleWithCategoryIds.model';
5
6@Injectable()
7export class ArticlesRepository {
8 constructor(private readonly database: Database) {}
9
10 async update(id: number, data: ArticleDto) {
11 const databaseResponse = await this.database
12 .transaction()
13 .execute(async (transaction) => {
14 const updateArticleResponse = await transaction
15 .updateTable('articles')
16 .set({
17 title: data.title,
18 article_content: data.content,
19 })
20 .where('id', '=', id)
21 .returningAll()
22 .executeTakeFirst();
23
24 if (!updateArticleResponse) {
25 throw new NotFoundException();
26 }
27
28 const newCategoryIds = data.categoryIds || [];
29
30 const categoryIds = await this.updateCategoryIds(
31 transaction,
32 id,
33 newCategoryIds,
34 );
35
36 return {
37 ...updateArticleResponse,
38 category_ids: categoryIds,
39 };
40 });
41
42 return new ArticleWithCategoryIds(databaseResponse);
43 }
44
45 // ...
46}Above, we use the updateCategoryIds method that modifies the relationship between the article and categories.
1import { Database, Tables } from '../database/database';
2import { Injectable } from '@nestjs/common';
3import { Transaction } from 'kysely';
4import { getDifferenceBetweenArrays } from '../utils/getDifferenceBetweenArrays';
5
6@Injectable()
7export class ArticlesRepository {
8 constructor(private readonly database: Database) {}
9
10 private async getCategoryIdsRelatedToArticle(
11 transaction: Transaction<Tables>,
12 articleId: number,
13 ): Promise<number[]> {
14 const categoryIdsResponse = await transaction
15 .selectFrom('categories_articles')
16 .where('article_id', '=', articleId)
17 .selectAll()
18 .execute();
19
20 return categoryIdsResponse.map((response) => response.category_id);
21 }
22
23 private async updateCategoryIds(
24 transaction: Transaction<Tables>,
25 articleId: number,
26 newCategoryIds: number[],
27 ) {
28 const existingCategoryIds = await this.getCategoryIdsRelatedToArticle(
29 transaction,
30 articleId,
31 );
32
33 const categoryIdsToRemove = getDifferenceBetweenArrays(
34 existingCategoryIds,
35 newCategoryIds,
36 );
37
38 const categoryIdsToAdd = getDifferenceBetweenArrays(
39 newCategoryIds,
40 existingCategoryIds,
41 );
42
43 await this.removeCategoriesFromArticle(
44 transaction,
45 articleId,
46 categoryIdsToRemove,
47 );
48 await this.addCategoriesToArticle(transaction, articleId, categoryIdsToAdd);
49
50 return this.getCategoryIdsRelatedToArticle(transaction, articleId);
51 }
52
53 // ...
54}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.
1export function getDifferenceBetweenArrays<ListType>(
2 firstArray: ListType[],
3 secondArray: unknown[],
4): ListType[] {
5 return firstArray.filter((arrayElement) => {
6 return !secondArray.includes(arrayElement);
7 });
8}Detaching categories from articles is straightforward and involves a single SQL query.
1import { Database, Tables } from '../database/database';
2import { Injectable } from '@nestjs/common';
3import { sql, Transaction } from 'kysely';
4
5@Injectable()
6export class ArticlesRepository {
7 constructor(private readonly database: Database) {}
8
9 private async removeCategoriesFromArticle(
10 transaction: Transaction<Tables>,
11 articleId: number,
12 categoryIdsToRemove: number[],
13 ) {
14 if (!categoryIdsToRemove.length) {
15 return;
16 }
17 return transaction
18 .deleteFrom('categories_articles')
19 .where((expressionBuilder) => {
20 return expressionBuilder('article_id', '=', articleId).and(
21 'category_id',
22 '=',
23 sql`ANY(${categoryIdsToRemove}::int[])`,
24 );
25 })
26 .execute();
27 }
28
29 // ...
30}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.
1import { Database, Tables } from '../database/database';
2import { BadRequestException, Injectable } from '@nestjs/common';
3import { Transaction } from 'kysely';
4import { isRecord } from '../utils/isRecord';
5import { PostgresErrorCode } from '../database/postgresErrorCode.enum';
6
7@Injectable()
8export class ArticlesRepository {
9 constructor(private readonly database: Database) {}
10
11 private async addCategoriesToArticle(
12 transaction: Transaction<Tables>,
13 articleId: number,
14 categoryIdsToAdd: number[],
15 ) {
16 if (!categoryIdsToAdd.length) {
17 return;
18 }
19 try {
20 await transaction
21 .insertInto('categories_articles')
22 .values(
23 categoryIdsToAdd.map((categoryId) => {
24 return {
25 article_id: articleId,
26 category_id: categoryId,
27 };
28 }),
29 )
30 .execute();
31 } catch (error) {
32 if (
33 isRecord(error) &&
34 error.code === PostgresErrorCode.ForeignKeyViolation
35 ) {
36 throw new BadRequestException('Category not found');
37 }
38 throw error;
39 }
40 }
41
42 // ...
43}We must add the appropriate error code to our PostgresErrorCode enum to react to the foreign key violation.
1export enum PostgresErrorCode {
2 UniqueViolation = '23505',
3 ForeignKeyViolation = '23503',
4}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!