Rust SQLx In a Nutshell
Rust and databases? Oh yeah, they go together like peanut butter and jelly—if peanut butter was a highly performant systems programming language and jelly was a blazing-fast async database library. That’s right, we’re talking about SQLx!
What is SQLx?
SQLx is an asynchronous, compile-time checked SQL library for Rust. Think of it as Diesel’s cool cousin who doesn’t need macros to do their job. Unlike Diesel, SQLx doesn’t generate Rust types for your queries at compile time—it just directly executes SQL while ensuring at compile-time that your queries are valid.
Key features of SQLx:
- Async-first – Leverages Rust’s async ecosystem (Tokio, async-std, etc.).
- Compile-time checked SQL – No more runtime SQL errors!
- Supports PostgreSQL, MySQL, SQLite, and MSSQL – Pick your poison.
- Minimal boilerplate – No need to define Rust structs for everything (but you can if you want!).
- Connection pooling – Because nobody wants to wait for a fresh connection every time.
- Row mappings – Map query results into Rust structs seamlessly.
Installing SQLx
To get started, add SQLx to your Cargo.toml
file. You’ll need to specify the database features you want.
|
|
If you’re using MySQL, SQLite, or MSSQL, replace "postgres"
with "mysql"
, "sqlite"
, or "mssql"
.
Connecting to a Database
Alright, let’s get our hands dirty. First, we need to connect to a database. Here’s how you do it with PostgreSQL:
|
|
Boom! You’re connected.
Make sure you set your DATABASE_URL
environment variable before running this.
For MySQL, just replace PgPool
with MySqlPool
and for SQLite, use SqlitePool
.
Running Queries
SQLx lets you execute queries using raw SQL while still being safe and ergonomic.
Simple Query Execution
Let’s fetch some users from a users
table:
|
|
Query with Parameters
SQLx supports query parameters like a boss:
|
|
Async Connection Pooling
SQLx provides built-in connection pooling. Instead of creating a new connection every time, we can use a connection pool:
|
|
This helps avoid the dreaded “too many connections” error!
Comparison: SQLx vs Diesel vs SeaORM
Feature | SQLx | Diesel | SeaORM |
---|---|---|---|
Compile-time SQL Checking | ✅ | ✅ | ❌ |
Async Support | ✅ | ❌ | ✅ |
ORM Features | ❌ (Raw SQL) | ✅ | ✅ |
Macros Required | ❌ | ✅ | ✅ |
Connection Pooling | ✅ | ✅ | ✅ |
Database Support | Postgres, MySQL, SQLite, MSSQL | Postgres, MySQL, SQLite | Postgres, MySQL, SQLite |
Key Ideas
Concept | Summary |
---|---|
SQLx | Async, compile-time checked SQL library for Rust |
Features | Supports PostgreSQL, MySQL, SQLite, MSSQL, connection pooling, and async execution |
Install | Add sqlx to Cargo.toml with feature flags for your database |
Queries | Use raw SQL with .query() and .bind() for parameters |
Connection Pooling | Use PgPool , MySqlPool , or SqlitePool to manage DB connections efficiently |
Comparison | SQLx vs Diesel vs SeaORM in terms of features and async support |