Building eloquent for Rust (part 1)

Tjardo
2 min readJan 11, 2023

Welcome to the journey where we will build the Rust library eloquent from scratch.

The author of this journey has a Laravel PHP background and is quite new to the language Rust (~3 months). This journey will therefore be more interesting for Rust beginners.

We’ll build a database query builder with a fluent interface —an eloquent way of writing.

Laravel Query Builder

The Laravel Query Builder makes it easy to communicate with the database. It has the ability to retrieve, insert, update and delete records in a very enjoyable way. It almost makes your forget how to write plain SQL.

Below you’ll see some Laravel examples from their documentation.

$users = DB::table('users')->get();

$user = DB::table('users')->where('name', 'John')->first();

$email = DB::table('users')->where('name', 'John')->value('email');

$user = DB::table('users')->find(3);

DB::table('users')
->where('id', $user->id)
->update(['active' => true]);

Idea of eloquent in Rust

The library we’ll try to build will have a similar way of communicating with the database — the eloquent way.

The first thing we’ll try to build is querying multiple rows from a given table name and 1 where clause.

Quickly putting something on paper — it could look something like this, but we’ll find out whether that’s possible at all and if it will actually work.

eloquent::table(table: String)
.where(column: String, value: String, operator: String)
.get();

The eloquent library should then convert this to the following plain SQL. We’ll probably make the operator optional as that’ll be mostly equal to =.

SELECT * FROM {table} WHERE {column} = {value};

Later on we’ll then extend this with features such as: first(), last(), limit(), order_by() etc.

Create the library

To create a library we’ll run the following command.

cargo new eloquent --lib

This will create a default structure for our library. After adding some missing metadata fields to the cargo.toml file we’re ready to publish our crate to crates.io. We now published an empty project (not ideal) but this allows all of you to follow the journey.

Crates.io: https://crates.io/crates/eloquent
Github: https://github.com/tjardoo/eloquent-rs

Don’t forget to subscribe to follow the journey!

--

--