Storing arrays is not an obvious thing in the world of SQL databases. Solutions such as MySQL, MariaDB, or Microsoft SQL Server don’t have a straightforward column type for arrays.
This article explores how the array data type works in PostgreSQL both through SQL queries and through TypeORM. By learning how to operate on arrays through SQL, we can better understand what the Postgres database is capable of. This will helps us quite a bit in using arrays through TypeORM.
The capabilities of the array data type in Postgres
Because databases such as MySQL don’t have an array data type, we might have had to work around this issue. One solution would be to create additional tables to store data that we would conceptualize as an array. Another solution would be to utilize the JSON data type available in MySQL and PostgreSQL.
To define the array data type column, we can append the square brackets or use the ARRAY keyword. Let’s play with our post table a bit and add the paragraphs column instead of content.
1ALTER TABLE post
2DROP COLUMN content,
3ADD COLUMN paragraphs text[]1ALTER TABLE post
2DROP COLUMN content,
3ADD COLUMN paragraphs text ARRAYThe text is a column data type that stores strings of any length
Although we could provide the array’s size, it does not affect the behavior of the database and might only serve as documentation.
When defining the array value input, we can use the curly braces notation or use the ARRAY keyword again.
1INSERT INTO post(title, paragraphs, "authorId")
2VALUES ('Hello world!', '{"Lorem ipsum", "Dolor sit amet"}', 1);Please note that we’ve surrounded the curly braces with single quotes and used the double quotes for strings
1INSERT INTO post(title, paragraphs, "authorId")
2VALUES ('Hello world!', ARRAY['Lorem ipsum', 'Dolor sit amet'], 1);I lean more towards using the ARRAY keyword, and therefore, it is more frequently used in this article.
An important note is that PostgreSQL will keep the elements in the array in the order you’ve put them in.
Modifying an array
We can change an existing array, for example, by replacing it as a whole.
1UPDATE post
2SET paragraphs = ARRAY['Lorem ipsum', 'Dolor sit amet']
3WHERE id = 1Another option is to update a single element.
1UPDATE post
2SET paragraphs[1] = 'Lorem ipsum'
3WHERE id = 1We can also update just a slice of an array. The following code updates the second and the third element, leaving the first element unchanged:
1UPDATE post
2 SET paragraphs[2:3] = ARRAY['Hello', 'World!']
3 WHERE id = 1PostgreSQL also supports concatenation with the use of the || operator. The following code creates a new array using the elements 1,2,5 and 6.
1UPDATE post
2SET paragraphs = paragraphs[1:2] || paragraphs[5:6]
3WHERE id = 1Searching through arrays
When searching through arrays, the ANY and ALL keywords can be very helpful.
To find a post where all paragraphs are equal to 'Apples', we can use the ALL command.
1SELECT * FROM post
2WHERE 'Apples' = ALL (paragraphs)To look for a post when any paragraph equals Oranges, we can use the ANY keyword.
1SELECT * FROM post
2WHERE 'Oranges' = ANY (paragraphs)Multi-dimensional arrays
PostgresSQL also supports multi-dimensional arrays. To define them, we can use multiple square brackets.
1ADD COLUMN twodimensional integer[][]Using them is similar to the regular arrays.
1SET twodimensional = ARRAY[[0,1], [2,3]]If you would like to use multi-dimensional arrays and need more examples, look at the official documentation.
Changing a regular column into an array
Above, we’ve completely dropped the content column. This might not be the best approach in production because it would result in data loss. Instead, let’s set the value of content to be the first element of the paragraphs array.
A simple way to achieve that is to:
- add the paragraphs column
- set its first element to be the value of the content column
- remove the content array
1ALTER TABLE post
2ADD COLUMN paragraphs text ARRAY;
3
4UPDATE post
5SET paragraphs = ARRAY[content];
6
7ALTER TABLE post
8DROP COLUMN content;Keep in mind that PostgreSQL utilizes a one-based numbering convention. It means that the array starts with index number 1, not 0.
Using arrays with TypeORM
While knowing all of the above helps us understand what arrays can be used, our goal is to implement them with TypeORM and NestJS. To define a column that is an array, we need to add the array: true property.
1import { Column, Entity } from 'typeorm';
2
3@Entity()
4class Post {
5 @Column('text', { array: true })
6 public paragraphs: string[];
7
8 // ...
9}
10
11export default Post;Since we expect our users to send an array of text, we also need to change our Data Transfer Objects and their validation. To check if the property is an array of strings, we need the @IsString({ each: true }) decorator.
1import { IsString, IsNotEmpty } from 'class-validator';
2
3export class CreatePostDto {
4 @IsString({ each: true })
5 @IsNotEmpty()
6 paragraphs: string[];
7
8 // ...
9}Doing the above is enough to start creating posts with the paragraphs array.
If you want to know how the author property is created in the above response, check out API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
When we look into the database, we can see that the paragraphs have been inserted properly.
1SELECT * FROM post
2WHERE id = 10Running more advanced queries on arrays
Since arrays are not a common data type in SQL databases, TypeORM might not support all of the features that we’ve used through regular SQL queries.
Fortunately, we can squeeze bare SQL queries into our NestJS code.
1async getPostsWithParagraph(paragraph: string) {
2 return this.postsRepository
3 .query(`SELECT * from post WHERE ${paragraph} = ANY(paragraphs)`);
4}There is an issue with the above code, though. Here, we are constructing a raw SQL query using a parameter that might be provided by a user. This opens up us for a SQL injection.
Fortunately, with TypeORM, we can create a parameterized query. In the below example, the $1 would be replaced with a value of a paragraph.
1async getPostsWithParagraph(paragraph: string) {
2 return this.postsRepository
3 .query('SELECT * from post WHERE $1 = ANY(paragraphs)', [paragraph]);
4}The simple-array column type
A side note for creating array columns with TypeORM is that we are not completely out of luck if we don’t use PostgreSQL.
TypeORM has a special simple-array column type that uses a regular string column under the hood.
1@Column("simple-array")
2paragraphs: string[];Even though TypeORM exposes the values as an array, it uses a single string column under the hood. All values are separated using a comma, so we can’t have any commas in our values.
Summary
In this article, we’ve gone through the concept of arrays in PostgreSQL both through writing SQL queries and using TypeORM. Thanks to knowing how to deal with arrays through SQL, we could better integrate them into our NestJS code. Fortunately, TypeORM allows us to write SQL queries ourselves, so the knowledge of Postgres really can come in handy.