API with NestJS #72. Working with PostgreSQL using raw SQL queries

JavaScript NestJS SQL

This entry is part 72 of 173 in the API with NestJS

Object-Relational Mapping (ORM) libraries can often help us write our code faster. The ORM allows us not to write raw SQL. Instead, we can manipulate the data using an object-oriented paradigm.

Using ORM can ease the learning curve of working with databases because we don’t need to go deep into learning SQL. Instead, we write the data model in the programming language we use to develop the application. On top of that, ORM should have security mechanisms that deal with issues such as SQL injection.

Unfortunately, ORMs have disadvantages too. For example, depending on ORM to generate the database structure based on our models can lead to not grasping the intricacies of the underlying architecture. Also, ORM automatically generates SQL queries for fetching, inserting or modifying data. Therefore, they are not always optimal and can lead to performance issues. Also, ORMs can have problems and bugs too.

It is fine to use ORM if we don’t need a lot of control over our SQL queries. If we develop a big project, though, we might prefer to deal with database management through raw SQL queries. In this article, we figure out how to structure our NestJS project to use raw SQL queries with a PostgreSQL database.

You can find the code from this article in this repository.

Connecting to the database

As usual in this series, we use Docker to create an instance of the PostgreSQL database for us.

docker-compose.yml

To provide Docker with the necessary environment variables, we need to create the file.

docker.env

We must also provide a similar set of variables for our NestJS application.

.env

It is also a good idea to validate if the environment variables are provided when the application starts.

app.module.ts

Establishing the connection

In this article, we use the node-postgres library to establish a connection to our PostgreSQL database and run queries.

To manage a database connection, we can create a dynamic module. Thanks to that, we could easily copy and paste it to a different project or keep it in a separate library.

If you are not familiar with dynamic modules, check out API with NestJS #70. Defining dynamic modules

database.module-definition.ts

We use above because we want our to be global.

When the is imported, we expect a particular set of options to be provided.

databaseOptions.ts

Using a connection pool

The node-postgres library recommends we use a connection pool. Since we are creating a dynamic module, we can define our pool as a provider.

database.module.ts

There is an advantage to defining the connection pool as a provider. If we want to specify some additional asynchronous configuration, this is a very good place to do so. You can find a proper example in a repository created by Jay McDoniel from the NestJS team.

Thanks to the fact that above we define a provider using the string, we now can use it in our service.

database.service.ts

Managing migrations using Knex

We could manage migrations manually, but using an existing tool might save us time and trouble. Therefore, in this article, we use Knex.

The first step in using Knex is to create the configuration file.

knexfile.ts

Above we use to make sure that our is loaded before using the .

We can now create our first migration using the migration CLI.

Running the above command creates a file where we can define our migration.

20220825173451_add_posts_table.ts

We need to fill the and methods with the SQL queries Knex will run when running migrations and rolling them back.

20220825173451_add_posts_table.ts

If you want to know more about identity columns, check out Serial type versus identity columns in PostgreSQL and TypeORM

We must execute one last command if we want Knex to run our migration.

Running migrations creates the table that contains information about which migrations Knex has already executed.

Knex also creates the table to prevent multiple procsses from running the same migrations in the same time.

The official documentation is a good resource if you want to know more about managing migrations with Knex.

The repository pattern and working with models

It might be a good idea to keep the logic of accessing data in a single place for a particular table. A very popular way of doing that is using the repository pattern.

posts.repository.ts

When running the method, we get the data in the following format:

We often might want to transform the raw data we get from the database. A fitting way to do that is to use the class-transformer library, a popular choice when working with NestJS.

post.model.ts

We need to call the function in our repository to use the above model.

posts.repository.ts

Thanks to doing the above, the data returned by the function contains the instances of the class. Now, instead of we have the property.

Using parametrized queries

We often need to use the input provided by the user as a part of our SQL query. When doing that carelessly, we open ourselves to SQL injections. The SQL injection can happen if we treat the user’s input as a part of the query. Let’s take a look at a simple example:

Because in the function, we concatenate a string, we open ourselves to the following SQL injection:

Running the method with the above string causes the following SQL query to run:

Unfortunately, it destroys our table.

One one of dealing with the above problem is using parameterized queries. When we use it, we send the parameters separately from the query, and our database knows to treat them as parameters.

To use parameters, we need to provide the second argument to the method we’ve defined in the .

posts.repository.ts

Validating incoming data

To validate the data provided by the users, we can take advantage of the library that’s popular among people using the NestJS framework.

post.dto.ts

We can use the above class in our repository when creating and updating posts.

posts.repository.ts

If you want to see the full repository, check out this repository.

We also need to use the class in our controller.

posts.controller.ts

The FindOneParams class takes care of parsing the id from the string to a number.

For validation to take place, we also need to use the . To do that globally, we can add it to the array in our .

app.module.ts

Using services

You might have noticed that the uses the , a straightforward service that uses the .

posts.service.ts

A service is a great place to write additional logic. A good example would be caching or using ElasticSearch.

If you want to know more about ElasticSearch, check out API with NestJS #12. Introduction to Elasticsearch

Summary

There could be many reasons we might not want to use ORM, and we’ve covered some of them in this article. To deal with that, we’ve implemented a way to write raw SQL queries when working with PostgreSQL and NestJS. To increase the development experience, we’ve decided to rely on Knex for managing migrations. The repository created in this article can serve as a good starting point for a more complex project.

Series Navigation<< API with NestJS #71. Introduction to feature flagsAPI with NestJS #73. One-to-one relationships with raw SQL queries >>
Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ClemSK
ClemSK
2 years ago

Hi Marcin, great article – very helpful as I’m starting a new project with Nest. Just wanted to mention that the app.module.ts file should also import the PostModule and DatabaseModule. Without this I wasn’t able to connect to Postgres. I found this by comparing with your completed file.
Below is the code that worked for me, I’ve commented out the sections on auth which come later.

Dragos
Dragos
1 year ago

Hi Marcin, great article x2. FYI, this creates a non iterable object which defeats the purpose of a getAll

Type ‘PostModel’ must have a ‘[Symbol.iterator]()’ method that returns an iterator.

Last edited 1 year ago by Dragos
Bilal
Bilal
8 months ago

can we use prisma for migration since it have good migration than using knex then use query builder for query