Set up ORM & database

At the bottom layer of our stack is the database. For our todo app we are going to use SQLite3.

Install SQLite3

We need the SQLite3 libraries, and it is convenient to have the SQLite3 cli. On Ubuntu, this is easy to install via:

$ sudo apt install sqlite3 libsqlite3-0 libsqlite3-dev

For installation on other linux distributions, check your distribution's documentation. For installation on other platforms, see

Install Diesel

We could just make raw queries into the database and do some ad hoc marshalling of the data into the types that will be used by our application, but that's complicated and error prone. We don't like things that are messy and error prone -- one of the big things that Rust gives us is a way to verify certain aspects of correctness at compile time.

Diesel is an ORM for Rust that provides us with a type-safe way to interact with the database. It supports SQLite3, PostgreSQL, and MySQL. Take a look at the documentation for guides on using a different backend if you don't want to use SQLite3.

Modify the dependencies section of your Cargo.toml so that the file looks like this:

name = "myblog"
version = "0.1.0"
authors = ["Your Name <[email protected]>"]
edition = "2018"

diesel = { version = "1.0.0", features = ["sqlite"] }

Now if you cargo run it should fetch Diesel (and everything it needs), build it, and run your example.

Install Diesel CLI

But that's not all we want from Diesel. There's also a cli that we can use to help manage our project. Since this is only used by us during development, and not by the app during runtime, we can install it onto our workstation instead of into our Cargo.toml. Do this via

$ cargo install diesel_cli --no-default-features --features sqlite

This installs the diesel_cli tool with support for SQLite3 -- see diesel help for a list of subcommands. If you want the cli to support more database systems read the following section.

We need to tell the diesel_cli what our database filename is. We can do this by using the DATABASE_URL environment variable, or by setting the variable in a file called .env. Let's do the latter:

$ echo 'DATABASE_URL=./testdb.sqlite3' > .env

Now we can get Diesel to set up our workspace for us:

$ diesel setup

If you inspect your directory contents, you will see a file called testdb.sqlite3.

Install Diesel CLI with additional MySQL and PostgreSQL support

If you want or need diesel_cli to support MySQL and PostgreSQL as well, you first need to install the required development libraries in addition to the previously installed SQLite3 packages:

$ sudo apt install libpq-dev libmysqlclient-dev

And then install diesel_cli via

$ cargo install diesel_cli

Note: if you already installed diesel_cli, you can overwrite the existing installation by adding --force to the cargo install command.