Arrays with PostgreSQL and the Drizzle ORM
Thanks to some of its features, PostgreSQL sets itself apart from other SQL databases. Unlike many SQL databases that limit columns to single entries,…
Thanks to some of its features, PostgreSQL sets itself apart from other SQL databases. Unlike many SQL databases that limit columns to single entries, PostgreSQL lets us store multiple values in a single column. This simplifies database design and can improve performance. In this article, we will explore the practical uses of arrays in PostgreSQL and show how to use them with the Drizzle ORM. The array column In earlier sections of this series, we created the structure for a table that holds articles. database-schema.ts export const articles = pgTable('articles', { id: serial('id').primaryKey(), title: text('title').notNull(), content: text('content').notNull(), authorId: integer('author_id') .references(() => users.id) .notNull(), });This time, instead of a plain text column for the article’s content, let’s use an array. To do that, we need the array() function. database-schema.ts export const articles = pgTable('articles', { id: serial('id').primaryKey(), title: text('title').notNull(), paragraphs: text('paragraphs').array().notNull(), authorId: integer('author_id') .references(() => users.id) .notNull(), }); // ...We can now use the Drizzle ORM Kit to create a migration.npx drizzle-kit generate --name change-article-content-to-paragraphsDrizzle ORM Kit will ask if you want to rename the content column to paragraphs or create a new column from scratch. We, however, want to do something a bit more advanced since the type of our column changes from a simple string to an array of strings. To avoid losing the data already stored in the content array, let’s set it as the first element of the paragraphs array and then remove the content column. 0005_change-article-content-to-paragraphs.sql ALTER TABLE articles ADD COLUMN paragraphs TEXT[]; UPDATE articles SET paragraphs = ARRAY[content]; ALTER TABLE articles DROP COLUMN content;Thanks to this approach, we don’t lose the data stored in our database when we run our migration. Working with arrays using the Drizzle ORM It’s very straightforward to insert a record into the table that contains an array.await this.drizzleService.db .insert(databaseSchema.articles) .values({ authorId: 1, title: 'My article', paragraphs: [ 'First paragraph', 'Second paragraph' ], }) .returning();To achieve that in a NestJS application, we need to adjust the Data Transfer Objects so that users can send arrays to our REST API. create-article.dto.ts import { IsString, IsNotEmpty, IsOptional, IsNumber } from 'class-validator'; export class CreateArticleDto { @IsString() @IsNotEmpty() content: string; @IsString({ each: true }) @IsNotEmpty({ each: true }) paragraphs: string[]; @IsOptional() @IsNumber({}, { each: true }) categoryIds: number[] = []; } Above, we use the class-validator library to ensure that the user provides a valid array of strings. We can now adjust our service and use the paragraphs property from our DTO. articles.service.ts import { BadRequestException, Injectable } from '@nestjs/common'; import { DrizzleService } from '../database/drizzle.service'; import { databaseSchema } from '../database/database-schema'; import { CreateArticleDto } from './dto/create-article.dto'; import { isDatabaseError } from '../database/databse-error'; import { PostgresErrorCode } from '../database/postgres-error-code.enum'; @Injectable() export class ArticlesService { constructor(private readonly drizzleService: DrizzleService) {} async create(article: CreateArticleDto, authorId: number) { try { const createdArticles = await this.drizzleService.db .insert(databaseSchema.articles) .values({ authorId, title: article.title, paragraphs: article.paragraphs, }) .returning(); return createdArticles.pop(); } catch (error) { if (!isDatabaseError(error)) { throw error; } if (error.code === PostgresErrorCode.NotNullViolation) { throw new BadRequestException( `The value of ${error.column} can not be null`, ); } if (error.code === PostgresErrorCode.CheckViolation) { throw new BadRequestException('The title can not be an empty string'); } throw error; } } // ... } Updating existing records The most straightforward way of modifying an array is to provide a brand-new one, even if we want to change only some elements.await this.drizzleService.db .update(databaseSchema.articles) .set({ title: 'My article', paragraphs: [ 'New first paragraph', 'Second paragraph' ], }) .where(eq(databaseSchema.articles.id, id)) .returning();Aside from allowing us to set the entire array’s contents when modifying it, PostgreSQL provides various functions. However, we need to write raw SQL to achieve that. For example, using array_append, we can add a new element at the end of an existing array.await this.drizzleService.db .update(databaseSchema.articles) .set({ title: 'My article', paragraphs: sql`array_append(${databaseSchema.articles.paragraphs}, ${'Final paragraph'})`, }) .where(eq(databaseSchema.articles.id, id)) .returning(); The sql tagged template is imported from the drizzle-orm library. If you want to know more about tagged templates, check out Concatenating strings with template literals. Tagged templates Similarly, the array_prepend function adds an element to the beginning of the array.await this.drizzleService.db .update(databaseSchema.articles) .set({ title: 'My article', paragraphs: sql`array_prepend(${databaseSchema.articles.paragraphs}, ${'Initial paragraph'})`, }) .where(eq(databaseSchema.articles.id, id)) .returning();With the trim_array function, we can remove a particular number of elements from the end of an array. For example, let’s use it to delete the last element.await this.drizzleService.db .update(databaseSchema.articles) .set({ title: 'My article', paragraphs: sql`trim_array(${databaseSchema.articles.paragraphs}, 1)`, }) .where(eq(databaseSchema.articles.id, id)) .returning(); Searching through arrays With PostgreSQL, we can search through arrays with the ALL and ANY operators. For example, we can find articles where all paragraphs equal a particular string using the ALL keyword.this.drizzleService.db .select() .from(databaseSchema.articles) .where( sql` ${'Lorem ipsum'} = ALL(${databaseSchema.articles.paragraphs}) `, );What might be more practical is that we can use the ANY operator to get the articles where any paragraph equals a particular string.this.drizzleService.db .select() .from(databaseSchema.articles) .where( sql` ${'Lorem ipsum'} = ANY(${databaseSchema.articles.paragraphs}) `, );In addition to the above, we can use the array_length function to filter the records based on the number of elements in the array. For example, we can find all articles with at least one paragraph.this.drizzleService.db .select() .from(databaseSchema.articles) .where( sql` array_length(${databaseSchema.articles.paragraphs}, 1) > 1 `, ); With the second argument of the array_length function we specify which dimension of the array we want to measure. It can be useful for multi-dimensional arrays. Summary In this article, we explored the use of array columns and implemented examples using the Drizzle ORM. Array columns can store multiple related values within a single column in PostgreSQL, aided by built-in functions and operators for various tasks. Unfortunately, though, arrays aren’t always the best solution. Indexing and querying arrays can be inefficient with large datasets. In such cases, creating a separate table and defining relationships might be a better approach, especially if we want to enforce specific data constraints. Evaluating your application’s needs and weighing the advantages and disadvantages before opting for array columns in PostgreSQL is crucial. However, having an extra tool in your toolbox is always beneficial. The post API with NestJS #156. Arrays with PostgreSQL and the Drizzle ORM appeared first on Marcin Wanago Blog - JavaScript, both frontend and backend.