Raw Queries with db::query!
Part 2 · Laravel Rust. Write plain SQL for café reports with db::query!, capture Rust variables and lists safely, bulk-insert rows, and see why SQL injection can't sneak in.
Models and typed queries handle most of the café’s needs. But one day the owner asks: “Which menu items get ordered the most?” That question joins tables, groups and counts rows, and it reads most clearly as plain SQL. In this lesson you’ll use the db::query! macro to write SQL by hand, and see how it keeps you safe from SQL injection, one of the oldest and most damaging bugs on the web.
First, the danger: SQL injection
Imagine searching orders by customer name with ordinary Rust string formatting:
fn main() { // Pretend this came from a search box on the website. let name = "x' OR '1'='1";
let sql = format!("SELECT * FROM orders WHERE customer_name = '{}'", name);
println!("{sql}");}SELECT * FROM orders WHERE customer_name = 'x' OR '1'='1'Step by step:
nameis whatever the visitor typed. Here, they typed something sneaky.format!pastes their text straight into the SQL.- The quote mark in their input closes our string early, and
OR '1'='1'becomes part of the command. Since'1'='1'is always true, the query now returns every order: other people’s names, notes and totals.
That’s SQL injection: input that changes the meaning of your SQL because it was glued into the command text. Nastier inputs can delete tables. It’s like a customer writing “…and also give me the cash drawer” on an order slip, and the barista reading the whole slip aloud as instructions.
The fix is to never glue values into SQL. Instead, send the SQL with placeholders and send the values separately as parameters. The database treats parameters as pure data, never as commands. Whatever the visitor types, it’s just a name to look for.
Warning
Never build SQL with format!, + or push_str using user input. Not even “just for a quick admin page”. Use db::query! or the model query builder instead.
Meet db::query!
db::query! lets you write SQL as usual and drop Rust variables right into it, inside braces:
use laravel::db;
let name = "Sam";
let orders = db::query!("SELECT id, customer_name FROM orders WHERE customer_name = {name}") .select() .await?;
for order in orders { let customer: String = order.try_get("customer_name")?; println!("{customer}");}{name}looks like string formatting, but it isn’t. The macro turns it into a placeholder and bindsnameas a parameter..select()runs the query and returns every matching row.try_get("customer_name")reads one column from a row, converting it to the Rust type you ask for. It returns aResult, hence the?.
So what does the database actually receive? On PostgreSQL, roughly this:
SQL: SELECT id, customer_name FROM orders WHERE customer_name = $1Parameters: $1 = "Sam"If the visitor types x' OR '1'='1, the database just searches for a customer literally named x' OR '1'='1, finds nobody, and returns nothing. The quote mark has no power, because it never becomes part of the SQL.
This is why the official docs describe db::query! as injection-safe by construction: the macro never concatenates values into your SQL string. At compile time, it turns every {capture} into a real bound parameter. There’s no unsafe way to use it by accident.
Note
Details here follow the official Database guide (opens in new tab). It also covers transactions, multiple connections and more ways to read results.
Mapping rows to structs
Reading columns one by one with try_get gets tedious. Derive db::FromRow on a struct and let Laravel fill it in, matching columns by name. Here’s the owner’s report:
use laravel::db;
#[derive(Debug, db::FromRow)]struct Popular { name: String, times_ordered: i64,}
let min_orders = 5;
let popular = db::query!( "SELECT menu_items.name, COUNT(*) AS times_ordered FROM order_items JOIN menu_items ON menu_items.id = order_items.menu_item_id GROUP BY menu_items.name HAVING COUNT(*) >= {min_orders} ORDER BY times_ordered DESC").select_as::<Popular>().await?;#[derive(Debug, db::FromRow)]lets a row become aPopular. Each field matches a column in theSELECT:nameandtimes_ordered.- The SQL joins line items to menu items, groups by name, and counts rows per item.
{min_orders}is bound as a parameter, so even this number never becomes SQL text..select_as::<Popular>()returns aVec<Popular>, most popular first.
A few other ways to finish a query:
| Method | Returns |
|---|---|
.select() |
every row |
.select_one() |
the first row, if any (Option) |
.select_as::<T>() / .select_one_as::<T>() |
rows mapped into your FromRow struct |
.scalar::<i64>() |
a single value, such as a count |
.insert(), .update(), .delete() |
runs a write statement |
What you can capture
A capture can name a variable or a field:
let order_id = 42;let status = "ready";
db::query!("UPDATE orders SET status = {status} WHERE id = {order_id}") .update() .await?;
// `form` is a validated PlaceOrder from the last lesson.db::query!("SELECT id FROM orders WHERE customer_name = {form.customer_name}") .select() .await?;{status}and{order_id}capture plain variables.{form.customer_name}captures a field of a struct, such as validated form input.- The macro borrows each value, so you can keep using your variables afterwards.
Captures accept only names and fields, not method calls. Compute anything else into a variable first:
let typed = " SAM ";let search = typed.trim().to_lowercase();
let matches = db::query!("SELECT id FROM orders WHERE LOWER(customer_name) = {search}") .select() .await?;Warning
Don’t wrap captures in quotes. Write WHERE customer_name = {name}, not WHERE customer_name = '{name}'. Captures must sit outside SQL quotes and comments, because the parameter already carries its own type. If you need a literal brace in your SQL, write {{ or }}.
Lists with {...list}
The kitchen screen wants every order that’s either pending or being prepared. In SQL that’s IN (...) with a list of values. Spread a Vec, array or slice with {...name}:
let statuses = vec!["pending", "preparing"];
let open_orders = db::query!( "SELECT id, customer_name FROM orders WHERE status IN ({...statuses})").select().await?;The ... expands the list into one parameter per item. The database receives roughly:
SQL: SELECT id, customer_name FROM orders WHERE status IN ($1, $2)Parameters: $1 = "pending", $2 = "preparing"Still no values in the SQL text, so still injection-safe.
Important
An empty list returns an error without running the query. When the list comes from user input (say, checkboxes on a filter form), check if statuses.is_empty() first and decide what an empty filter should mean.
Bulk inserts with VALUES {...rows(fields)}
Autumn arrives, and the café adds a seasonal menu. Inserting items one at a time means one database trip each. db::query! can expand a whole collection of structs into a single multi-row INSERT:
use laravel::db;
struct NewItem { name: String, price_cents: i64,}
let items = vec![ NewItem { name: "Pumpkin Spice Latte".into(), price_cents: 450 }, NewItem { name: "Maple Scone".into(), price_cents: 325 }, NewItem { name: "Chai Latte".into(), price_cents: 400 },];
let inserted = db::query!( "INSERT INTO menu_items (name, price_cents) VALUES {...items(name, price_cents)}").insert().await?;
println!("Added {} items", inserted.rows_affected());Added 3 itemsFirst, a note on .into(): "Pumpkin Spice Latte" is a &str (borrowed text), but the name field wants an owned String. .into() converts one into the other using the From/Into traits you met in Traits and Generics; Rust works out the target type from the field.
{...items(name, price_cents)}means “for each item, write one row using itsnameandprice_centsfields”.- Put the expansion right after
VALUES, without extra parentheses; the macro writes the parentheses for each row. - Every field of every row is a separate parameter, so 3 items × 2 fields = 6 parameters.
rows_affected()reports how many rows went in.
Databases cap parameters per query (65,535 on PostgreSQL and MySQL, 32,766 on SQLite), so insert very large collections in chunks. Also note that raw queries don’t fill in created_at/updated_at for you the way create! does. Supply them yourself if you need them.
Models or raw SQL?
Raw SQL is powerful, but it gives up one thing: db::query! doesn’t check your SQL against your tables at compile time. Misspell custmer_name and you’ll find out when the query runs, not when you build.
A good habit:
- Reach for models and typed queries first: compile-checked columns, relationships, eager loading.
- Use
db::query!for reports, complex joins, or database-specific features that are clearest in SQL.
Either way, values travel as parameters, so both are safe from injection.
Try it yourself
- Write a
db::query!that counts how many orders a given customer (let name = "Sam";) has placed, returning a singlei64. - Mark several orders as ready at once. Given
let ready_ids = vec![12, 15, 19];, write anUPDATEthat sets their status to"ready".
Show solution
let name = "Sam";
let count = db::query!("SELECT COUNT(*) FROM orders WHERE customer_name = {name}") .scalar::<i64>() .await? .unwrap_or(0);let ready_ids = vec![12, 15, 19];let status = "ready";
let updated = db::query!("UPDATE orders SET status = {status} WHERE id IN ({...ready_ids})") .update() .await?;scalar returns an Option (there might be no row), so unwrap_or(0) gives a plain number. update() returns how many rows changed. Remember to make sure ready_ids isn’t empty if it comes from user input.
Recap
- SQL injection happens when user input is glued into SQL text; the cure is sending values as parameters.
db::query!lets you write SQL with{captures}that become bound parameters at compile time. It never concatenates values, so it’s injection-safe by construction.- Capture variables or fields (
{name},{form.customer_name}); compute method calls into a variable first, and never put captures in quotes. {...list}expands into one parameter per item forIN (...);VALUES {...rows(a, b)}does a bulk insert.- Raw SQL isn’t checked against your schema while compiling, so prefer models first and raw SQL for reports.
What’s next
The café now stores, validates and reports on its data. In the next module, starting with Async Tasks and Concurrency, you’ll make it fast by doing several things at once.
0 of 35 lessons complete