chapter four

4 Performing database operations

 

This chapter covers:

  • Writing our first async connection to database
  • Setting up the web service and writing unit tests
  • Creating and querying records from the database

In the previous chapter, we built a web service that uses an in-memory data store. In this chapter, we’ll enhance that web service. We’ll replace the in-memory data store with a relational database.

Our enhanced web service will expose the same set of APIs as before, but we will now have a proper database to persist the data to disk, because we do not want our data to get lost everytime we restart the web service. As there are many parts to take in, this database-backed web service will be developed iteratively and incrementally over three iterations of code.

In the first iteration, we’ll learn how to connect asynchronously to a postgres database, using a database connection pool, from a vanilla Rust program.

In the second iteration, we’ll set up the project structure for the Actix-based web service and write unit tests.

In the third iteration, we’ll write the actual handler functions to create database records and query the results.

At the end of each iteration, you will have a working version of code that can be inspected, run and tested independently.

The final code structure for this chapter is shown in figure 4.1.

Figure 4.1. Project structure
600

With these goals in mind, let’s get started.

4.1 Writing our first async connection to database (Iteration 1)

4.1.1 Selecting the database and connection library

4.1.2 Setting up the database and connecting with async pool

4.2 Setting up the web service and writing unit tests (Iteration 2)

4.2.1 Setup dependencies and routes

4.2.2 Setup the application state and the data model

4.2.3 Setup connection pool using dependency injection

4.2.4 Write the unit tests

4.3 Creating and querying records from the database (Iteration 3)

4.3.1 Writing database access functions

4.3.2 Writing handler functions

4.3.3 Writing the main() function for the database-backed web service

4.4 Summary