chapter seven

7 Add a database to your application

 

This chapter covers:

  • Setting up a local database.
  • Understanding the requirements on your database crate.
  • Going through the pros and cons of ORMs.
  • Choosing a crate suitable for your needs.
  • Adding a database connection to our web service.
  • Mapping our structs to tables.
  • Extending our code to run queries within the code.
  • Adding tracing to database queries.
  • Running database migrations.
  • Switching to a new database management system.

In the previous chapter, we added the ability to log metrics about our applications. Next to the extraction of code into several modules, this makes for an already solid web service. We try to go through the steps like you would do in the start of writing a new web service.

Chapter one to six gave us a solid foundation, which we will build out in the last chapters in the book. We will move more and more towards a production grade application, and one step almost all web services have to face at some point is talking to a database.

Handling the nitty-gritty database internals is not the focus of this book, so what we are going to do is set up an example database, so we can store and retrieve data from it. The important part is: How does one connect to a database with Rust, where should you abstract the interaction with the database and how does it impact your code?

The step towards a database comes with major questions you have to answer for yourself:

7.1 Setting up our example database

7.1.1 Creating our first tables

7.2 Working with a database crate

7.2.1   Adding sqlx into our project

7.2.2 Connecting Store to our database

7.3 Re-implement our route handlers

7.3.1 Adding the database to get_questions

7.3.2 Re-implement the add_question route handler

7.3.3 Adjusting the update and delete questions handler

7.3.4 Updating the the add_answer route

7.4 Error handling and tracing database interactions

7.5 Integrating SQL migrations

7.6 Case study: Switching database management systems

7.7 Summary