Skip to content

Overview

Learning Diesel is harder than other crates because of the amount of setup that is required.

  • Reliant on a specific workflow dependent on the Diesel CLI utility
  • A lot of boilerplate code
  • Multiple APIs available for doing the same thing

Diesel supports procedural functions for CRUD functions as well as (mostly) equivalent methods on structs that implement Dsl traits. The Dsl API is more fluent

CRUD verb function method
Create diesel::insert_into diesel::dsl::insert_into
Delete diesel::delete diesel::dsl::delete?

Prerequisites

Diesel has drivers for various DBMSes. Prerequisites for these have to be installed before attempting to install the corresponding features in Diesel CLI or compiling a Rust project using it.

pacman -S postgresql
su - postgres -c 'initdb --pgdata /var/lib/postgres/data' # (1)
systemctl enable postgresql --now
  1. On Arch, this step appears to be necessary before the postgresql service can be enabled. initdb requires a directory to be explicitly specified using --pgdata or alternatively the PGDATA environment variable.
dnf install libpq-devel mariadb-devel postgresql postgresql-server
postgresql-setup --initdb # (1)
systemctl enable postgresql --now
  1. This command facilitates initialization of the database cluster, which defaults to /var/lib/pgsql/data, similar to using initdb.
apt install libpq-dev

Diesel CLI

Install Diesel CLI
cargo install diesel_cli --no-default-features --features postgres sqlite # (1)
  1. Without installing dependencies, the installation will fail upon calling /usr/bin/ld because it is unable to find "-lpq" (in the case of PostgreSQL).
.env
DATABASE_URL=database.db # (1)
  1. Because this is a relative path, Diesel will create the database in the working directory, wherever it may be. So absolute paths are recommended.
Create migrations directory and database specified in .env
diesel setup
diesel.toml
[print_schema]
file = "src/schema.rs"
schema.rs
table! {
    starships (registry) {
        registry -> Text,
        name -> Text,
        crew -> Integer,
    }
}

The schema can also be printed from the command-line

diesel print-schema

Migrations

Diesel facilitates the creation of migration scripts, reversible changes to the database's schema. Named up.sql and down.sql, they must be manually edited by the user.

Migration commands
diesel migration generate setup_tables # (1)
diesel migration list
diesel migration run
diesel migration revert # (2)
diesel migration redo
  1. Example scripts:
    up.sql
    CREATE TABLE starships (
        registry TEXT PRIMARY KEY NOT NULL,
        name TEXT NOT NULL,
        crew INTEGER NOT NULL
    );
    
    down.sql
    DROP TABLE starships;
    
  2. Because the migrations are reversible (via the down.sql script), the migration can be rolled back.

When a migration is performed, the Diesel CLI will generate a schema.rs file in a directory set by diesel.toml.