For this guide, we’re going to walk through some simple examples for each of the pieces of CRUD, which stands for “Create Read Update Delete”. Each step in this guide will build on the previous, and is meant to be followed along.

This guide assumes that you’re using PostgreSQL. Before we start, make sure you have PostgreSQL installed and running. If you are using some different database, like for example SQLite, some examples won’t just run as the implemented API might differ. In the project repository, you may find various examples for every supported database.

Diesel requires Rust 1.56 or later. If you’re following along with this guide, make sure you’re using at least that version of Rust by running rustup update stable.

Initializing a new project

The first thing we need to do is generate our project.

Generate a new project

  1. cargo new --lib diesel_demo
  2. cd diesel_demo

First, let’s add Diesel to our dependencies. We’re also going to use a tool called .env to manage our environment variables for us. We’ll add it to our dependencies as well.

Cargo.toml

  1. [dependencies]
  2. diesel = { version = "2.0.0", features = ["postgres"] }
  3. dotenvy = "0.15"

Installing Diesel CLI

Diesel provides a separate CLI tool to help manage your project. Since it’s a standalone binary, and doesn’t affect your project’s code directly, we don’t add it to Cargo.toml. Instead, we just install it on our system.

Install the CLI tool

  1. cargo install diesel_cli

If you run into an error like:

  1. note: ld: library not found for -lmysqlclient
  2. clang: error: linker command failed with exit code 1 (use -v to see invocation)

This means you are missing the client library needed for a database backend – mysqlclient in this case. You can resolve this issue by either installing the library (using the usual way to do this depending on your operating system) or by excluding the undesired default library with the --no-default-features flag.

By default diesel depends on the following client libraries:

If you are not sure on how to install those dependencies please consult the documentation of the corresponding dependency or your distribution package manager.

For example, if you only have PostgreSQL installed, you can use this to install diesel_cli with only PostgreSQL:

  1. cargo install diesel_cli --no-default-features --features postgres

Setup Diesel for your project

We need to tell Diesel where to find our database. We do this by setting the DATABASE_URL environment variable. On our development machines, we’ll likely have multiple projects going, and we don’t want to pollute our environment. We can put the url in a .env file instead.

  1. echo DATABASE_URL=postgres://username:password@localhost/diesel_demo > .env

Now Diesel CLI can set everything up for us.

  1. diesel setup

This will create our database (if it didn’t already exist), and create an empty migrations directory that we can use to manage our schema (more on that later).

Now we’re going to write a small CLI that lets us manage a blog (ignoring the fact that we can only access the database from this CLI…). The first thing we’re going to need is a table to store our posts. Let’s create a migration for that:

  1. diesel migration generate create_posts

Diesel CLI will create two empty files for us in the required structure. You’ll see output that looks something like this:

  1. Creating migrations/20160815133237_create_posts/up.sql
  2. Creating migrations/20160815133237_create_posts/down.sql

Migrations allow us to evolve the database schema over time. Each migration can be applied (up.sql) or reverted (down.sql). Applying and immediately reverting a migration should leave your database schema unchanged.

Next, we’ll write the SQL for migrations:

up.sql

  1. CREATE TABLE posts (
  2. id SERIAL PRIMARY KEY,
  3. title VARCHAR NOT NULL,
  4. body TEXT NOT NULL,
  5. published BOOLEAN NOT NULL DEFAULT FALSE
  6. )

down.sql

  1. DROP TABLE posts

We can apply our new migration:

  1. diesel migration run

It’s a good idea to make sure that down.sql is correct. You can quickly confirm that your down.sql rolls back your migration correctly by redoing the migration:

  1. diesel migration redo

Since migrations are written in raw SQL, they can contain specific features of the database system you use. For example, the CREATE TABLE statement above uses PostgreSQL’s SERIAL type. If you want to use SQLite instead, you need to use INTEGER instead.

When preparing your app for use in production, you may want to run your migrations during the application’s initialization phase. You may also want to include the migration scripts as a part of your code, to avoid having to copy them to your deployment location/image etc.

The diesel_migrations crate provides the embed_migrations! macro, allowing you to embed migration scripts in the final binary. Once your code uses it, you can simply include connection.run_pending_migrations(MIGRATIONS) at the start of your main function to run migrations every time the application starts.

Write Rust

OK enough SQL, let’s write some Rust. We’ll start by writing some code to show the last five published posts. The first thing we need to do is establish a database connection.

src/lib.rs

  1. use diesel::pg::PgConnection;
  2. use diesel::prelude::*;
  3. use dotenvy::dotenv;
  4. use std::env;
  5. pub fn establish_connection() -> PgConnection {
  6. dotenv().ok();
  7. let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
  8. PgConnection::establish(&database_url)
  9. .unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
  10. }

We’ll also want to create a Post struct into which we can read our data, and have diesel generate the names we’ll use to reference tables and columns in our queries.

We’ll add the following lines to the top of src/lib.rs:

src/lib.rs

  1. pub mod models;
  2. pub mod schema;

Next we need to create the two modules that we just declared.

src/models.rs

  1. use diesel::prelude::*;
  2. #[derive(Queryable)]
  3. pub struct Post {
  4. pub id: i32,
  5. pub title: String,
  6. pub body: String,
  7. pub published: bool,
  8. }

#[derive(Queryable)] will generate all of the code needed to load a Post struct from a SQL query.

Typically the schema module isn’t created by hand, it gets generated by Diesel. When we ran diesel setup, a file called diesel.toml was created which tells Diesel to maintain a file at src/schema.rs for us. The file should look like this:

src/schema.rs

  1. // @generated automatically by Diesel CLI.
  2. diesel::table! {
  3. posts (id) {
  4. id -> Int4,
  5. title -> Varchar,
  6. body -> Text,
  7. published -> Bool,
  8. }
  9. }

The exact output might vary slightly depending on your database, but it should be equivalent.

The table! macro creates a bunch of code based on the database schema to represent all of the tables and columns. We’ll see how exactly to use that in the next example.

Any time we run or revert a migration, this file will get automatically updated.

Using #[derive(Queryable)] assumes that the order of fields on the Post struct matches the columns in the posts table, so make sure to define them in the order seen in the schema.rs file.

Let’s write the code to actually show us our posts.

src/bin/show_posts.rs

  1. use self::models::*;
  2. use diesel::prelude::*;
  3. use diesel_demo::*;
  4. fn main() {
  5. use self::schema::posts::dsl::*;
  6. let connection = &mut establish_connection();
  7. let results = posts
  8. .filter(published.eq(true))
  9. .limit(5)
  10. .load::<Post>(connection)
  11. .expect("Error loading posts");
  12. println!("Displaying {} posts", results.len());
  13. for post in results {
  14. println!("{}", post.title);
  15. println!("-----------\n");
  16. println!("{}", post.body);
  17. }
  18. }

The use self::schema::posts::dsl::* line imports a bunch of aliases so that we can say posts instead of posts::table, and published instead of posts::published. It’s useful when we’re only dealing with a single table, but that’s not always what we want.

We can run our script with cargo run --bin show_posts. Unfortunately, the results won’t be terribly interesting, as we don’t actually have any posts in the database. Still, we’ve written a decent amount of code, so let’s commit.

The full code for the demo at this point can be found here.

Next, let’s write some code to create a new post. We’ll want a struct to use for inserting a new record.

src/models.rs

  1. use crate::schema::posts;
  2. #[derive(Insertable)]
  3. #[diesel(table_name = posts)]
  4. pub struct NewPost<'a> {
  5. pub title: &'a str,
  6. pub body: &'a str,
  7. }

Now let’s add a function to save a new post.

src/lib.rs

  1. use self::models::{NewPost, Post};
  2. pub fn create_post(conn: &mut PgConnection, title: &str, body: &str) -> Post {
  3. use crate::schema::posts;
  4. let new_post = NewPost { title, body };
  5. diesel::insert_into(posts::table)
  6. .values(&new_post)
  7. .get_result(conn)
  8. .expect("Error saving new post")
  9. }

When we call .get_result on an insert or update statement, it automatically adds RETURNING * to the end of the query, and lets us load it into any struct that implements Queryable for the right types. Neat!

Diesel can insert more than one record in a single query. Just pass a Vec or slice to insert, and then call get_results instead of get_result. If you don’t actually want to do anything with the row that was just inserted, call .execute instead. The compiler won’t complain at you, that way. :)

Now that we’ve got everything set up, we can create a little script to write a new post.

src/bin/write_post.rs

  1. use diesel_demo::*;
  2. use std::io::{stdin, Read};
  3. fn main() {
  4. let connection = &mut establish_connection();
  5. let mut title = String::new();
  6. let mut body = String::new();
  7. println!("What would you like your title to be?");
  8. stdin().read_line(&mut title).unwrap();
  9. let title = title.trim_end(); // Remove the trailing newline
  10. println!(
  11. "\nOk! Let's write {} (Press {} when finished)\n",
  12. title, EOF
  13. );
  14. stdin().read_to_string(&mut body).unwrap();
  15. let post = create_post(connection, title, &body);
  16. println!("\nSaved draft {} with id {}", title, post.id);
  17. }
  18. #[cfg(not(windows))]
  19. const EOF: &str = "CTRL+D";
  20. #[cfg(windows)]
  21. const EOF: &str = "CTRL+Z";

We can run our new script with cargo run --bin write_post. Go ahead and write a blog post. Get creative! Here was mine:

  1. Compiling diesel_demo v0.1.0 (file:///Users/sean/Documents/Projects/open-source/diesel_demo)
  2. Running `target/debug/write_post`
  3. What would you like your title to be?
  4. Diesel demo
  5. Ok! Let's write Diesel demo (Press CTRL+D when finished)
  6. You know, a CLI application probably isn't the best interface for a blog demo.
  7. But really I just wanted a semi-simple example, where I could focus on Diesel.
  8. I didn't want to get bogged down in some web framework here.
  9. Plus I don't really like the Rust web frameworks out there. We might make a
  10. new one, soon.
  11. Saved draft Diesel demo with id 1

Unfortunately, running show_posts still won’t display our new post, because we saved it as a draft. If we look back to the code in show_posts, we added .filter(published.eq(true)), and we had published default to false in our migration. We need to publish it! But in order to do that, we’ll need to look at how to update an existing record. First, let’s commit. The code for this demo at this point can be found here.

Now that we’ve got create and read out of the way, update is actually relatively simple. Let’s jump right into the script:

src/bin/publish_post.rs

  1. use self::models::Post;
  2. use diesel::prelude::*;
  3. use diesel_demo::*;
  4. use std::env::args;
  5. fn main() {
  6. use self::schema::posts::dsl::{posts, published};
  7. let id = args()
  8. .nth(1)
  9. .expect("publish_post requires a post id")
  10. .parse::<i32>()
  11. .expect("Invalid ID");
  12. let connection = &mut establish_connection();
  13. let post = diesel::update(posts.find(id))
  14. .set(published.eq(true))
  15. .get_result::<Post>(connection)
  16. .unwrap();
  17. println!("Published post {}", post.title);
  18. }

That’s it! Let’s try it out with cargo run --bin publish_post 1.

  1. Compiling diesel_demo v0.1.0 (file:///Users/sean/Documents/Projects/open-source/diesel_demo)
  2. Running `target/debug/publish_post 1`
  3. Published post Diesel demo

And now, finally, we can see our post with cargo run --bin show_posts.

  1. Running `target/debug/show_posts`
  2. Displaying 1 posts
  3. Diesel demo
  4. ----------
  5. You know, a CLI application probably isn't the best interface for a blog demo.
  6. But really I just wanted a semi-simple example, where I could focus on Diesel.
  7. I didn't want to get bogged down in some web framework here.
  8. Plus I don't really like the Rust web frameworks out there. We might make a
  9. new one, soon.

We’ve still only covered three of the four letters of CRUD though. Let’s show how to delete things. Sometimes we write something we really hate, and we don’t have time to look up the ID. So let’s delete based on the title, or even just some words in the title.

src/bin/delete_post.rs

  1. use diesel::prelude::*;
  2. use diesel_demo::*;
  3. use std::env::args;
  4. fn main() {
  5. use self::schema::posts::dsl::*;
  6. let target = args().nth(1).expect("Expected a target to match against");
  7. let pattern = format!("%{}%", target);
  8. let connection = &mut establish_connection();
  9. let num_deleted = diesel::delete(posts.filter(title.like(pattern)))
  10. .execute(connection)
  11. .expect("Error deleting posts");
  12. println!("Deleted {} posts", num_deleted);
  13. }

We can run the script with cargo run --bin delete_post demo (at least with the title I chose). Your output should look something like:

  1. Compiling diesel_demo v0.1.0 (file:///Users/sean/Documents/Projects/open-source/diesel_demo)
  2. Running `target/debug/delete_post demo`
  3. Deleted 1 posts

When we try to run cargo run --bin show_posts again, we can see that the post was in fact deleted. This barely scratches the surface of what you can do with Diesel, but hopefully this tutorial has given you a good foundation to build off of. We recommend exploring the API docs to see more. The final code for this tutorial can be found here.