4 Performing database operations

 

This chapter covers

  • Writing our first async connection to a database
  • Setting up the web service and writing unit tests
  • Creating and querying records in 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, replacing 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—we do not want our data to get lost every time we restart the web service. As there are many parts involved, we will develop this database-backed web service iteratively over three iterations of code:

  • In the first iteration, you’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, we will have a working version of the code that can be inspected, run, and tested independently.

4.1 Setting up the project structure

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

Figure 4.1 Project structure for chapter 4

4.2 Writing our first async connection to database (iteration 1)

4.2.1 Selecting the database and connection library

4.2.2 Setting up the database and connecting with an async pool

4.3 Setting up the web service and writing unit tests (iteration 2)

4.3.1 Setting up the dependencies and routes

4.3.2 Setting up the application state and data model

4.3.4 Writing the unit tests