Set up ORM & database

At the bottom layer of our stack is the database. For our todo app we are using 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 sqlite.org.

Install MySQL and PostgreSQL Libs

Diesel's CLI needs to link against MySQL and PostgreSQL libs, so we need to install these:

$ sudo apt install libpq-dev libmysqlclient-dev

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, Postgres, 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:

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

[dependencies]
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.

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. This installs a cli tool -- see diesel help for a list of subcommands.

We need to tell the diesel cli what our database filename is. We can do this 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.