Course › Week 4 · Async and plugging into Laravel › Day 3 · lesson 24 of 42 · 45 min reading + 60 min practice
Databases with sqlx
A connection pool, queries checked at compile time, and transactions, on your Laravel database.
On this page
A Rust worker next to a Laravel app reads and writes the same database. sqlx is the usual way: plain SQL, async, with rows decoded into your structs. It is not an ORM: there is no Eloquent here, and for a worker that runs a few well-known queries, that is a feature.
Every program below runs against a real Postgres 16 database, reset before each one to the tables a Laravel migration creates. Laravel owns the schema: the Rust side never runs migrations of its own.
Setup
cargo add sqlx --features runtime-tokio,postgres
cargo add tokio --features full
export DATABASE_URL=postgres://user:password@127.0.0.1:5432/nordic
sqlx takes one URL. Laravel’s .env usually has separate DB_HOST, DB_DATABASE… keys; build the URL from them, or set DB_URL, which Laravel 11 and later also read. For MySQL, use the mysql feature and MySqlPool; everything else today works the same.
The table, as Laravel creates it
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('bookings', function (Blueprint $table) {
$table->id(); // bigserial: i64 in Rust
$table->string('guest'); // varchar(255): String
$table->integer('nights'); // integer: i32
$table->bigInteger('total_cents'); // bigint: i64
$table->string('status', 20)->default('pending');
$table->string('note')->nullable(); // may be NULL: Option<String>
$table->timestamps();
});
}
};
There is also a payments table with a booking_id, an amount_cents and a unique provider_ref, which section 6 relies on.
1. A pool, not a connection
A PgPool holds a few open connections and lends one to each query. Like reqwest’s Client, you build it once, and it is cheap to clone into tasks. acquire_timeout bounds how long a query waits for a free connection, so a database that is down fails in 3 seconds instead of hanging.
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let count: i64 = sqlx::query_scalar("select count(*) from bookings")
.fetch_one(&pool)
.await?;
println!("{count} bookings");
Ok(())
}
3 bookingsquery_scalar is for a query that returns one value. count(*) is a bigint in Postgres, so it decodes into an i64; decoding it into an i32 would be a runtime error.
map_err(|_| "DATABASE_URL is not set")?: a plain &str converts into Box<dyn Error>, so a missing variable becomes a readable error instead of a panic.
Error: PoolTimedOut
exit code 1The same program with Postgres not running (a wrong port): after the 3-second acquire timeout, PoolTimedOut and exit code 1. Returning the error from main prints its terse debug form; the next lesson’s worker reports it as a sentence that says which database it could not reach.
2. Rows into structs
#[derive(sqlx::FromRow)] maps columns to fields by name, and query_as returns your struct. A column that may be NULL must be an Option field.
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Booking {
id: i64,
guest: String,
nights: i32,
total_cents: i64,
status: String,
note: Option<String>,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let bookings: Vec<Booking> = sqlx::query_as(
"select id, guest, nights, total_cents, status, note from bookings order by id",
)
.fetch_all(&pool)
.await?;
for b in &bookings {
println!(
"#{} {} · {} nights · {} cents · {} · note: {:?}",
b.id, b.guest, b.nights, b.total_cents, b.status, b.note
);
}
Ok(())
}
#1 Lina · 3 nights · 45030 cents · confirmed · note: None
#2 Omar · 7 nights · 105070 cents · pending · note: Some("Late check-in")
#3 Sara · 2 nights · 30020 cents · pending · note: NoneThe types
| Laravel column | Postgres type | Rust field |
|---|---|---|
$table->id(), foreignId() | bigint | i64 |
integer() | integer | i32 |
bigInteger() | bigint | i64 |
string(), text() | varchar, text | String |
boolean() | boolean | bool |
->nullable() | may be NULL | Option<…> |
timestamps(), date() | timestamp, date | needs the chrono or time feature of sqlx |
Postgres has no unsigned integers, so ids are i64, not u64. Convert at the edge of your program if the rest of it uses u64.
A NULL into a String
If note were a String field, the query compiles and fails on the first row whose note is NULL:
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Note {
id: i64,
note: String,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let notes: Vec<Note> = sqlx::query_as("select id, note from bookings order by id")
.fetch_all(&pool)
.await?;
for n in ¬es {
println!("#{}: {}", n.id, n.note);
}
Ok(())
}
Error: ColumnDecode { index: "\"note\"", source: UnexpectedNullError }
exit code 1Read it from the inside out: decoding column note failed because the value was an unexpected NULL. The fix is note: Option<String>. Section 7 shows how to catch this mismatch at compile time instead.
3. Bind values, never format them into SQL
$1, $2 are placeholders, and .bind(value) fills them in order. The value travels separately from the SQL text, so a guest called O'Brien, or '; drop table bookings; --, is only ever a name. This is Eloquent’s where('guest', $name); never format! a value into a query string.
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Booking {
id: i64,
guest: String,
nights: i32,
total_cents: i64,
status: String,
note: Option<String>,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let pending: Vec<Booking> = sqlx::query_as(
"select id, guest, nights, total_cents, status, note from bookings
where status = $1 and nights >= $2 order by id",
)
.bind("pending")
.bind(2_i32)
.fetch_all(&pool)
.await?;
for b in &pending {
println!(
"#{} {} ({} nights, {} cents, {}, {:?})",
b.id, b.guest, b.nights, b.total_cents, b.status, b.note
);
}
let hostile = "'; drop table bookings; --";
let found: Vec<Booking> = sqlx::query_as(
"select id, guest, nights, total_cents, status, note from bookings where guest = $1",
)
.bind(hostile)
.fetch_all(&pool)
.await?;
println!("guests named {hostile:?}: {}", found.len());
Ok(())
}
#2 Omar (7 nights, 105070 cents, pending, Some("Late check-in"))
#3 Sara (2 nights, 30020 cents, pending, None)
guests named "'; drop table bookings; --": 0The bound type must match the column: .bind(2_i32) for an integer. 2_i32 is the number 2 with its type written on it, since a bare 2 here could be any integer type.
4. One, maybe one, or all
| Method | Returns | Eloquent |
|---|---|---|
fetch_all | Vec<T>, possibly empty | ->get() |
fetch_optional | Option<T>: None when there is no row | ->first() |
fetch_one | T, or Err(RowNotFound) when there is no row | ->firstOrFail() |
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Booking {
id: i64,
guest: String,
nights: i32,
total_cents: i64,
status: String,
note: Option<String>,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
const FIND: &str =
"select id, guest, nights, total_cents, status, note from bookings where id = $1";
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
for id in [2_i64, 99] {
let booking: Option<Booking> = sqlx::query_as(FIND).bind(id).fetch_optional(&pool).await?;
match booking {
Some(b) => println!(
"#{}: {} ({} nights, {} cents, {}, {:?})",
b.id, b.guest, b.nights, b.total_cents, b.status, b.note
),
None => println!("#{id}: no such booking"),
}
}
let missing: Result<Booking, sqlx::Error> =
sqlx::query_as(FIND).bind(99_i64).fetch_one(&pool).await;
if let Err(error) = missing {
println!("fetch_one for #99: {error}");
}
Ok(())
}
#2: Omar (7 nights, 105070 cents, pending, Some("Late check-in"))
#99: no such booking
fetch_one for #99: no rows returned by a query that expected to return at least one rowconst FIND: &str gives the query a name, and is checked once, at compile time, like any other constant. Use fetch_optional when “not there” is normal, fetch_one when it means something is wrong.
5. Writing: execute and RETURNING
sqlx::query(…).execute() runs a statement and returns how many rows it changed. For an insert whose new id you need, add RETURNING id and use query_scalar, which Postgres answers in the same round trip.
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let id: i64 = sqlx::query_scalar(
"insert into bookings (guest, nights, total_cents, created_at, updated_at)
values ($1, $2, $3, now(), now()) returning id",
)
.bind("Youssef")
.bind(14_i32)
.bind(210_140_i64)
.fetch_one(&pool)
.await?;
println!("created booking #{id}");
let result = sqlx::query(
"update bookings set status = 'confirmed', updated_at = now() where status = 'pending'",
)
.execute(&pool)
.await?;
println!("confirmed {} bookings", result.rows_affected());
Ok(())
}
created booking #4
confirmed 3 bookingsEloquent fills created_at and updated_at for you. Plain SQL does not: a Rust worker that writes Laravel’s tables sets them itself, or Laravel will show those rows with empty dates.
6. Transactions: all or nothing
Confirming a booking means two writes: the booking’s status, and a payment row. pool.begin() starts a transaction; each query runs on it with &mut *tx; commit() makes both permanent. If anything fails before the commit, ? returns early, tx is dropped, and dropping an uncommitted transaction rolls it back. Here the second payment reuses a provider_ref, which the unique index rejects:
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
async fn confirm(pool: &PgPool, booking_id: i64, provider_ref: &str) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("update bookings set status = 'confirmed', updated_at = now() where id = $1")
.bind(booking_id)
.execute(&mut *tx)
.await?;
sqlx::query("insert into payments (booking_id, provider_ref, amount_cents) select id, $2, total_cents from bookings where id = $1")
.bind(booking_id)
.bind(provider_ref)
.execute(&mut *tx)
.await?;
tx.commit().await
}
async fn status(pool: &PgPool, id: i64) -> Result<String, sqlx::Error> {
sqlx::query_scalar("select status from bookings where id = $1")
.bind(id)
.fetch_one(pool)
.await
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
for (id, provider_ref) in [(2_i64, "pi_3QY7"), (3, "pi_3QX2")] {
match confirm(&pool, id, provider_ref).await {
Ok(()) => println!("#{id}: confirmed"),
Err(error) => println!("#{id}: not confirmed: {error}"),
}
println!("#{id}: status is now {}", status(&pool, id).await?);
}
Ok(())
}
#2: confirmed
#2: status is now confirmed
#3: not confirmed: error returned from database: duplicate key value violates unique constraint "payments_provider_ref_key" at line 666
#3: status is now pendingBooking #3’s status update ran, then the payment insert failed, and the update was undone: its status is still pending. Without the transaction, it would be confirmed with no payment, the kind of row finance finds a month later.
&mut *tx lends the transaction to one query at a time. This is Laravel’s DB::transaction(fn () => …), with the rollback tied to the variable going out of scope instead of to an exception.
7. query_as!: checked against the database while compiling
The query_as! macro sends your SQL to the database at compile time, using DATABASE_URL, and checks the columns and their types against your struct. A typo in a column name becomes a build error:
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Booking {
id: i64,
guest: String,
nights: i32,
total_cents: i64,
status: String,
note: Option<String>,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let b = sqlx::query_as!(
Booking,
"select id, guset, nights, total_cents, status, note from bookings where id = $1",
1_i64
)
.fetch_one(&pool)
.await?;
println!("#{} {}", b.id, b.guest);
Ok(())
}
error: error returned from database: column "guset" does not exist at line 3729
--> src/main.rs:33:13
|
33 | let b = sqlx::query_as!(
| _____________^
34 | | Booking,
35 | | "select id, guset, nights, total_cents, status, note from bookings where id = $1",
36 | | 1_i64
37 | | )
| |_____^
|
= note: this error originates in the macro `$crate::sqlx_macros::expand_query` which comes from the expansion of the macro `sqlx::query_as` (in Nightly builds, run with -Z macro-backtrace for more info)
error: could not compile `hello` (bin "hello") due to 1 previous errorNo error code: the message comes from Postgres, through the macro. Fix the typo and it compiles; make note a String again and you get section 2’s NULL problem as a compile error instead of a runtime one.
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct Booking {
id: i64,
guest: String,
nights: i32,
total_cents: i64,
status: String,
note: Option<String>,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let b = sqlx::query_as!(
Booking,
"select id, guest, nights, total_cents, status, note from bookings where id = $1",
1_i64
)
.fetch_one(&pool)
.await?;
println!(
"#{} {}, {} nights, {} cents, {}, {:?}",
b.id, b.guest, b.nights, b.total_cents, b.status, b.note
);
Ok(())
}
#1 Lina, 3 nights, 45030 cents, confirmed, NoneWith the macro, the parameters go inside it instead of in .bind() calls, and their types are checked too. The trade-off: every build needs a database, including in CI. cargo sqlx prepare (from cargo install sqlx-cli) saves the checked queries into a .sqlx folder you commit, so later builds work offline.
This course uses both: query_as with FromRow where the build should not need a database, the macro where catching a schema mismatch early is worth it.
Coming from PHP
The transaction from section 6 in Laravel:
<?php
use Illuminate\Support\Facades\DB;
DB::transaction(function () use ($booking, $providerRef) {
$booking->update(['status' => 'confirmed']);
$booking->payments()->create([
'provider_ref' => $providerRef,
'amount_cents' => $booking->total_cents,
]);
}); // any exception inside rolls back
Same guarantees, different trigger: Laravel rolls back when an exception escapes the closure; sqlx rolls back when the transaction is dropped without commit(), which every early ? does. And Eloquent’s attributes are untyped until a cast says otherwise, while every sqlx row is a struct whose field types the decoder enforces.
PracticeThe sqlx README, and a report query
Read the sqlx README, sections “Usage” and “Compile-time verification”.
Exercise: revenue per status
Write a query that returns, per status, the number of bookings and the sum of total_cents, sorted by status, into a struct StatusTotal { status: String, bookings: i64, revenue_cents: i64 }. Careful: in Postgres, sum(bigint) returns a numeric, not a bigint; cast it with ::bigint. Print one line per status.
Show the solution
use std::env;
use std::error::Error;
use std::time::Duration;
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
#[derive(sqlx::FromRow)]
struct StatusTotal {
status: String,
bookings: i64,
revenue_cents: i64,
}
/// One pool for the whole program, built from DATABASE_URL.
async fn connect() -> Result<PgPool, Box<dyn Error>> {
let url = env::var("DATABASE_URL").map_err(|_| "DATABASE_URL is not set")?;
let pool = PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(3))
.connect(&url)
.await?;
Ok(pool)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let pool = connect().await?;
let totals: Vec<StatusTotal> = sqlx::query_as(
"select status, count(*) as bookings, sum(total_cents)::bigint as revenue_cents
from bookings group by status order by status",
)
.fetch_all(&pool)
.await?;
for t in &totals {
println!(
"{:<10} {:>3} bookings {:>10} cents",
t.status, t.bookings, t.revenue_cents
);
}
Ok(())
}
confirmed 1 bookings 45030 cents
pending 2 bookings 135090 centsas bookings names the column so FromRow can match it to the field. Without the ::bigint cast, decoding fails at runtime with a message about NUMERIC, the same kind of error as section 2’s NULL.
Remember
- Bind every value with
$1, never format it into SQL; nullable columns areOptionfields. - Writes that belong together go in one transaction: dropping it without
commit()rolls it back.
Tomorrow: configuration from .env, logging with tracing, and the exit codes PHP will rely on.