Diesel for Rust: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Diesel and why do you need it?



Diesel is a powerful, safe, and extensible ORM (Object-Relational Mapping) library for the Rust programming language. It provides a type-safe way to interact with relational databases such as PostgreSQL, MySQL, and SQLite. Unlike many other ORMs, Diesel does not use runtime magic or reflection. Instead, it generates all necessary code at compile time, ensuring that your queries are correct and will not cause runtime errors.



Main reasons to use Diesel:

  • Type safety: Errors in SQL queries (e.g., incorrect column names or type mismatches) are caught at compile time, not in production.
  • Performance: Diesel generates highly optimized code that performs at the level of hand-written SQL queries.
  • Extensibility: You can easily add support for new data types, operators, and functions.
  • Migrations: The built-in migration system allows you to manage the database schema as code.
  • Security: Diesel automatically escapes query parameters, preventing SQL injection.


Diesel is ideal for projects where reliability, performance, and data security are important. It is widely used in web applications, API services, data processing tools, and any other Rust projects requiring database interaction.



Installing Diesel



Installing Diesel consists of two parts: adding the library to your project and installing the CLI tool for working with migrations.



1. Adding to Cargo.toml

Open your project's Cargo.toml file and add the dependencies. Choose the appropriate database backend (or multiple):



[dependencies]diesel = { version = "2.1", features = ["postgres"] }  # For PostgreSQL# diesel = { version = "2.1", features = ["mysql"] }   # For MySQL# diesel = { version = "2.1", features = ["sqlite"] }  # For SQLite


2. Installing the CLI (Command Line Interface)

The diesel_cli tool is used to create and run migrations. Install it via cargo:



# For PostgreSQLcargo install diesel_cli --no-default-features --features postgres

# For MySQLcargo install diesel_cli --no-default-features --features mysql

# For SQLitecargo install diesel_cli --no-default-features --features sqlite

# For all backendscargo install diesel_cli


3. Configuring the connection

Create a .env file in the project root to store the connection string:



DATABASE_URL=postgres://username:password@localhost/diesel_demo


Then initialize Diesel in your project:



diesel setup


This command creates a diesel.toml file, a migrations folder, and attempts to create the database if it does not exist.



Quick start with a code example



Let's create a simple application for managing users.



1. Creating a migration

Let's create a users table:



diesel migration generate create_users


Edit the migration files:



up.sql:

CREATE TABLE users (    id SERIAL PRIMARY KEY,    name VARCHAR NOT NULL,    email VARCHAR NOT NULL UNIQUE,    age INTEGER NOT NULL DEFAULT 0,    created_at TIMESTAMP NOT NULL DEFAULT NOW());


down.sql:

DROP TABLE users;


Apply the migration:



Recommendations