Database
- Introduction
- Configuration
- Running queries
- Transactions
- Using multiple connections
- Read and write connections
- Listening for queries
- Native SQLx access
- Troubleshooting
- Testing
Introduction
Almost every modern web application interacts with a database. Built on SQLx, dust-framework provides first-party support for PostgreSQL, MySQL, MariaDB, and SQLite, whether you are working with raw SQL via db::query!, the fluent query builder, or models.
Most of your application's queries will go through models and the query builder. This guide walks through configuring your database connections, working with transactions and read replicas, and writing raw SQL when a query is clearest in SQL itself. To create and modify tables, see migrations.
Configuration
Database settings live in src/config/database.rs. New applications define a single postgres connection by default. Configure the default connection name with DB_CONNECTION and its connection string with DATABASE_URL:
DB_CONNECTION=postgres
DATABASE_URL=postgres://postgres@127.0.0.1/dustdust-framework selects the driver from the URL scheme: postgres://, mysql://, mariadb://, or sqlite:. Although MySQL and MariaDB share a wire protocol, their SQL syntax differs in places, so use mariadb:// for MariaDB servers so the query builder generates MariaDB-compatible SQL.
Drivers
Each database driver is enabled via a Cargo feature on dust-framework so your application only compiles the drivers it uses. New applications enable database-postgres in Cargo.toml. To switch drivers or add another database engine, update the feature list in Cargo.toml:
[dependencies]dust-framework = { version = "0.1", features = ["database-postgres", "database-sqlite"] }| Feature | Databases |
|---|---|
database-postgres |
PostgreSQL |
database-mysql |
MySQL and MariaDB |
database-sqlite |
SQLite |
Without a driver feature, the dust::db module doesn't exist, and the database session, cache, and queue drivers can't run.
SQLite
SQLite keeps the entire database in a single file with no separate server to run, making it convenient for local development and small applications. To use it instead of PostgreSQL, replace database-postgres with database-sqlite in Cargo.toml, then configure your .env file:
DB_CONNECTION=sqlite
DATABASE_URL=sqlite://storage/app/database.sqlite?mode=rwcThe path is relative to your application's root directory. mode=rwc creates the file on first use, provided the parent directory already exists.
SQLite behaves differently from the server databases in ways that matter as your application grows:
- Foreign keys are off unless you enable them. A new SQLite connection does not enforce foreign key constraints. Turn them on for every pooled connection with
initialize("PRAGMA foreign_keys = ON")on the connection, as Driver options shows. Without it, aforeign_id(..).constrained()column accepts orphaned rows. - Only one writer at a time. SQLite serializes writes, so a long write transaction blocks other writers and can surface as a busy or locked error. Keep write transactions short and retry contested ones with
transaction_with_attempts. - There are no row-level locks.
lock_for_updatehas nothing to lock, but the single-writer rule gives you the same safety if you retry conflicts. - Some query features are missing. SQLite has no
ilike, no full-text search fordb::search, and no native exact decimals; see Driver differences.
Use an in-memory database (sqlite::memory:) when you want one that disappears when the process ends. Each pooled connection opens its own in-memory database, so keep the pool at one connection, or use a temporary file, when several connections must see the same rows.
Defining more connections
When your application talks to more than one database, such as a separate reporting database, register additional named connections in src/config/database.rs. Start from Database::from_env(env) so your default connection continues to read DB_CONNECTION, DATABASE_URL, DB_MAX_CONNECTIONS, DB_TIME_PRECISION, and the read and write variables from the environment:
use dust::config::database::{ConnectionConfig, Database};use dust::config::{self, Env};#[config::section]fn database(env: &Env) -> Database { let mut database = Database::from_env(env); database.add_connection( "reporting", ConnectionConfig::new(env.get("REPORTING_DATABASE_URL").unwrap_or_default()) .max_connections(20), ); database}By default, each connection maintains a pool of up to 10 open connections. Under heavy concurrency, you can raise the default connection's pool size with DB_MAX_CONNECTIONS, keeping the combined total across all application instances below your database server's connection limit:
DB_MAX_CONNECTIONS=20For additional connections, chain max_connections on ConnectionConfig, as shown on reporting above. Queries wait up to 30 seconds to acquire a connection from the pool before returning an error. To adjust pool timeouts, call acquire_timeout, idle_timeout, or max_lifetime on ConnectionConfig, such as .acquire_timeout(5.seconds()).
dust-framework opens connection pools lazily on the first query, so an unreachable database does not prevent your application from booting unless your own boot hooks query it.
To run a query on a named connection, see Using multiple connections.
Time precision
By default, each database connection stores timestamps, date-times, and times with microsecond precision (6 fractional digits of seconds), matching the maximum precision supported by PostgreSQL and MySQL. Before sending a time value to the database, dust-framework truncates it to the connection's precision rather than letting the database round it, and the schema builder's time columns use the same precision by default. That way, a row written at dust::now() is never rounded forward into the future, so a query for records up to dust::now() always finds it.
To store whole seconds instead, or any other precision from 0 to 6, set DB_TIME_PRECISION in your .env file:
DB_TIME_PRECISION=0For additional connections, chain time_precision on ConnectionConfig in src/config/database.rs:
database.add_connection( "legacy", ConnectionConfig::new("mysql://app@10.0.0.5/legacy").time_precision(0),);When customizing a column with .precision(n) in a migration, give it at least the connection's precision. A column with less precision than its connection causes the database to round incoming values instead of truncating them, while a column with higher precision still only receives values truncated to the connection's precision.
[!NOTE] If you change
DB_TIME_PRECISIONin an application that has already run migrations, write a new migration to update your existing time columns with.precision(n).change().
Driver options
For TLS, Unix sockets, or other settings that don't fit in a URL, build the connection in src/config/database.rs from SQLx's options for your driver. initialize runs SQL each time the pool opens a new connection:
use dust::config::database::{ConnectionConfig, Database};use dust::config::{self, Env};use dust::db::sqlx::postgres::{PgConnectOptions, PgSslMode};#[config::section]fn database(env: &Env) -> Database { let mut database = Database::from_env(env); let postgres = ConnectionConfig::postgres( PgConnectOptions::new() .host("db.internal") .username("app") .database("app") .ssl_mode(PgSslMode::Require), ) .initialize("SET search_path TO app, public"); database.add_connection("postgres", postgres); database}ConnectionConfig::mysql, ConnectionConfig::mariadb, and ConnectionConfig::sqlite accept the same builder options. When replacing the default connection with driver options, chain max_connections or time_precision directly on the ConnectionConfig if you need a custom pool size or time precision.
Connection reference
Most applications configure one connection through the environment. These variables apply to the default connection only; a named connection you add in src/config/database.rs ignores them unless you pass the values yourself:
| Variable | Default | What it does |
|---|---|---|
DB_CONNECTION |
postgres |
Names the default connection |
DATABASE_URL |
None | The default connection's URL, whose scheme selects the driver |
DB_MAX_CONNECTIONS |
10 |
The pool's maximum open connections |
DB_TIME_PRECISION |
6 |
Fractional digits of seconds stored in time columns |
DB_READ_HOSTS |
None | Comma-separated read replicas, as hosts or full URLs |
DB_WRITE_URL |
DATABASE_URL |
The URL that writes and transactions use |
DB_STICKY |
false |
Whether a write makes later reads in the same request use the writer |
The URL scheme is the driver: postgres://, mysql://, mariadb://, or sqlite:. An unsupported scheme fails when the first query runs, with an error naming the connection. Percent-encode characters that are special in a URL, such as @ in a password, so the URL parser reads them as part of the credential.
Environment variables are read once when the application boots. Changing them requires a restart; the schema builder and query builder do not re-read configuration per query.
Connection lifecycle
dust-framework resolves configuration at boot but does not connect. A connection's pool opens on its first query, then grows on demand up to max_connections. A query waits up to acquire_timeout (30 seconds by default) for a free connection before returning an error, which is how pool exhaustion shows up:
couldn't acquire a connection to database `primary`Three details follow from the lazy pool:
- A bad URL or an unreachable server fails at the first query, not at startup. If you want a deployment to fail early, run a health check in a
bootedcallback withserver_version(). - Idle and old connections are recycled.
idle_timeoutcloses connections that sit unused, andmax_lifetimeretires connections that live too long, which most managed databases require. The defaults suit small applications; tune them when a proxy or server closes connections on its own schedule. - Dropping a pool does not interrupt running queries. Removing a connection stops new queries while the pool waits for in-flight ones to finish, then closes.
use dust::Application;use dust::db;Application::configure() .booted(async |_| { let version = db::default_connection()?.server_version().await?; tracing::info!(%version, "Connected to the database"); Ok(()) }) // ...each and a cursor hold one connection from the pool until the stream ends or is dropped. A slow loop over each with a pool of 10 can therefore starve nine other queries; see Streaming results.
Running queries
Once your connection is configured, you may run queries with the db::query! macro. Write your SQL as usual, and wrap any Rust variable in braces. The macro binds each one as a query parameter, so a variable can never inject SQL. This handler finds a user by the ID in the URL, and responds with a 404 when there's no such user:
use dust::db;use dust::prelude::*;pub async fn show(Params(id): Params<i64>) -> dust::Result<String> { let user = db::query!("SELECT id, name FROM users WHERE id = {id}") .select_one() .await? .or_abort(404)?; let name: String = user.try_get("name")?; Ok(name)}The macro runs the query on your default connection. It doesn't check the SQL against your schema when you compile, so a misspelled column is an error when the query runs, not a compile error.
Running a select query
select returns every matching row, and select_one returns the first, if there is one. Read a row's columns with try_get, by name or by zero-based position:
use dust::db;let active = true;let users = db::query!("SELECT id, name FROM users WHERE active = {active}") .select() .await?;for user in users { let name: String = user.try_get("name")?;}Most of the time you'll want rows as structs instead, as Mapping rows to structs shows.
The method you end a query with decides how many rows the database sends and what you get back:
| Method | Reads | Returns |
|---|---|---|
select |
Every row | Vec<AnyRow> |
select_one |
The first row | Option<AnyRow> |
scalar::<T> |
The first column of the first row | Option<T> |
select_as::<T> / select_one_as::<T> |
Every row / the first row | Vec<T> / Option<T> |
each / cursor |
Every row, streamed | () / a stream of rows |
statement |
No rows | The statement's result |
A missing row is None, not an error, so a query for a user that does not exist succeeds with None. Reading a column that the query did not select, or a value that does not fit the Rust type, is an error from try_get.
When a query returns a single value, such as a count, scalar returns it directly. It returns None when there's no row:
let count = db::query!("SELECT COUNT(*) FROM users").scalar::<i64>().await?.unwrap_or(0);When calling a stored procedure that returns multiple result sets, use select_result_sets to collect each set in order and read its rows:
let account_id = 42;let sets = db::query!("CALL account_summary({account_id})") .select_result_sets() .await?;for row in &sets[0].rows { let balance: i64 = row.try_get("balance")?;}for row in &sets[1].rows { let invoice_id: i64 = row.try_get("id")?;}Running insert, update, and delete statements
Use the insert, update, and delete methods to execute write statements against the database. Both update and delete return the number of rows affected by the query:
use dust::db;let (name, email) = ("Taylor", "taylor@example.com");db::query!("INSERT INTO users (name, email) VALUES ({name}, {email})") .insert() .await?;let updated = db::query!("UPDATE users SET votes = 100 WHERE name = {name}") .update() .await?;let deleted = db::query!("DELETE FROM users WHERE votes < 10").delete().await?;To get the new row's ID back, see Returning inserted IDs and rows. For statements that return nothing, such as DROP TABLE, use statement:
db::query!("DROP TABLE users").statement().await?;To run multiple statements separated by semicolons, use unprepared. Because it sends the SQL directly as written without preparing it, it cannot bind values and returns an error if the query contains any captured variables:
db::query!( "CREATE TABLE audit_logs (id INTEGER PRIMARY KEY, message TEXT); CREATE INDEX audit_logs_message_index ON audit_logs (message);").unprepared().await?;Binding values
A capture may name a variable or a field, such as {email}, {user.id}, or {form.address.city}. The macro borrows each one, so you can keep using your variables afterward. It accepts only names and fields, so compute anything else, such as a method call, into a variable first.
To match against a list, spread a Vec, array, or slice with {...name}. It binds one parameter per item:
use dust::db;let roles = vec!["admin", "editor"];let users = db::query!("SELECT * FROM users WHERE role IN ({...roles})") .select() .await?;An empty list returns an error without running the query, so check for one first when the list comes from input. Place captures outside SQL quotes and comments, and write a literal brace as {{ or }}.
Inserting many rows
To insert a collection in one statement, expand it with {...users(name, email)}. The expansion writes one parenthesized row per item, binding the fields you list:
use dust::db;struct NewUser { name: String, email: String,}let users = vec![ NewUser { name: "Taylor".into(), email: "taylor@example.com".into() }, NewUser { name: "Jess".into(), email: "jess@example.com".into() },];let inserted = db::query!("INSERT INTO users (name, email) VALUES {...users(name, email)}") .insert() .await?;let count = inserted.rows_affected();Put the expansion directly after VALUES, without parentheses around it. Each field is a parameter, and PostgreSQL and MySQL allow 65,535 parameters in one query, while SQLite allows 32,766. Insert a larger collection in chunks.
Mapping rows to structs
To map rows into your own structs, derive db::FromRow and call select_as or select_one_as. Fields map to columns by name, and #[db(rename = "...")] maps a field to a column with another name:
use dust::db;#[derive(Debug, db::FromRow)]struct Subscriber { id: i64, #[db(rename = "email_address")] email: String, nickname: Option<String>,}let id = 42;let subscriber: Option<Subscriber> = db::query!("SELECT id, email_address, nickname FROM subscribers WHERE id = {id}") .select_one_as() .await?;let subscribers = db::query!("SELECT id, email_address, nickname FROM subscribers") .select_as::<Subscriber>() .await?;Mapping ignores extra columns. A missing column, or a NULL in a field that isn't an Option, returns an error. To read one column from every row, map each row to the column's type:
let ids = db::query!("SELECT id FROM users WHERE active").select_as::<i64>().await?;#[db(json)] decodes a JSON column into any field that implements Deserialize. On an Option field, both SQL NULL and JSON null read as None:
#[derive(db::FromRow)]struct User { id: i64, #[db(json)] roles: Vec<String>, #[db(json)] preferences: Option<serde_json::Value>,}To map a column into a single-field wrapper struct, derive Newtype, which the prelude imports. The struct then binds and decodes as the value it wraps, so it works as a FromRow field and as a model column:
use dust::db;use dust::prelude::*;#[derive(Debug, Newtype)]struct Email(String);#[derive(Debug, db::FromRow)]struct Subscriber { id: i64, email: Email,}For custom conversions, such as parsing an IANA timezone name from a text column into a TimeZone, implement db::Decode. index is the column's zero-based position in the row, which you can pass to row.try_get to read the underlying database value:
use dust::db::{AnyRow, Decode};use dust::time::tz::TimeZone;struct UserTimeZone(TimeZone);impl Decode for UserTimeZone { fn decode(row: &AnyRow, index: usize) -> dust::Result<Self> { let name: String = row.try_get(index)?; Ok(Self(TimeZone::get(&name)?)) }}Returning inserted IDs and rows
To retrieve the ID of a newly inserted row, call insert_returning_id. Include a RETURNING id clause on PostgreSQL and SQLite; on MySQL and MariaDB, omit the clause and dust-framework automatically reads the auto-increment ID:
use dust::db;let name = "Taylor";let id: Option<i64> = db::query!("INSERT INTO users (name) VALUES ({name}) RETURNING id") .insert_returning_id() .await?;To get whole rows back from a write, write a RETURNING clause and use one of the returning methods. The _as methods map the rows with db::FromRow:
#[derive(db::FromRow)]struct User { id: i64, name: String,}let (id, name) = (42, "Taylor Otwell");let user = db::query!("UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name") .update_returning_as::<User>() .await?;| Statement | First row, as Option<T> |
Every row, as Vec<T> |
|---|---|---|
INSERT |
insert_returning_as |
insert_returning_all_as |
UPDATE |
update_returning_as |
update_returning_all_as |
DELETE |
delete_returning_as |
delete_returning_all_as |
Each method also has a raw variant without the _as suffix, such as insert_returning or update_returning_all, which returns AnyRow values you can read with try_get:
if let Some(row) = db::query!( "UPDATE users SET name = {name} WHERE id = {id} RETURNING id, name").update_returning().await?{ let updated_name: String = row.try_get("name")?;}PostgreSQL and SQLite support RETURNING on INSERT, UPDATE, and DELETE, MariaDB supports it on INSERT and DELETE, and MySQL does not support RETURNING.
JSON columns
To store a custom Rust type as JSON, derive db::Json alongside Serde's traits. Bind it in queries as a standard parameter and read it back with try_get or as a FromRow field:
use dust::db;use dust::prelude::*;use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize, db::Json)]struct Preferences { theme: String, notifications: bool,}let id = 42;let preferences = Preferences { theme: "dark".into(), notifications: true };db::query!("UPDATE users SET preferences = {preferences} WHERE id = {id}") .update() .await?;let row = db::query!("SELECT preferences FROM users WHERE id = {id}") .select_one() .await? .or_abort(404)?;let preferences: Preferences = row.try_get("preferences")?;A Vec or other collection captured as {roles} binds as a single JSON value, while {...roles} spreads it into one parameter per item. PostgreSQL and MySQL store JSON in native JSON columns, and SQLite stores it as text.
Enums, UUIDs, and IP addresses
To store an enum without fields as text, derive Enum, which the prelude imports. It uses the same names as Serde, so #[serde(rename_all)] and #[serde(rename)] decide what's stored:
use dust::db;use dust::prelude::*;use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]enum Status { PendingReview, Active,}let id = 42;let status = Status::PendingReview;db::query!("UPDATE posts SET status = {status} WHERE id = {id}") .update() .await?;This stores pending_review. Reading a string that matches no variant returns an error. For enums whose variants hold data, derive db::Json instead and store them in a JSON column such as table.json("payment_method") or table.jsonb("payment_method"):
use dust::db;use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize, db::Json)]enum PaymentMethod { Card { last4: String }, BankTransfer,}let id = 42;let method = PaymentMethod::Card { last4: "4242".into() };db::query!("UPDATE orders SET payment_method = {method} WHERE id = {id}") .update() .await?;For UUIDs and ULIDs, use dust::str::Uuid and dust::str::Ulid. A Uuid binds as a native UUID on PostgreSQL and as text on other databases, and a Ulid always binds as text. IpAddr binds as text too, so store it in a text column, as the schema builder's ip_address column does:
use std::net::IpAddr;use dust::db;use dust::str::{self, Ulid, Uuid};let id: Uuid = str::uuid();let trace_id: Ulid = str::ulid();let ip_address: IpAddr = "203.0.113.7".parse()?;db::query!( "INSERT INTO logins (id, trace_id, ip_address) VALUES ({id}, {trace_id}, {ip_address})").insert().await?;Dates and timestamps
Dates and times use the types in dust::time:
use dust::db;use dust::prelude::*;use dust::time::Timestamp;use dust::time::civil::Date;let id = 42;let ships_on: Date = "2026-11-20".parse()?;let paid_at = dust::now().timestamp();db::query!("UPDATE orders SET ships_on = {ships_on}, paid_at = {paid_at} WHERE id = {id}") .update() .await?;let order = db::query!("SELECT ships_on, paid_at FROM orders WHERE id = {id}") .select_one() .await? .or_abort(404)?;let paid_at: Option<Timestamp> = order.try_get("paid_at")?;| Rust type | What it holds | PostgreSQL | MySQL | SQLite |
|---|---|---|---|---|
time::civil::Date |
A calendar date | DATE |
DATE |
Text |
time::civil::Time |
A time of day | TIME |
TIME |
Text |
time::civil::DateTime |
A date and time, without a timezone | TIMESTAMP |
DATETIME |
Text |
time::Timestamp |
An instant | TIMESTAMPTZ or TIMESTAMP |
TIMESTAMP or DATETIME |
Text |
dust-framework stores times in UTC, so a Timestamp field reads the schema builder's timestamps() columns on every database, even though some of those columns have no timezone.
Decimals
For exact decimals such as prices or account balances, use dust::numeric::Decimal rather than floating-point numbers:
use dust::db;use dust::numeric::Decimal;use dust::prelude::*;let id = 42;let subtotal: Decimal = "149.99".parse()?;let tax: Decimal = "12.37".parse()?;let total = (&subtotal + &tax).round(2);db::query!("UPDATE orders SET total = {total} WHERE id = {id}") .update() .await?;let order = db::query!("SELECT total FROM orders WHERE id = {id}") .select_one() .await? .or_abort(404)?;let total: Decimal = order.try_get("total")?;Decimal supports standard arithmetic (+, -, *, /), comparisons, and rounding helpers such as .round(2) and .with_scale(2). Borrow operands like &subtotal + &tax when you want to reuse them afterward.
Decimal maps to NUMERIC on PostgreSQL, DECIMAL on MySQL, and NUMERIC or text on SQLite. Parse decimals from strings rather than floats so they preserve every digit. Because SQLite has no native exact decimal type and stores fractional NUMERIC values as floating-point numbers (roughly 15 digits of precision), store higher-precision decimals in a text column on SQLite.
Streaming results
select loads every matching row into memory at once, which can exhaust memory when processing large tables such as a full subscriber list. To process rows one at a time, call each with an async closure; iteration stops immediately on the first error:
use dust::db;db::query!("SELECT email FROM subscribers").each(async |row| { let email: String = row.try_get("email")?; // Send the newsletter... Ok(())}).await?;each keeps a connection from the pool until it finishes, so keep slow work out of the closure. The closure can't change variables outside it. To collect rows, keep a running total, or stop early, use cursor, which returns a stream of rows:
use dust::db;use dust::stream::TryStreamExt;let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id").cursor();let mut sent = 0;while let Some(row) = cursor.try_next().await? { let email: String = row.try_get("email")?; // Send the newsletter... sent += 1;}To map each streamed row directly into a struct deriving db::FromRow, use cursor_as:
use dust::db;use dust::stream::TryStreamExt;#[derive(db::FromRow)]struct Subscriber { id: i64, email: String,}let mut cursor = db::query!("SELECT id, email FROM subscribers ORDER BY id") .cursor_as::<Subscriber>();while let Some(subscriber) = cursor.try_next().await? { tracing::info!(id = subscriber.id, email = %subscriber.email, "Processing subscriber");}Handling errors
Query failures return standard dust::Error values, so propagating them with ? from a handler produces a 500 response. Each error message includes the database error, connection name, driver, and SQL query, such as no such table: subscribers (Connection: primary, Driver: SQLite, SQL: INSERT INTO subscribers (email) VALUES (?)). Bound values are omitted from the message, and the error tracks the call site that built the query. To handle specific constraint failures, such as a duplicate email address, inspect the error with db::is_unique_violation:
use dust::db;use dust::prelude::*;#[dust::input]#[validate(anyone)]pub struct Subscribe { #[validate(required, email)] email: String,}pub async fn subscribe( Valid(Subscribe { email }): Valid<Subscribe>,) -> dust::Result<Redirect> { match db::query!("INSERT INTO subscribers (email) VALUES ({email})").insert().await { Ok(_) => {} Err(error) if db::is_unique_violation(&error) => { // Already subscribed... } Err(error) => return Err(error), } Ok(Redirect::back())}dust-framework provides helpers to classify common database errors across PostgreSQL, MySQL, MariaDB, and SQLite:
| Helper | Matches |
|---|---|
db::is_unique_violation(&error) |
Unique or primary key constraint violation |
db::is_foreign_key_violation(&error) |
Foreign key constraint violation |
db::is_check_violation(&error) |
CHECK constraint violation |
db::is_lost_connection(&error) |
Dropped connection, server restart, or failed-over read-only primary |
Driver differences
The query builder writes the SQL each driver expects, and the schema builder writes the DDL, so portable queries need no branching. Raw SQL is sent as written, so keep these differences in mind when you drop down to SQL or reach for an advanced feature:
| Capability | PostgreSQL | MySQL / MariaDB | SQLite |
|---|---|---|---|
| Placeholders | $1, $2, ... |
? |
? |
RETURNING on writes |
INSERT, UPDATE, DELETE |
INSERT and DELETE on MariaDB; not on MySQL |
INSERT, UPDATE, DELETE |
| Native JSON columns | json, jsonb |
json |
text |
Case-insensitive like |
ilike |
The column's collation | ASCII letters only |
db::search |
Yes | Yes | No |
| Row-level locks | Yes | Yes | No |
| Upsert conflict target | Needs a unique index | Uses any primary or unique index | Needs a unique index |
CREATE INDEX CONCURRENTLY |
Via .online() |
Ignored | Ignored |
| Exact decimals | numeric |
decimal |
Approximate for fractional values |
| Vector columns | pgvector | MariaDB 11.7+ | No |
set columns |
No | Yes | No |
| Spatial indexes | With PostGIS | Yes | No |
When a feature is unavailable, the query or schema change fails with the database's own error when it runs. For database-specific SQL, match on connection.driver() or keep the branch in the migration that needs it, as Supporting several databases shows.
Transactions
When transferring funds between two accounts, both updates must succeed or fail together. Use db::transaction to run an async closure inside a database transaction on the default connection; dust-framework commits automatically when the closure returns Ok and rolls back on error:
use dust::db;let (from, to, amount) = (1_i64, 2_i64, 25_i64);db::transaction(async |tx| { db::query!(tx, "UPDATE accounts SET balance = balance - {amount} WHERE id = {from}") .update() .await?; db::query!(tx, "UPDATE accounts SET balance = balance + {amount} WHERE id = {to}") .update() .await?; Ok(())}).await?;The closure may borrow your variables and return a value, which db::transaction returns after the commit:
let order_id: i64 = db::transaction(async |tx| { let order_id = db::query!( tx, "INSERT INTO orders (user_id, total) VALUES ({user_id}, {total}) RETURNING id" ) .insert_returning_id() .await? .expect("inserted order ID"); db::query!(tx, "INSERT INTO order_items (order_id, sku) VALUES ({order_id}, {sku})") .insert() .await?; Ok(order_id)}).await?;To run a transaction on another connection, call transaction on that connection: db::connection("reporting")?.transaction(async |tx| { .. }).
Inside the closure, every query on the transaction's connection joins the transaction, even queries that don't go through tx. A helper function can run a plain db::query! or a model query and still see uncommitted rows, and its writes roll back with yours. The database session, cache, and queue stores, the unique and exists validation rules, and awaited listeners all participate in the active transaction.
Calling db::transaction inside another transaction's closure creates a savepoint. When the inner closure fails, only its writes roll back, and the outer transaction carries on. A function may wrap its own writes in db::transaction, and it works the same whether or not you call it inside your transaction.
A few queries behave differently inside a transaction:
- A query from a task started with
task::spawnfails, because the task could outlive the transaction. Await the work inside the transaction instead, or start it after the commit. - To write something that must survive a rollback, such as an audit entry, run it on
db::default_connection()?.outside_transaction(). - On MySQL and SQLite, a query inside an
eachclosure fails, because the cursor holds the transaction's connection. Read the rows withselectfirst. - MySQL commits the transaction when it runs a statement that changes a table, such as
CREATE TABLE, so keep schema changes out of transactions.
Handling deadlocks
Under high concurrency, two transactions can deadlock and cause the database to abort one of them. transaction_with_attempts retries the closure automatically when a deadlock or MySQL/SQLite lock wait timeout occurs, up to the total number of attempts specified:
use dust::db;let id = 42_i64;db::transaction_with_attempts(3, async |tx| { db::query!(tx, "UPDATE accounts SET balance = balance + 1 WHERE id = {id}") .update() .await?; Ok(())}).await?;Each attempt runs a fresh copy of the closure, so the closure must be Clone. It may borrow your variables, but not change them. Other errors, such as a constraint violation, don't retry. Keep side effects that can't run twice, such as sending an email, out of the closure, and register them as after-commit work instead.
After-commit work
Some work should happen only once the data it describes is committed, such as sending an order confirmation. db::after_commit registers that work from anywhere inside a transaction, without passing the transaction around. This function records an order, and logs it once the order is committed:
use dust::db;pub async fn place_order(user_id: i64, total: i64) -> dust::Result<()> { db::query!("INSERT INTO orders (user_id, total) VALUES ({user_id}, {total})") .insert() .await?; db::after_commit(async move || { tracing::info!(user_id, "Order placed"); Ok(()) }) .await}db::transaction(async |_| place_order(1, 4_999).await).await?;When no transaction is active, the callback runs immediately. If the transaction rolls back, dust-framework discards it. Inside a nested savepoint, the callback waits until the outermost transaction commits.
The callback runs after the connection is released, so it may query the committed data. Its closure must own what it captures, which is why the example uses async move. If the callback fails, db::transaction returns an AfterCommitError, while the committed data remains saved.
After-commit callbacks are held in memory, so they are lost if the process stops before they run. For durable follow-up work, dispatch a queued job instead. Jobs dispatched inside a transaction automatically wait for the commit, and so do events, except for listeners marked at_dispatch.
Managing a transaction yourself
db::transaction commits and rolls back for you, and it's the right choice for most code. When you need to decide yourself when to commit or roll back, call db::begin, or begin on a connection. Calling begin on a transaction creates a savepoint:
use dust::db;let mut transaction = db::begin().await?;db::query!(transaction, "INSERT INTO notes (body) VALUES ('Keep this note')") .insert() .await?;let mut savepoint = transaction.begin().await?;db::query!(savepoint, "INSERT INTO notes (body) VALUES ('Discard this note')") .insert() .await?;savepoint.rollback().await?;transaction.commit().await?;Dropping a transaction you haven't committed rolls it back. Queries that don't go through the transaction, and db::after_commit, join it only inside transaction.scope(async |tx| { .. }).
Using multiple connections
db::query! runs on your default connection. To run a query on another, look the connection up by name with db::connection and pass it before the SQL:
use dust::db;let reporting = db::connection("reporting")?;let month = "2026-10";let totals = db::query!( reporting, "SELECT region, SUM(total) FROM sales WHERE month = {month} GROUP BY region").select().await?;db::default_connection() returns the default connection. Connection handles are cheap to clone and do not open a pool until the first query runs. Because dust-framework does not translate raw SQL across database engines, you can match on connection.driver() when writing database-specific SQL:
use dust::db::{self, Driver};let connection = db::default_connection()?;let version = match connection.driver() { Driver::Postgres => db::query!(connection, "SELECT version()") .scalar::<String>() .await?, Driver::MySql | Driver::MariaDb => db::query!(connection, "SELECT VERSION()") .scalar::<String>() .await?, Driver::Sqlite => db::query!(connection, "SELECT sqlite_version()") .scalar::<String>() .await?,};Scoped default connections
Some applications keep each tenant in its own database, so every query in a request must go to that tenant's connection. db::using_connection changes the default connection while a future runs, for every query inside it, including the query builder's and your models':
use dust::db;db::using_connection("tenant_42", async { let count = db::query!("SELECT COUNT(*) FROM projects").scalar::<i64>().await?; // ... Ok::<_, dust::Error>(())}).await?;The default goes back to the previous one when the future finishes. Tasks you start with task::spawn inherit the override, but raw Tokio tasks don't.
Adding connections at runtime
You can register and remove named connections at runtime by injecting DatabaseManager. Calling add_connection registers a connection lazily without opening its pool until the first query runs, and remove_connection unregisters it and closes its pool once active queries finish:
use dust::config::database::ConnectionConfig;use dust::container::Inject;use dust::db::DatabaseManager;pub async fn connect_shard(database: Inject<DatabaseManager>, shard: &str, url: String) { database.add_connection(shard, ConnectionConfig::new(url));}pub async fn disconnect_shard(database: Inject<DatabaseManager>, shard: &str) { database.remove_connection(shard);}Registered connections remain in DatabaseManager until removed, so keep the number of named connections bounded. For one-off or temporary connections, such as importing from a customer-supplied database, call database.connect instead to create an unregistered connection whose pool closes automatically when the handle drops:
use dust::config::database::ConnectionConfig;use dust::container::Inject;use dust::db::{self, DatabaseManager};pub async fn import_from( database: Inject<DatabaseManager>, url: String,) -> dust::Result<i64> { let external = database.connect(ConnectionConfig::new(url))?; let count = db::query!(external, "SELECT COUNT(*) FROM customers") .scalar::<i64>() .await? .unwrap_or(0); Ok(count)}Read and write connections
As your traffic grows, you may want to send SELECT statements to read replicas and every write to your primary database. List your replicas' hosts in DB_READ_HOSTS, separated by commas:
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,replica-2.internal:5433
DB_STICKY=trueEach replica connects with DATABASE_URL's credentials, database, and options, and changes only the host, and the port when you give one. dust-framework picks a replica at random for each new connection.
Sometimes a replica needs its own credentials, such as a read-only user, or a different database name. For that replica, list its full URL instead of its host, and dust-framework uses the URL as written. You may mix both forms in one list:
DATABASE_URL=postgres://app:secret@primary.internal/app
DB_READ_HOSTS=replica-1.internal,postgres://reader:secret@replica-2.internal/appIf your provider gives the primary its own URL, such as a writer endpoint that fails over to a new primary, set it in DB_WRITE_URL. Writes and transactions then use DB_WRITE_URL, while host-only replicas still take their credentials, database, and options from DATABASE_URL:
DATABASE_URL=postgres://app:secret@db.internal/app
DB_WRITE_URL=postgres://app:secret@writer.db.internal/app
DB_READ_HOSTS=reader-1.db.internal,reader-2.db.internalEvery URL on a connection must use the same database driver, so you can't pair a PostgreSQL writer with MySQL replicas. Tests that refresh the database still create their databases from DATABASE_URL.
These variables configure the default connection. To give another connection replicas, or to configure them in code, give the connection a read endpoint, and optionally a write endpoint, in src/config/database.rs:
use dust::config::database::{ConnectionConfig, Endpoint};database.add_connection( "reporting", ConnectionConfig::new("postgres://app:password@reporting/app") .read(Endpoint::hosts(["reporting-replica-1", "reporting-replica-2"])) .sticky(true),);Endpoint::hosts keeps the connection's credentials, database, and options, and changes only the host. To connect with other credentials, use Endpoint::new(url) instead. To read a list in the same format as DB_READ_HOSTS from a variable of your own, use env.get::<Endpoint>("REPORTING_READ_HOSTS").
When you configure the default connection in code and call apply_env, each of these variables that's set replaces the setting it names, and the connection keeps the settings whose variables aren't set.
dust-framework routes each query by the method that runs it. select, select_one, scalar, and cursors read from a replica. Writes, the returning methods, and every query in a transaction use the writer: DB_WRITE_URL when it's set, and DATABASE_URL otherwise. Raw queries, the query builder, and models all follow these rules.
Replicas can lag briefly behind the writer. With sticky enabled, once a request, queued job, or console command writes to the connection, subsequent reads use the writer for the remainder of that request, job, or command so it always reads its own writes. To force a single query onto the writer, such as reading a row written by another request, call use_write_connection:
use dust::db;let id = 42_i64;let order = db::query!("SELECT * FROM orders WHERE id = {id}") .use_write_connection() .select_one() .await?;To send every read to the writer for the rest of the request, call use_write_connection_when_reading(true) on the connection.
Preventing stale reads across requests
If a user updates a post and then reloads the page, a read replica may still show the old title. The sticky option ends when the update request ends. To send the user's next requests to the writer while replicas catch up, append PreventStaleDatabaseReads to the web middleware group in src/app.rs:
use dust::http::middleware::PreventStaleDatabaseReads;.with_middleware(|middleware, _| { middleware.web(|web| { web.append(PreventStaleDatabaseReads::default()); });})For two seconds after a write to the default connection, the middleware sends reads on that connection to the writer for requests in the same session. If your replicas need more time, pass a duration instead:
use dust::time::ToSpan;web.append(PreventStaleDatabaseReads::new(5.seconds()));The middleware must run after StartSession. When you use the database session driver, dust-framework loads the session from the writer even before the middleware runs. Reads from other sessions and on other connections keep their usual routing.
Listening for queries
To see each query your application runs, such as to log slow ones, register a listener with db::listen. Do it in a booted callback in src/app.rs, or in a service provider's boot method:
use dust::db;use dust::time::ToSpan;.booted(async |_| { db::listen(|query| { if query.elapsed > 500.milliseconds() { let types: Vec<_> = query .bindings .iter() .map(|binding| binding.type_name) .collect(); tracing::warn!( connection = %query.connection, sql = %query.sql, bindings = ?types, elapsed = %query.elapsed, location = %query.location, "Slow query", ); } });})The listener receives a QueryInfo for every successful query across all connections, including the begins, commits, rollbacks, and savepoints of transactions, exposing connection, sql, elapsed, location, and bindings. Each entry in query.bindings provides the parameter's Rust type_name while leaving value as None by default so passwords and tokens stay out of your logs.
Native SQLx access
When you need something dust-framework doesn't wrap, such as a type only one database has, use SQLx directly. dust-framework re-exports it as dust::db::sqlx. db::default_connection_for and db::connection_for return a connection for one driver, whose queries bind values with bind and return SQLx's own rows:
use dust::db::{self, sqlx::{Postgres, Row}};let connection = db::default_connection_for::<Postgres>()?;let rows = connection .query("SELECT name FROM users WHERE tags @> $1") .bind(vec!["beta"]) .select() .await?;let names = rows.iter().map(|row| row.try_get("name")).collect::<Result<Vec<String>, _>>()?;PostgreSQL numbers its placeholders $1, $2, and so on, while MySQL and SQLite use ?. For SQLx's own query functions, check out a native connection from the pool with acquire. It goes back to the pool when you drop it, so drop it as soon as you're done:
let mut native = connection.acquire().await?;let count: i64 = db::sqlx::query_scalar("SELECT count(*) FROM users") .fetch_one(&mut *native) .await?;In a transaction that you begin on such a connection, run SQLx queries on tx.native() instead, so they join the transaction.
Queries you run on a native connection skip dust-framework's query listeners and sticky reads. After writing through one on a sticky connection, call connection.set_record_modification_state(true).
Troubleshooting
When a query fails, the error names the database message, connection, driver, and SQL, so start there. These are the failures you are most likely to meet:
| Symptom | Likely cause | What to do |
|---|---|---|
couldn't acquire a connection |
Pool too small, or a slow each/cursor holds a connection |
Raise DB_MAX_CONNECTIONS, shorten the work, or read with select |
no such table in a test |
Migrations have not run against the test database | Enable refresh_database |
duplicate key value violates unique constraint |
A unique index rejected the write | Handle it with db::is_unique_violation, or use an upsert |
there is no unique or exclusion constraint matching the ON CONFLICT specification |
An upsert names columns without a unique index on PostgreSQL or SQLite | Add the unique index in a migration |
database is locked on SQLite |
Two writers, or a long write transaction | Keep write transactions short and retry with transaction_with_attempts |
| An old value after a write | A replica has not caught up | Set DB_STICKY, use use_write_connection, or add PreventStaleDatabaseReads |
operator does not exist or a syntax error |
Raw SQL written for another driver | Branch on connection.driver(), or use the schema and query builders |
To see the exact statement and its bound types, register a query listener and log query.sql, or call to_sql() on a query builder before running it. Values are never included in an error message, so a query that fails on a value needs the value logged by your own code, not by the driver.
Testing
Tests that touch the database need tables to query and a clean slate each time. New applications call refresh_database in src/testing.rs so each test starts from your migrations and rolls back when it ends. For a complete overview of database assertions, seeding, and refreshing the database in tests, see testing the database.