Working With SQL Databases in Rust

As you build more Rust programs, you may need to interact with databases for data storage and retrieval.

Rust’s strong typing, memory safety, and performance, combined with its support for asynchronous operations, ORMs, and migrations, enable efficient and scalable data processing, making Rust an excellent choice for building database applications.

4

Introduction to Using SQL Databases in Rust

There are many database crates and libraries in the Rust ecosystem that provide support for the various database paradigms.

For SQL databases, you get to choose between database drivers likeLibpq,Mysql-connector, andSqlite3that provide an interface for Rust programs to interact with databases directly without any abstraction layer on the SQL and ORMs (Object-Relational Mappers) likeDiesel,Sqlx, andRust-postgresthat provide a convenient way to work with database overRust data typessuch as structs and functions.

The Rust logo alongside an illustration of a stack of crates bearing the same logo

The Diesel ORM is one of the most popular database packages in the Rust ecosystem. As an ORM, Diesel provides features from query building and execution to model definition and database schema migrations, making it easier for you to interact with databases andwrite efficient, clean, and easy-to-maintain code.

Diesel also supportsmultiple database engines including PostgreSQL, MySQL, and SQLite, and provides a robust set of features for handling complex database operations like transactions, joins, and aggregate functions.

result of printing the schema

With powerful tools, features, and excellent documentation, Diesel has become a go-to choice for many Rust developers looking to build robust and scalable data-driven applications.

Getting Started With Diesel

You’ll have to add thedieselanddotenvcrates to your project’s dependencies in the dependencies section of yourcargo.tomlfile.

After adding the crates as dependencies, you must install thediesel_cliCLI tool to interact with Diesel.

result of the database insertion operation

Run this command to install thediesel_clitool:

You can call the CLI tool with thedieselcommand after installing the tool.

A Rust logo superimposed on a photograph of somebody working on an iMac desktop computer

Next, create an environment variables file and specify your database URL.

Run this command to create and insert the database URL for an in-memory SQLite database.

To work with Diesel, you must install sqlite3 or your preferred database on your computer.

Finally, run thesetupcommand for Diesel to set up a database for your project:

Thesetupcommand creates amigrationsdirectory, creates the database specified in theDATABASE_URL, and runs existing migrations.

Setting Up Migrations With Diesel

After setting up your database with Diesel, you’ll use themigration generatecommand to generate migration files. You’ll add the name of the file as an argument:

The command generates two SQL files in themigrationsdirectory:up.sqlanddown.sql.

You’ll write SQL for your database table definitions in theup.sqlfile:

You’ll write SQL code to drop database tables in thedown.sqlfile:

After writing the SQL files, run themigration runcommand to apply pending migrations.

Additionally, you can use themigration redocommand to revert migrations:

Also, it’s possible to use theprint-schemacommand to print the schema. The command prints the contents of theschema.rsfile.

The output of theprint_schemacommand is Rust code that matches your SQL schema:

Connecting to Your SQL Database With Diesel

First, add these imports and directives to your file:

You’ll use the imports and directives to connect to your database and perform operations.

Here’s how it’s possible to connect to an SQLite database with a function and return a connection instance:

Theestablish_connectionfunction returns the connection instance struct (SqliteConnection). Theestablish_connectionloads the environment variables with theokfunction, accesses the database URL with thevarfunction, and establishes a connection with the database via the URL with theestablishfunction.

After a successful connection, you’re able to execute queries and insert them into your database.

Inserting Values to a Database With Diesel

You’ll use a struct that matches your SQL schema to insert values into your database.

Here’s a struct that matches thehumantable schema:

The insertion function will return an instance of theHumantype for other operations.

You’ll need a struct for your insertion function; the struct will implement two macro attributes, one for insertion functionality and the other that identifies the table for the operation.

Here’s the struct for the insertion operation:

Your insertion function will take in a connection instance and the data you want to insert into the database. Insert the data and print a message based on the status of the operation.

Theinsert_intofunction takes in the parameters and inserts the values into the database with Diesel’sinsert_intofunction that takes in the table and thevaluesfunction that takes in a struct instance. The function assigns the ID in descending order with thedescfunction before executing the operation.

Here’s themainfunction that calls theinsert_intofunction:

Theconnvariable is a connection instance, and thenew_humanvariable is the function call. Themainfunction prints the ID after a successful operation.

Querying Databases With Diesel

Alternatively, your query function struct will implement theQueryableattribute with aderivemacro.

Here’s the struct for the query operation:

The query function will take in a connection instance and return aHumanstruct as follows:

Thequery_dbfunction filters the human table for the row where theageequals 25 and returns the first occurrence as a struct instance.

In themainfunction, thepersonvariable calls thequery_dbfunction and prints the fields of the row with an age value equal to 25.

You Can Build Web Servers With Rust

Rust continues to gain popularity in web development as a server-side language with libraries likeActix-webandRocketthat make it easier to set up servers and build APIs and websites by abstracting complex functionality.

Most web servers have to interact with databases for data storage and retrieval. You can further integrate your Diesel-powered apps with Actix-web or Rocket to build sophisticated web applications.

Learn how to build a custom HTTP web server using either Rust’s Actix or Rocket package.

Every squeak is your PC’s way of crying for help.

Who asked for these upgrades?

When your rival has to bail out your assistant.

It’s not super flashy, but it can help to keep your computer up and running.

The fix was buried in one tiny toggle.

Technology Explained

PC & Mobile