Database: Models
- Introduction
- Declaring models
- Retrieving models
- Route model binding
- Creating models
- Updating models
- Deleting models
- Serializing models
- Hooks
- Events
- Model reference
- Common pitfalls
- Performance notes
- Testing
Introduction
dust-framework includes a built-in object-relational mapper (ORM) for working with your database using typed Rust structs. Each database table has a corresponding model that lets you query, insert, update, and delete records while checking column names, relationships, and types at compile time.
A model is a Rust struct annotated with #[model], where each field maps to a column and each instance represents a row. Models build on the same query builder used for raw tables, and use the create! and update! macros to write changes safely.
Before getting started, configure a database connection and create the model's table with a migration. Models live in src/models/, one file per model, alongside the included User model:
// src/models/post.rsuse dust::model::{BelongsTo, model};use dust::time::Timestamp;use crate::models::User;#[model]pub struct Post { pub id: i64, pub user_id: i64, pub title: String, pub body: Option<String>, #[default] pub votes: i64, #[default] pub views: i64, pub published_at: Option<Timestamp>, pub created_at: Timestamp, pub updated_at: Timestamp, #[belongs_to] pub user: BelongsTo<User>,}#[default] marks a column that has a database default (such as votes and views), allowing you to omit those fields in create! and receive the database-assigned value back. The user field is not a database column; it defines a relationship to the user who authored the post.
You can query a model directly from a route handler:
use dust::prelude::*;use crate::models::Post;pub async fn index() -> dust::Result<Json<Vec<Post>>> { let posts = Post::query() .filter(Post::votes.gt(100) & Post::published_at.is_not_null()) .order_by(Post::published_at.desc()) .get() .await?; Ok(Json(posts))}Post::votes and Post::published_at are typed columns. Because each column carries its Rust type, comparing Post::votes against a string fails at compile time rather than failing at runtime.
Model or query builder?
A model is a typed mapper for one table. It knows the table name, the primary key, every column's Rust type, and the relationships you declared. That knowledge buys you compile-time column checks, hooks, events, managed timestamps, fill structs, route binding, and relationship helpers. It does not change how SQL runs: a model query compiles to the same statements as db::table, on the same connection, inside the same transaction.
| You need | Use |
|---|---|
| Hooks, events, timestamps, route binding, relationships | A model |
| Compile-time column names and value types | A model |
| A projection, aggregate, tuple, or derived table | db::table |
| A bulk write that should skip per-row events | Either, but say so deliberately |
| Rows from a table that has no model | db::table |
Two model instances are snapshots of rows, not shared handles. Loading the same row twice gives two independent values, and changing one does not change the other until you write and reload it. is compares identity by key and connection; == compares every field when you derive PartialEq.
Declaring models
Apply #[model] to a struct with named fields. Each field's Rust type determines how its column is read and written, and nullable columns are wrapped in Option<T>.
Fields fall into a few kinds:
| Field | Example | Stored in the table |
|---|---|---|
| Column | pub title: String |
Yes |
| Nullable column | pub body: Option<String> |
Yes, and may be NULL |
| Column with a database default | #[default] pub votes: i64 |
Yes, and may be omitted on create |
| Renamed column | #[column("is_admin")] pub admin: bool |
Yes, under the database name |
| Primary key | #[key] pub uuid: Uuid |
Yes |
| Relationship | #[belongs_to] pub user: BelongsTo<User> |
No, joined on demand |
| Embedded value | #[embed] pub total: Money |
Yes, one column per inner field |
| Morph type | pub commentable_type: MorphType<Commentable> |
Yes, as the type column |
The struct's field order does not matter; column names and types do. When a table has a column that a model does not declare, the model ignores it on read and never writes it. That is useful during an expand-and-contract migration, but it also means a model can drift from its table until a write fails.
Table and column names
dust-framework infers table, primary key, and column names by convention, so most models require no overrides:
| Convention | Rule | Override |
|---|---|---|
| Connection | The default connection | #[model(connection = "directory")] |
| Table | The struct's name in snake case, made plural: BlogPost is blog_posts, and Category is categories |
#[model(table = "people")] |
| Key | The id field |
#[key] on another field |
| Column | The field's name | #[column("is_admin")] on the field |
| Route key | The key | #[model(route_key = "slug")] |
use dust::model::model;use dust::str::Uuid;#[model(table = "people", connection = "directory", route_key = "slug")]pub struct Person { #[key] pub uuid: Uuid, pub slug: String, #[column("is_admin")] pub admin: bool,}#[model] generates associated functions and methods such as query, find, create, update, and delete, so a struct field cannot reuse those names. If a table has a column named query, name the Rust field something else and annotate it with #[column("query")].
Primary keys
dust-framework determines how new primary keys are generated from the key field's type. Most tables use an auto-incrementing i64 key assigned by the database:
| Key type | New keys |
|---|---|
i64, i32, and the other integer types |
Assigned by the database, such as with the auto-incrementing column created by table.id() |
Uuid |
create generates a time-ordered version 7 UUID |
Ulid |
create generates a ULID |
String |
Must be provided explicitly when creating the model |
Defining fields
Each field on a model struct corresponds to a column in its database table. Wrap nullable columns in Option<T>, and annotate columns that have a database default value with #[default] so you can omit them when creating records.
For example, an Invoice model might combine numbers, exact decimals, calendar dates, IP addresses, and timestamps:
use std::net::IpAddr;use dust::model::model;use dust::numeric::Decimal;use dust::str::Uuid;use dust::time::{Timestamp, civil::Date};#[model]pub struct Invoice { pub id: Uuid, pub number: String, pub subtotal: Decimal, #[default] pub paid: bool, pub due_on: Option<Date>, pub billed_from: Option<IpAddr>, pub created_at: Timestamp, pub updated_at: Timestamp,}dust-framework supports the following field types out of the box (any of them may be wrapped in Option<T> for nullable columns):
| Rust type | Import | Column kind |
|---|---|---|
i8, i16, i32, i64 |
Prelude | Signed integers |
u8, u16, u32, u64, usize |
Prelude | Unsigned integers |
f32, f64 |
Prelude | Floating-point numbers |
Decimal |
dust::numeric::Decimal |
Exact decimals (money, rates) |
bool |
Prelude | Booleans |
String |
Prelude | Text / VARCHAR |
Vec<u8> |
Prelude | Binary / BLOB / BYTEA |
Timestamp |
dust::time::Timestamp |
Timestamps (TIMESTAMPTZ / TIMESTAMP) |
civil::Date, civil::Time, civil::DateTime |
dust::time::civil |
Calendar dates, times, and datetimes |
Uuid, Ulid |
dust::str |
UUIDs and ULIDs |
IpAddr, Ipv4Addr, Ipv6Addr |
std::net |
IP addresses |
Json<T>, serde_json::Value, #[derive(db::Json)] |
dust::db |
JSON columns |
#[derive(Enum)] |
Prelude | Enum columns |
Vector |
dust::db::Vector |
Vector embeddings (pgvector / MariaDB) |
Encrypted<T> |
dust::crypt::Encrypted |
Encrypted columns |
PasswordHash |
dust::hash::PasswordHash |
Hashed passwords |
RememberToken |
dust::auth::RememberToken |
Authentication remember tokens |
Timestamps
If your model defines created_at and updated_at fields (as Timestamp or Option<Timestamp> to match table.timestamps()), dust-framework populates both automatically on create! and refreshes updated_at on every update. If you explicitly pass a timestamp during a create or update, dust-framework preserves your value, which is useful when importing historical records. dust-framework truncates model timestamps to the connection's time precision so they match what the database stores.
Model query methods (update, increment, and decrement) also maintain updated_at. Bulk insert calls and raw db::table queries do not set timestamps automatically, so supply them explicitly when needed.
Enum columns
To store a Rust enum in a text column, derive Enum alongside Clone, Debug, Serialize, and Deserialize. dust-framework stores each variant using its Serde name (such as "pro" with #[serde(rename_all = "snake_case")]):
// src/models/customer.rsuse dust::prelude::*;use dust::model::model;use serde::{Deserialize, Serialize};#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]pub enum Plan { Free, Pro,}#[model]pub struct Customer { pub id: i64, pub email: String, pub plan: Plan,}Enum columns work with typed queries and writes, such as Customer::plan.eq(Plan::Pro) and update!(customer { plan: Plan::Pro }). To store an enum whose variants carry data, derive db::Json and store it in a JSON column instead.
JSON columns
When a column stores structured JSON data, such as user preferences or integration settings, define a Rust struct for the shape and derive db::Json alongside Clone, Debug, Serialize, and Deserialize. Back the column with table.json(..) or table.jsonb(..) in your migration:
// src/models/user.rsuse dust::db;use dust::model::model;use serde::{Deserialize, Serialize};#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Json)]pub struct Preferences { pub theme: String, pub notifications: bool,}#[model]pub struct User { pub id: i64, pub email: String, pub preferences: Preferences,}If you don't need a dedicated struct, fields may also use Json<Vec<T>>, Json<HashMap<K, V>>, or serde_json::Value.
When creating a model with a db::Json field, pass a variable or wrap an inline struct literal in parentheses inside create! so it isn't parsed as a nested related model:
use dust::model::create;let preferences = Preferences { theme: "light".into(), notifications: true,};let mut user = create!(User { email: "taylor@example.com", preferences }).await?;To replace the whole JSON value, pass the updated struct to update!:
use dust::model::update;let mut preferences = user.preferences.clone();preferences.theme = "dark".into();update!(user { preferences }).await?;To update a single nested key in place without replacing the entire JSON document, call update_values with db::values! and arrow notation (column->key). Calling update_values on a model writes the change in SQL and reloads the model in place, while calling it on a query updates all matching rows in a single statement:
use dust::db::values;user.update_values(values! { "preferences->theme": "dark" }).await?;User::query() .filter(User::id.eq(user.id)) .update_values(values! { "preferences->notifications": false }) .await?;You can also filter models by JSON keys directly on the typed column with path, separating nested keys with -> and indexing arrays with [n], or check JSON array membership and length with json_contains and json_length:
let dark_mode_users = User::query() .filter(User::preferences.path("theme").eq("dark")) .get() .await?;let email_subscribers = User::query() .filter(User::preferences.path("notifications->email").eq(true)) .filter(User::preferences.path("languages[0]").eq("en")) .get() .await?;To learn more about JSON path expressions, json_contains, and json_length, check out the query builder's JSON columns section.
Values over several columns
When a value spans multiple columns, such as a price with an amount and currency that you want to sum and index separately, derive db::Embed on a struct holding those columns and mark the model field #[embed]:
// src/models/order.rsuse dust::db;use dust::model::model;use serde::{Deserialize, Serialize};#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, db::Embed)]pub struct Money { pub amount: i64, pub currency: String,}#[model]pub struct Order { pub id: i64, #[embed] pub total: Money, #[embed(prefix = "refunded")] pub refunded: Money,}By default, dust-framework prefixes each embedded column with the model's field name, so total maps to total_amount and total_currency, and refunded maps to refunded_amount and refunded_currency. Pass #[embed(prefix = "")] to use the embedded struct's field names without a prefix. The embedded struct should derive Clone, Debug, Serialize, and Deserialize alongside db::Embed, and each of its fields must be a valid column type.
Passing a single Money value populates all of its underlying columns across create!, update!, fill structs, and query updates. Wrap a struct literal in parentheses inside create! so it is not parsed as a nested related model:
use dust::model::{create, update};let usd = |amount| Money { amount, currency: "USD".into() };let mut order = create!(Order { total: usd(1500), refunded: (Money { amount: 0, currency: "USD".into() }),}).await?;update!(order { refunded: usd(500) }).await?;Order::total exposes a typed column for each embedded field, allowing you to filter or pluck individual sub-columns, or compare the entire embedded value at once with eq and ne:
let large_orders = Order::query() .filter(Order::total.amount.gt(1000)) .get() .await?;let currencies = Order::query() .pluck(Order::total.currency) .await?;let price = Money { amount: 1500, currency: "USD".into() };let matching = Order::query().filter(Order::total.eq(&price)).get().await?;let others = Order::query().filter(Order::total.ne(&price)).get().await?;Updates only write the sub-columns that actually changed, and JSON serialization represents the field as a nested object (such as "total": { "amount": 1500, "currency": "USD" }).
Retrieving models
Once you have declared a model and migrated its table, you can retrieve all records from the table using all:
use crate::models::Post;let posts = Post::all().await?;For filtering, ordering, limits, or pagination, begin a query with Post::query(), which wraps the query builder for the model's table, and finish it with get:
let posts = Post::query() .filter(Post::published_at.is_not_null()) .order_by(Post::published_at.desc()) .limit(10) .get() .await?;To retrieve a single model by its primary key, call find, which returns Option<Post>:
let post: Option<Post> = Post::find(1).await?;If you'd rather fail with a 404 response when no matching row exists, use find_or_fail. It returns a ModelNotFound error that dust-framework automatically converts into a 404 response (rendering No query results for model `Post` with the key `1`. for JSON clients or a 404 error page for browsers):
use dust::prelude::*;use crate::models::Post;pub async fn show(Params(id): Params<i64>) -> dust::Result<Json<Post>> { // Returns a 404 response automatically if no post has this ID... let post = Post::find_or_fail(id).await?; Ok(Json(post))}When a model's ID comes directly from a route parameter like this, you'll usually let route model binding load the model and return the 404 for you automatically.
To retrieve multiple models by their primary keys in a single query, pass a list of keys to find_many:
let posts = Post::find_many([1, 2, 3]).await?;To retrieve the first model matching a condition, use first_where, or chain first or first_or_fail onto a query. Like find_or_fail, first_or_fail responds with a 404 when no row matches:
let post = Post::first_where(Post::title.eq("Hello")).await?;let post = Post::query() .filter(Post::votes.gt(100)) .order_by(Post::published_at.desc()) .first() .await?;let post = Post::query() .filter(Post::slug.eq(slug)) .first_or_fail() .await?;When you already have a collection of models and need their primary keys, call keys() on the slice or Vec to extract them in order:
let users = User::query() .order_by(User::name) .limit(10) .get() .await?;let posts = Post::query() .filter(Post::user_id.is_in(users.keys())) .get() .await?;To retrieve a single column's values without hydrating full models, pass a typed column to pluck (returning Vec<T>) or value (returning Option<T>). Both infer the column's exact Rust type automatically:
let titles = Post::query() .order_by(Post::title) .pluck(Post::title) .await?;let title = Post::query() .filter(Post::id.eq(1)) .value(Post::title) .await?;[!NOTE] Because hydrating a model requires every column, model queries always select all columns and do not expose
selectoradd_select. To include computed values from related records, such as each post's comment count, usewith_countand other relationship aggregates. To select only a subset of columns into a custom struct, usedb::tableinstead.
Filtering with typed columns
#[model] generates a typed column constant for every field on your struct, such as Post::title and Post::votes. Each column provides type-checked comparison methods like eq, ne, lt, gt, is_in, and is_null, so comparing a column against the wrong type fails at compile time:
let posts = Post::query() .filter(Post::user_id.eq(user.id)) .filter(Post::votes.ge(10)) .filter(Post::published_at.is_not_null()) .get() .await?;let selected = Post::query() .filter(Post::id.is_in([1, 2, 3])) .filter(Post::title.ne("Draft")) .get() .await?;Each comparison accepts an owned value, a reference, or another column of the same type; String columns also accept &str, and Option<T> columns accept T. Combine conditions with &, |, and !:
let posts = Post::query() .filter(Post::title.starts_with("dust-framework") & Post::votes.ge(10)) .filter(Post::updated_at.gt(Post::created_at)) .order_by(Post::votes.desc()) .get() .await?;Here are all of the comparison and ordering methods available on typed columns:
| Method | Columns | SQL |
|---|---|---|
eq, ne, lt, le, gt, ge |
Every column | =, <>, <, <=, >, >= |
is_in(values), is_not_in(values) |
Every column | in (...), not in (...). An empty is_in matches no rows, an empty is_not_in matches every row, and a subquery matches the rows it returns |
between(low, high) |
Every column | between ... and ... |
is_null(), is_not_null() |
Option<T> columns |
is null, is not null |
like(pattern) |
String and Option<String> columns |
like, where % and _ are wildcards |
like_case_sensitive(pattern) |
String and Option<String> columns |
Case-sensitive like across all databases |
starts_with, ends_with, contains |
String and Option<String> columns |
like, where % and _ in the text match only themselves |
is_past(), is_future() |
Timestamp and Option<Timestamp> columns |
< or > the current time |
is_today(), is_before_today(), is_after_today() |
Timestamp and Option<Timestamp> columns |
The column's date =, <, or > today's date in UTC |
asc(), desc() |
Every column | An ordering |
You may also pass typed columns anywhere the query builder expects a column, including order_by, pluck, and group_by([Post::user_id]).
When you need a SQL condition that typed columns do not model, combine them with db::raw!:
use dust::db;let posts = Post::query() .filter(Post::votes.gt(100) & db::raw!("extract(dow from created_at) = 1")) .get() .await?;Aggregates
Model queries support the same aggregate methods as db::table, including count, exists, sum, avg, min, and max:
let published = Post::query() .filter(Post::published_at.is_not_null()) .count() .await?;let has_drafts = Post::query() .filter(Post::published_at.is_null()) .exists() .await?;let total_votes: Option<i64> = Post::query().sum(Post::votes).await?;let average_votes: Option<f64> = Post::query().avg(Post::votes).await?;let top_votes: Option<i64> = Post::query().max(Post::votes).await?;Comparing with subqueries
Sometimes the value you want to compare against lives in another table or requires an aggregate across rows. For example, you might list the posts written by anyone who has commented on a featured post, or the posts with more votes than the site's average. Rather than loading those values first, call select_column on a model query to narrow it to a single column or aggregate expression, and pass it to is_in or any comparison so the database runs it as a subquery:
let commented = Comment::query() .join("posts", Post::id.eq(Comment::post_id)) .filter(Post::featured.eq(true)) .select_column(Comment::user_id);let posts = Post::query() .filter(Post::user_id.is_in(commented)) .get() .await?;let average = Post::query().select_column(Post::votes.avg());let popular = Post::query() .filter(Post::votes.gt(average)) .get() .await?;You may pass any typed column, column aggregate (count, count_distinct, sum, avg, min, max), or db::table query selecting a single column.
Paginating results
When displaying a long list of models, call paginate on a model query to return a single page of records along with page links and totals:
let posts = Post::query() .filter(Post::published_at.is_not_null()) .order_by(Post::published_at.desc()) .paginate(15) .await?;You may also call simple_paginate for previous/next pagination without a total count query, or cursor_paginate for cursor-based pagination on large datasets. To learn more about rendering pagination links, infinite scroll, and customizing page URLs, check out the pagination guide.
Scopes
If you find yourself reusing the same filter across queries, such as popular or published posts, you can define a scope as an associated function on your model returning db::Condition, then pass it to filter:
use dust::db::Condition;impl Post { pub fn popular() -> Condition { Post::votes.gt(100) } pub fn is_published() -> Condition { Post::published_at.is_not_null() }}let posts = Post::query() .filter(Post::popular() & Post::is_published()) .get() .await?;Because #[model] defines a typed column constant for every field, give scopes distinct names from column fields (such as is_published rather than published_at).
Scopes may also accept parameters, such as filtering posts by a specific author:
impl Post { pub fn by(user: &User) -> Condition { Post::user_id.eq(user.id) }}let posts = Post::query() .filter(Post::by(&user) & Post::is_published()) .get() .await?;If a reusable scope needs to apply ordering, limits, or eager loads in addition to filters, accept and return Builder<Self>, and chain it onto any query with scope:
use dust::db::Builder;impl Post { pub fn trending(query: Builder<Post>) -> Builder<Post> { query.filter(Post::votes.gt(10)).order_by(Post::votes.desc()).limit(10) }}let posts = Post::query() .filter(Post::is_published()) .scope(Post::trending) .get() .await?;Chunking and streaming
When a console command or background job needs to process tens of thousands of models, loading them all into memory at once is impractical. Instead, stream models in pages with chunk_by_id, which paginates by primary key so it remains safe even if your loop updates or deletes rows as it goes:
use dust::stream::TryStreamExt;let mut pages = Post::query().filter(Post::votes.eq(0)).chunk_by_id(100);while let Some(posts) = pages.try_next().await? { for post in posts { post.delete().await?; }}lazy_by_id yields the same paged results one model at a time, and chunk paginates using the query's own order_by clause. Use chunk_by_id_desc or lazy_by_id_desc to walk primary keys from highest to lowest. All of these chunked methods eager-load any relationships requested with with for each page. By contrast, cursor streams individual rows over a single query and therefore cannot eager-load relationships.
Ordering results
To sort model queries, pass a typed column to order_by (ascending by default, or call .desc() for descending order). Chaining multiple order_by calls adds tie-breakers in order:
let posts = Post::query() .order_by(Post::votes.desc()) .order_by(Post::title) .get() .await?;For sorting by a timestamp column, latest orders newest first and oldest orders oldest first:
let posts = Post::query().latest(Post::created_at).limit(10).get().await?;Sometimes you need to sort rows in a custom domain order rather than alphabetically or numerically. For example, a support queue should display urgent tickets before high-priority tickets, even though "urgent" sorts after "high" alphabetically:
// src/models/ticket.rsuse dust::prelude::*;use dust::model::model;use dust::time::Timestamp;use serde::{Deserialize, Serialize};#[derive(Clone, Copy, Debug, Serialize, Deserialize, Enum)]#[serde(rename_all = "snake_case")]pub enum Priority { Low, Medium, High, Urgent,}#[model]pub struct Ticket { pub id: i64, pub priority: Priority, pub created_at: Timestamp,}Use in_order_of to sort rows according to the position of their column value in a list. Any rows whose value is not in the list appear last:
use crate::models::{Priority, Ticket};let tickets = Ticket::query() .in_order_of(Ticket::priority, [Priority::Urgent, Priority::High]) .order_by(Ticket::created_at) .get() .await?;This query returns urgent tickets first, followed by high-priority tickets, and then low and medium tickets together (ordered oldest first within each group). Because in_order_of is type-checked against the column, [Priority::Urgent] compiles while ["urgent"] does not.
Comparing models
To check whether two model instances represent the same database record, such as checking whether a comment's author also wrote the post, call is or is_not. Loaded #[belongs_to] and #[has_one] relationships support both methods directly:
let post = Post::query() .with(Post::user) .with(Post::comments.with(Comment::user)) .find_or_fail(id) .await?;for comment in &post.comments { let from_author = comment.user.is(&post.user);}is compares only the models' primary keys and database connections, so a user loaded from an archive connection is not considered equal to a user with the same key on the default connection, while a model whose other columns were updated still matches its original record. If you want value-level comparison across every field (for example in tests), derive PartialEq and use ==. When a #[belongs_to] relationship is not loaded, compare the foreign key directly (post.user_id == user.id).
Route model binding
Routes that inspect or modify a model typically include its key in the URL, such as /posts/42. Instead of querying the post manually, declare it as a handler parameter. dust-framework resolves the model from the route parameter matching the struct name in snake case: {post} for Post, or {blog_post} for BlogPost:
// src/routes/web.rsroute.get("/posts/{post}", posts::show);use dust::prelude::*;use crate::models::Post;pub async fn show(post: Post) -> dust::Result<Json<Post>> { Ok(Json(post))}dust-framework matches the parameter against the model's primary key or configured route_key. A missing record or an unparseable value, such as /posts/hello for an i64 key, returns a 404 response automatically.
You may also pass a model directly to route! and redirect! in place of its raw key:
// "/posts/42", or "/posts/hello-world" with route_key = "slug"Ok(redirect!(posts::show, &post))When a route binds two parameters of the same model type, such as /users/{user}/friends/{friend}, extract one as user: User and resolve the other with request.model::<User>("friend").await?.
Customizing the key
Sometimes a single route should resolve a model by a different column. For example, a public blog route might look up posts by slug while admin routes continue using the primary key. Specify the column name after a colon in the route parameter while still extracting post: Post in the handler:
// src/routes/web.rsroute.get("/blog/{post:slug}", blog::show);route.get("/admin/posts/{post}", admin::posts::show);dust-framework parses the route segment using that column's Rust type, which must be text, an integer, a UUID, or a ULID. Naming a field that does not exist on the model fails with a 500 error naming the unknown field.
URL generation respects each route's parameter syntax automatically, so passing the same Post generates the right URL for both routes:
route!(blog::show, &post)?; // "http://localhost/blog/hello-world"route!(admin::posts::show, &post)?; // "http://localhost/admin/posts/42"If every route should bind a model by the same column, set route_key on #[model] instead as shown in Table and column names.
Nested models
A route can nest one model under another, such as /users/{user}/blog/{post:slug}. When the child parameter uses a custom key like {post:slug}, dust-framework scopes the post to that user automatically. A request for another user's post returns 404, allowing two users to each own a post with the slug hello-world:
route.get("/users/{user}/blog/{post:slug}", blog::show);When the child parameter binds by primary key (as in /users/{user}/posts/{post}), dust-framework binds it independently by default. To require that the child belong to the parent, call scope_bindings on the route or nested resource!:
route.get("/users/{user}/posts/{post}", posts::show).scope_bindings();resource!(users::posts).scope_bindings();To enable scoped bindings for an entire group of routes, call scope_bindings before group:
route.scope_bindings().group(|route| { route.get("/users/{user}/posts/{post}", posts::show); route.get("/teams/{team}/members/{user}", members::show);});dust-framework resolves the scoped child through a relationship connecting the two models. First, it looks for a relationship on the parent matching the pluralized child parameter name (such as User::posts for {post}), supporting #[has_one], #[has_many], #[belongs_to_many], and through relationships. With scope_bindings, /teams/{team}/members/{user} matches only members of that team, and /projects/{project}/deployments/{deployment} matches only deployments belonging to that project's environments. If the parent has no matching relationship name, dust-framework falls back to the child's #[belongs_to] relationship pointing to the parent, or to the sole relationship between the two models. Has-one-of-many relationships such as latest_order are never used to scope bindings, and filtered relationships such as admins never shadow an unfiltered relationship such as members.
The parent parameter is the parameter immediately preceding the child, named after its model (such as {user} for User). You may also name the parent parameter after a #[belongs_to] relationship on the child, such as {author} when Post declares an author relationship:
use dust::model::{BelongsTo, model};#[model]pub struct Post { pub id: i64, pub author_id: i64, pub title: String, #[belongs_to] pub author: BelongsTo<User>,}route.get("/authors/{author}/posts/{post}", posts::show).scope_bindings();In this handler, extract post: Post and look up the author with request.model::<User>("author").await?.
If two models share multiple relationships and none matches the parameter names, dust-framework responds with a 500 error listing the ambiguous relationships. If no relationship exists between the two models, the child binds without scoping.
To disable automatic scoping on a route with a custom key, call without_scoped_bindings on the route or group:
route.get("/users/{user}/blog/{post:slug}", blog::show).without_scoped_bindings();A route-level call overrides its group's setting, so an individual route inside a scope_bindings group can opt out with without_scoped_bindings and vice versa.
Creating models
create! inserts a row and returns the stored model populated with its generated key, timestamps, and database defaults. This handler creates a post for the logged-in user:
use dust::model::create;use dust::prelude::*;use crate::models::{Post, User};pub async fn store(Authenticated(user): Authenticated<User>) -> dust::Result<Redirect> { let post = create!(Post { title: "My first post", user: &user }).await?; Ok(redirect!(posts::show, &post))}Each field sets the column of the same name, and any omitted columns receive NULL or their database default. Shorthand field syntax works as in standard Rust struct literals, and a #[belongs_to] relationship accepts the related model so user: &user populates user_id.
Each field accepts a value of its column's type or a reference to clone from, along with common conversions: &str for String, T for Option<T>, dust::now() for Timestamp, and a plain-text password or Password for PasswordHash, which dust-framework hashes with hash::make before storing. If a value does not match the column, the compiler error lists the accepted types.
Fill structs
When creating models from request input, a client can submit fields your form never rendered. Allowing arbitrary fields to populate a model would let an attacker send is_admin=1 and escalate their privileges.
A fill struct explicitly lists the columns a request is allowed to write. Annotate it with #[dust::input(fills = Post)] to target the model and derive Deserialize, Validate, and Fill, then spread ..input at the end of create!:
use dust::model::create;use dust::prelude::*;use crate::models::{Post, User};#[dust::input(fills = Post)]#[validate(authenticated)]pub struct NewPost { #[validate(required, max_length(255))] pub title: String, #[validate(required)] pub body: String,}pub async fn store( Authenticated(user): Authenticated<User>, Valid(input): Valid<NewPost>,) -> dust::Result<Redirect> { let post = create!(Post { user: &user, ..input }).await?; Ok(redirect!(posts::show, &post))}Because a fill struct only writes the fields you declare on it, columns like user_id cannot be tampered with by the client. Define a dedicated fill struct for each form containing only the fields that form is allowed to modify. Explicit fields placed before ..input override values from input, matching Rust's struct update syntax.
Two field attributes customize how a field maps to the model:
#[fill(column = "nickname")]maps the form field to a differently named column on the model.#[fill(skip)]excludes the field from the model write, which is useful for extra inputs liketag_idsthat you handle separately.
If you need to keep using input after creating the model, such as reading a #[fill(skip)] field, borrow it with ..&input instead. For example, this handler creates a post and then attaches tags through a #[belongs_to_many] relationship:
use crate::models::Tag;#[dust::input(fills = Post)]#[validate(authenticated)]pub struct NewPost { #[validate(required, max_length(255))] pub title: String, #[fill(skip)] #[serde(default)] #[validate(max_items(10), each(exists(Tag::id)))] pub tag_ids: Vec<i64>,}pub async fn store( Authenticated(user): Authenticated<User>, Valid(input): Valid<NewPost>,) -> dust::Result<Redirect> { let post = create!(Post { user: &user, ..&input }).await?; post.tags().attach(&input.tag_ids).await?; Ok(redirect!(posts::show, &post))}update!(post { ..&input }) and the builder's fill(&input) accept a borrowed reference as well.
When building partial-update endpoints that only submit changed fields, wrap optional form fields in Sometimes<T>. To learn more, check out Updating only the fields a request sends.
To learn more about #[dust::input] structs, validation rules, authorization, and custom error messages, check out the validation guide.
Fill structs outside a request
When a fill struct doesn't come from an HTTP request, such as a domain struct used by a console command or background job, derive Fill directly with #[fills(Post)], and add Validate if you also want to check its fields with validate:
use dust::model::{Fill, create};use dust::validation::Validate;use crate::models::{Post, User};#[derive(Validate, Fill)]#[fills(Post)]pub struct PublishPost { #[validate(required, max_length(255))] pub title: String, #[validate(required)] pub body: String,}pub async fn publish(author: &User, input: PublishPost) -> dust::Result<Post> { input.validate().await?; create!(Post { user: author, ..input }) .await}Required columns
Every non-nullable column is required unless it carries #[default], is a generated primary key, or is a managed timestamp. If you omit a required column in create!, compilation fails with a message listing the missing fields:
error[E0080]: evaluation panicked: can't create a `Post` without `user` (or `user_id`) and `title`When a required column is supplied dynamically by a fill struct, a creating hook, or a relationship builder such as user.posts(), dust-framework defers the check until runtime and returns an error before executing the insert if anything is missing. You may also opt out of the compile-time check explicitly by ending the fields with .., as shown in first_or_create.
Creating related models together
Passing a struct literal for a relationship field inside create! inserts that related record automatically. dust-framework inserts #[belongs_to] parents before the main row, and inserts #[has_one], #[has_many], #[belongs_to_many], and their polymorphic counterparts afterward:
use dust::model::create;use crate::models::{Post, User};let post = create!(Post { title: "Hello", user: User { name: "Abigail", email: "abigail@example.com", password: "secret" },}).await?;To insert multiple models of the same type at once, pass a bracketed list to create!, which returns a Vec of the created models in order:
let posts = create!([ Post { title: "One", user: &user }, Post { title: "Two", user: &user },]).await?;Both forms wrap all inserts in a single transaction so any failure rolls everything back. The returned models already have their newly created relationships hydrated in memory, so reading post.user above requires no extra query, and child models created alongside a parent already hold that parent in their #[belongs_to] or #[morph_to] field.
Building a create in steps
When the columns to set depend on runtime conditions, use the builder returned by Post::create() instead of create!. It exposes a setter for every column and relationship, plus .fill(input) as the builder equivalent of ..input. This version of the store handler publishes the post immediately if the author's email is verified:
use dust::prelude::*;use crate::models::{Post, User};pub async fn store( Authenticated(user): Authenticated<User>, Valid(input): Valid<NewPost>,) -> dust::Result<Redirect> { let mut create = Post::create().user(&user).fill(input); if user.email_verified_at.is_some() { create = create.published_at(dust::now()); } let post = create.await?; Ok(redirect!(posts::show, &post))}Finding or creating models
Sometimes you want to retrieve an existing record matching a condition, or insert it if no match exists (such as looking up a user by email). Pass a condition and a create! expression or fill struct to first_or_create:
use dust::model::create;use crate::models::User;let user = User::first_or_create( User::email.eq(email), create!(User { name, password, .. }),).await?;When inserting a new row, dust-framework automatically copies any eq values combined with & from the lookup condition, so you do not need to repeat email inside create! (the trailing .. tells create! that the condition supplies it). Non-equality clauses such as gt or | are used only for the lookup.
update_or_create accepts the same arguments, but updates the matching row with the provided values if it already exists instead of returning it unchanged:
let user = User::update_or_create( User::email.eq("taylor@example.com"), create!(User { name: "Taylor Otwell", password: "secret", .. }),).await?;When you need to know whether the record was newly created or already existed (for example, to send a welcome email only on creation), chain .found_or_created() before awaiting. It returns FoundOrCreated::Created(model) or FoundOrCreated::Found(model):
use dust::mail;use dust::model::FoundOrCreated;use crate::mail::Welcome;let user = User::first_or_create(User::email.eq(email), create!(User { name, password, .. })) .found_or_created() .await?;if let FoundOrCreated::Created(user) = &user { mail::to(user).queue(Welcome::new(user)?).await?;}let user = user.into_model();If another concurrent request inserts the row between the lookup and the insert, the losing request resolves to Found, ensuring the welcome email is sent only once.
Add a unique index on the lookup columns (such as email) so concurrent requests cannot insert duplicate rows. With a unique index in place, dust-framework catches the constraint violation from the losing insert and fetches the winning row automatically.
Inserting many rows
When importing a large batch of records, inserting them one by one with create! is slow and you rarely need every hydrated model back. Use insert with the row! macro (or a list of fill structs) to write all rows in a single SQL statement and return the number of inserted rows:
use dust::model::row;use crate::models::User;let inserted = User::insert(row!([ User { email: "taylor@example.com", name: "Taylor", password: "secret" }, User { email: "abigail@example.com", name: "Abigail", password: "secret" },])).await?;When inserting a dynamic list of records, such as rows parsed from a CSV, map each item with a single-row row!(User { .. }) instead:
let rows = imports.into_iter().map(|item| { row!(User { email: item.email, name: item.name, password: item.password, })});let inserted = User::insert(rows).await?;insert still sets timestamps and hashes PasswordHash columns automatically. row! verifies required columns at compile time, while fill structs are validated before the statement executes.
When some incoming rows may already exist, use upsert to insert new rows and update existing ones in a single statement. Pass the rows, the unique columns that identify existing records, and the columns to update on conflict:
let rows = row!([ User { email: "taylor@example.com", name: "Taylor Otwell", password: "secret" }, User { email: "jess@example.com", name: "Jess", password: "secret" },]);let affected = User::upsert(rows, [User::email], [User::name]).await?;Because typed columns carry their Rust type, Rust arrays only accept columns of the same type. When matching on or updating columns with different types (such as a String and an Option<Timestamp>), pass a tuple instead:
// Same column types (`i64` and `i64`): pass an array...Post::upsert(posts, [Post::id], [Post::votes, Post::views]).await?;// Mixed column types (`String` and `Option<Timestamp>`): pass a tuple...User::upsert(users, [User::email], (User::name, User::email_verified_at)).await?;When a user with a matching email already exists, upsert updates only name and updated_at while leaving all other columns untouched. PostgreSQL and SQLite require a unique index on the identifying columns. MySQL and MariaDB detect conflicts using every primary or unique index on the table, as with the query builder's upsert.
Because insert and upsert write rows without hydrating models, they do not run hooks, dispatch events, or create nested related models (pass an existing parent such as user: &user instead).
Replicating models
When you want to create a new record that shares most of its attributes with an existing model, such as duplicating a shipping address as a billing address, spread ..shipping.replicate() at the end of create! and override only the fields that differ:
use dust::model::create;use crate::models::Address;let shipping = create!(Address { kind: "shipping", line_1: "123 Example Street", city: "Victorville", state: "CA", postcode: "90001",}).await?;let billing = create!(Address { kind: "billing", ..shipping.replicate() }).await?;The new row receives a fresh primary key and timestamps, and any fields before ..shipping.replicate() override the copied columns. Loaded relationships from shipping are not copied because related rows such as orders remain linked to the original row; load them on the new model when needed. A create builder also accepts the copy via .fill(shipping.replicate()).
To exclude specific columns from the copy so they fall back to their database defaults or NULL, chain .except(...) with an array (for columns of one type) or a tuple (for mixed types). For example, this handler duplicates a flight without copying its last flight time or pilot:
use dust::model::create;use dust::prelude::*;use crate::models::Flight;pub async fn duplicate(flight: Flight) -> dust::Result<Redirect> { let copy = create!(Flight { ..flight.replicate().except((Flight::last_flown_at, Flight::last_pilot_id)) }) .await?; Ok(redirect!(flights::show, ©))}Updating models
update! modifies an existing model and writes only the columns that changed along with updated_at. For example, this handler resolves a post via route model binding and updates it from a validated form:
use dust::model::update;use dust::prelude::*;use crate::models::Post;#[dust::input(fills = Post)]#[validate(anyone)]pub struct EditPost { #[validate(required, max_length(255))] pub title: String,}pub async fn update( mut post: Post, Valid(input): Valid<EditPost>,) -> dust::Result<Redirect> { update!(post { published_at: dust::now(), ..input }).await?; Ok(redirect!(posts::show, &post))}Field assignments follow the same rules as create!: passing None clears an Option column, and passing a related model to a #[belongs_to] field such as user: &other updates user_id. After awaiting, post reflects the updated values in memory. If no field values actually changed, dust-framework skips the query, hooks, and events completely.
To update multiple records in a single query, check out Updating many rows.
Updating only the fields a request sends
To distinguish omitted fields from explicit null values, declare those fields as Sometimes<T>. Omitted fields decode as Sometimes::Missing and are skipped by ..input, preserving their existing column values, while submitted fields decode as Sometimes::Present. For a Sometimes<Option<T>> field, an explicit null decodes as Present(None) and clears the column. For example, assuming users has a nullable bio column:
use dust::model::update;use dust::prelude::*;use dust::validation::Sometimes;use crate::models::User;#[dust::input(fills = User)]#[validate(authenticated)]pub struct EditProfile { #[validate(required, max_length(255))] pub name: Sometimes<String>, #[validate(max_length(1000))] pub bio: Sometimes<Option<String>>,}pub async fn update( Authenticated(mut user): Authenticated<User>, Valid(input): Valid<EditProfile>,) -> dust::Result<Redirect> { update!(user { ..input }).await?; Ok(Redirect::back())}With this form, sending {"name": "Taylor"} updates name without touching bio, whereas sending {"bio": null} clears bio without touching name.
Validation skips any Sometimes field omitted from the request, so required on name means the value cannot be empty when it is present. To learn more about validation rules and helper methods such as present(), check out Fields a request may leave out.
create! also skips missing Sometimes fields so their columns receive database defaults. Omit Sometimes on fields that a creation form must always supply.
Incrementing a column
Counters such as a post's view count are frequently updated by concurrent requests. Using += or -= inside update! emits an atomic database update (such as views = views + 1) so concurrent increments never overwrite each other, and updates the in-memory model afterward:
update!(post { views += 1 }).await?;update!(post { votes -= 1 }).await?;+= and -= work on integer, floating-point, and Decimal columns. You may also call post.increment(Post::views, 1) or post.decrement(Post::votes, 1) directly.
Building an update in steps
Just as Post::create() builds an insert dynamically, post.update() returns a builder exposing a setter for every column along with fill, increment, and decrement. For example, this code updates a post from a form and clears published_at when saving it as a draft:
use dust::time::Timestamp;let mut update = post.update().fill(&input);if input.draft { update = update.published_at(None::<Timestamp>);}update.await?;Because an Option column's setter accepts multiple optional types, annotate None with its inner type (such as None::<Timestamp>).
Updating many rows
When you need to apply the same change to every record matching a query, such as publishing all of a user's drafts, pass the query to update! instead of a single model to execute one bulk UPDATE statement without loading rows into memory:
use dust::model::update;use dust::prelude::*;use crate::models::{Post, User};pub async fn publish_drafts( Authenticated(user): Authenticated<User>,) -> dust::Result<Redirect> { update!(user.posts().filter(Post::published_at.is_null()) { published_at: dust::now(), }) .await?; Ok(Redirect::back())}update! returns the number of affected rows. Fields work like single-model updates, so misspelled columns and mismatched types fail to compile, and views += 1, ..input, and user: &editor all work. dust-framework also updates updated_at automatically unless you set it explicitly:
update!(Post::query().filter(Post::user_id.eq(old_author.id)) { user: &new_author,}).await?;update!(Post::query().filter(!Post::published_at.is_null()) { views += 1,}).await?;Because bulk query updates never instantiate models, they do not run hooks or dispatch events. When listeners must receive events for each changed record, load the models and update them individually.
You may also pass a relationship query to update!, including #[belongs_to_many] relationships, or build a bulk update dynamically with update(), increment, and decrement:
update!(post.tags() { featured: true }).await?;Post::query() .filter(Post::published_at.is_null()) .update() .published_at(dust::now()) .await?;Post::query() .filter(!Post::published_at.is_null()) .increment(Post::views, 1) .await?;For writes that typed setters cannot express, such as updating a single JSON path or computing a column from another column in SQL, call update_values with db::values!. Your query's filters, table, connection, and updated_at timestamp still apply, though column names and value types are not checked at compile time:
use dust::db::{col, values};Post::query() .filter(Post::votes.gt(100)) .update_values(values! { "options->theme": "dark", score: col("votes") * 2 }) .await?;Models also provide update_values, which updates the row and reloads it like refresh so the model reflects database-written columns:
post.update_values(values! { "options->theme": "dark" }).await?;Reloading from the database
If another request, listener, or bulk query updates a record after you loaded it, use fresh to fetch a brand-new Option<Post> from the database (returning None if the row was deleted), or refresh to reload the existing model and any loaded relationships in place:
let latest: Option<Post> = post.fresh().await?;post.refresh().await?;Deleting models
Call delete on a model to remove its row from the database. Because delete consumes the model by value, Rust prevents you from accidentally using the deleted model afterward:
post.delete().await?;If you already know the primary keys of the records to delete, such as IDs selected in a bulk action, pass them to destroy. It loads each model before deleting it so hooks and events still run, and returns the number of deleted records:
let deleted = Post::destroy([1, 2, 3]).await?;To delete matching rows directly in SQL without loading them, call delete on a query. It returns the number of deleted rows and, like bulk updates, skips hooks and events:
let deleted = Post::query() .filter(Post::votes.eq(0)) .delete() .await?;Note that calling post.tags().delete() on a #[belongs_to_many] relationship deletes the Tag rows themselves; to only unlink tags from the post, call detach instead.
Model query deletes also support order_by and limit, making it easy to prune old rows in bounded batches. For example, this query deletes the 1,000 oldest posts:
let deleted = Post::query().oldest(Post::created_at).limit(1000).delete().await?;Bulk updates support order_by and limit as well. For example, this query publishes the ten oldest drafts:
let drafts = Post::query() .filter(Post::published_at.is_null()) .oldest(Post::created_at) .limit(10);update!(drafts { published_at: dust::now() }).await?;Serializing models
A model serializes its columns together with any relationships and aggregates you loaded, so you can return it from a handler with Json. A column you never want in a response, such as an internal note or a billing identifier, is skipped explicitly.
To hide a column from serialized responses, such as an internal note or billing identifier, annotate it with #[serde(skip)] (or #[serde(skip_serializing)] if the model also derives Deserialize):
use dust::auth::RememberToken;use dust::crypt::Encrypted;use dust::hash::PasswordHash;use dust::model::model;#[model]pub struct User { pub id: i64, pub name: String, pub email: String, #[serde(skip)] pub password: PasswordHash, #[serde(skip)] pub remember_token: Option<RememberToken>, #[serde(skip)] pub api_secret: Option<Encrypted<String>>, #[serde(skip)] pub internal_notes: Option<String>,}Sensitive wrapper types (PasswordHash, RememberToken, and Encrypted<T>) deliberately do not implement Serialize, and #[model] rejects them at compile time unless they are marked #[serde(skip)], preventing secrets from leaking to the frontend by accident.
A few fields are skipped automatically without any attribute:
- Unloaded relationships:
BelongsTo,HasOne,HasMany, and other relationship fields are omitted from JSON unless you eager-load them withwith(and relationship aggregates such asposts_countappear only when requested withwith_count). - Framework metadata: Internal fields added by
#[model], such as the database connection the record was loaded from, are always skipped.
Standard Serde attributes also work on models: use #[serde(rename = "...")] on a column, #[serde(rename_all = "camelCase")] on the struct (which renames columns, loaded relationships, and relationship aggregates), or #[serde(skip_serializing_if = "Option::is_none")] to omit None values. Derive Deserialize on a model only when you need to deserialize it back from JSON, such as when storing it in the cache.
When an endpoint needs a different JSON shape than your model, such as exposing extra fields only to administrators or including computed properties, define a dedicated response struct deriving Serialize and return it with Json:
use dust::prelude::*;use serde::Serialize;use crate::models::User;#[derive(Serialize)]pub struct PublicProfile { pub id: i64, pub name: String,}impl From<User> for PublicProfile { fn from(user: User) -> Self { Self { id: user.id, name: user.name, } }}pub async fn show(user: User) -> Json<PublicProfile> { Json(user.into())}Hooks
Some invariants should apply to every write of a model regardless of where it originates, such as keeping an article's slug in sync with its title or preventing edits to locked articles. Model hooks run before a model write executes and may mutate the pending values or return an error to abort the operation. Annotate the model with #[model(hooks)] and implement Hooks. Every method has a default no-op implementation, so implement only the hooks you need:
use dust::model::{Changes, Draft, Hooks, model};use dust::str::Str;#[model(hooks)]pub struct Article { pub id: i64, pub title: String, pub slug: String, pub locked: bool,}impl Hooks for Article { async fn creating(article: &mut Draft<Self>) -> dust::Result<()> { if let Some(slug) = article.get(Article::title).map(|title| title.slug()) { article.set(Article::slug, slug); } Ok(()) } async fn updating(&mut self, changes: &Changes<Self>) -> dust::Result<()> { if changes.has(Article::title) { dust::abort_if(self.locked, 409)?; self.slug = self.title.slug(); } Ok(()) } async fn deleting(&self) -> dust::Result<()> { dust::abort_if(self.locked, 409) }}| Hook | Receives | Runs |
|---|---|---|
creating |
A Draft of the columns about to be inserted |
Before an insert |
updating |
The model with its changes, and the Changes |
Before an update. The update also writes the changes the hook makes to the model |
deleting |
The model | Before the delete |
Because no model instance exists before an insert, creating receives a Draft instead of &mut Self. Call draft.get(column) to inspect a pending column value (returning Option) and draft.set(column, value) to modify it. Implementing both creating and updating keeps slug in sync when a record is inserted and whenever its title changes.
Events
After each single-model write, dust-framework dispatches a Created<M>, Updated<M>, or Deleted<M> event from dust::model. Register a listener to react to model writes without coupling side effects to your handlers, such as sending a welcome email whenever a new user signs up:
// src/listeners/send_welcome_email.rsuse dust::event::{Event, listener};use dust::model::Created;use crate::models::User;#[listener]async fn send_welcome_email(event: Event<Created<User>>) -> dust::Result<()> { let user = &event.model; // Send the welcome email to user.email... Ok(())}Every model event exposes the affected record on event.model. Inside a transaction, model event listeners wait until the transaction commits and are skipped if it rolls back, preventing emails from going out for failed sign-ups. To run a listener synchronously inside the transaction instead so its own database writes roll back together, annotate it with #[listener(at_dispatch)].
Updated events also include event.changes, detailing which columns changed during the update:
use dust::event::{Event, listener};use dust::model::Updated;#[listener]async fn verify_new_email(event: Event<Updated<User>>) -> dust::Result<()> { if event.changes.has(User::email) { let previous: &str = event.changes.old(User::email); // Notify the previous address about the change... } Ok(())}Use changes.new(column) to inspect the updated value, or iterate over changes to receive each changed column's name alongside its previous and new values (useful for writing audit logs).
To handle an event asynchronously on a queue worker, mark the listener #[listener(queued)]. dust-framework serializes only the model's key and reloads the record when the job runs. In a queued listener, changes tracks changed column names without their values, so inspect it with changes.has(column) or changes.columns(). Queued listeners cannot subscribe to Deleted because the record no longer exists in the database. Queued jobs serialize and reload models using the same key-based lookup.
Muting events
To perform a write without dispatching model events (for example, inside a seeder that shouldn't send emails), chain quietly() on a create or update, or call delete_quietly():
create!(Post { title: "Hello", user: &user }).quietly().await?;update!(post { views += 1 }).quietly().await?;post.delete_quietly().await?;To mute model events across multiple operations, wrap the async block in model::without_events. Model hooks still execute inside the block, so derived fields such as slugs are still populated:
use dust::model::{self, create};model::without_events(async { create!(User { name: "Taylor", email: "taylor@example.com", password: "secret" }).await?; create!(User { name: "Abigail", email: "abigail@example.com", password: "secret" }).await?; Ok::<_, dust::Error>(())}).await?;Which writes run hooks and events
Hooks and events run only for writes that operate on model instances. Bulk query writes, insert, and upsert modify rows directly in SQL without hydrating models, so they skip both:
| Write | Hooks | Event |
|---|---|---|
create!, create, lists, related models, and creates through a relationship |
creating for each row |
Created for each row |
first_or_create and update_or_create |
creating on insert, updating on update |
Created on insert, Updated on update |
update!, update, increment, and decrement |
updating |
Updated |
delete and destroy |
deleting |
Deleted for each model |
insert, upsert, update_values, and update!, update, and delete on a query |
None | None |
Model reference
The macro-generated API covers the whole row lifecycle. This table is a map, not a replacement for the sections above:
| Call | Returns | Notes |
|---|---|---|
Model::all() |
Vec<Model> |
Every row; add constraints with query() |
Model::query() |
Builder<Model> |
Filters, ordering, eager loads, pagination |
Model::find(key) |
Option<Model> |
None when no row matches |
Model::find_or_fail(key) |
Model |
404 when no row matches |
Model::first_where(condition) |
Option<Model> |
The first matching row |
Model::create() |
A create builder | Set columns, then await |
create!(Model { .. }) |
Model |
Compile-time required columns |
Model::insert(rows) |
u64 |
Bulk insert; skips hooks and events |
Model::upsert(rows, keys, update) |
u64 |
Bulk insert-or-update |
Model::first_or_create(condition, create) |
Model |
Chain .found_or_created() to tell which |
Model::destroy(keys) |
u64 |
Loads each model, so hooks and events run |
update!(model { .. }) |
The updated model, or the affected count on a query | Writes only changed columns |
model.delete() |
() |
Consumes the model |
model.fresh() / model.refresh() |
Option<Model> / () |
Re-read from the database |
model.replicate() |
A copy | New key and timestamps on create |
model.is(&other) |
bool |
Same key and connection |
For query methods such as get, first, value, pluck, paginate, and chunk_by_id, see Retrieving models and the query builder.
Common pitfalls
These behaviours surprise people once; they are worth knowing before they surprise you in production:
- Generated names are reserved.
#[model]creates associated items such asquery,find,create,update, anddelete. A column with one of those names needs a different Rust field name and#[column("query")]. #[default]means the database supplies the value. It is not Rust'sDefault. Without it, a non-nullable column is required increate!, and omitting it fails to compile.- Omitting a column is not the same as setting it to
NULL. Omitted columns get their database default orNULL;Optionfields explicitly set toNonewriteNULL. - Timestamps are opt-in by field. A model without
created_atandupdated_atfields does not get managed timestamps, even if the table has the columns. - Model queries always select every column. Do not expect
selecton a model query; usedb::tablefor projections. - Bulk writes skip the model lifecycle.
insert,upsert,update!on a query, anddeleteon a query do not run hooks or dispatch events. The table above lists every case. - A no-op update is truly skipped. When no value changes,
update!runs no query, no hook, and no event. - Struct literals for JSON and embedded values need parentheses. Inside
create!,(Money { .. })and(Preferences { .. })are values; without parentheses the macro reads them as nested related models. deleteconsumes the model. That is deliberate: using a deleted row afterward is a bug the compiler catches.- Database cascades bypass models. Rows removed by
cascade_on_delete()do not run hooks, events, or search syncs; see Cascades and deletes.
Performance notes
- Eager-load what you render. Reading
post.userinside a loop over 25 posts runs 25 extra queries.with(Post::user)loads them in one more. - Count in SQL when you only need a number.
with_count,with_sum, andexistsavoid loading related rows you never read. - Choose
chunk_by_idfor background work. It keeps memory flat and stays correct while the loop updates or deletes rows. - Prefer one bulk write to many single writes.
update!on a query andinsertsend one statement instead of one per model. - Index the columns you filter and join on. PostgreSQL does not index a foreign key automatically; add
table.index(["user_id"])in the migration when you filter by it often. - Avoid hydrating for a single value.
valueandpluckdecode one column;existsstops at the first matching row. - Paginate large lists.
paginateruns a count query as well as the page query;simple_paginateskips the count, andcursor_paginateavoids deep offsets.
Testing
In your tests, seed records with factories, exercise your routes, and verify database state with the database assertions. Enable refresh_database so every test runs against a clean migrated schema:
// tests/posts.rsuse dust::testing::prelude::*;use app::models::{Post, User};#[dust::test]async fn users_can_delete_their_posts(app: Application) -> dust::Result<()> { let user = User::factory().create().await?; let post = Post::factory().for_(Post::user, &user).create().await?; app.delete(&format!("/posts/{}", post.id)).acting_as(&user).await.assert_redirect(); app.assert_model_missing(&post).await; Ok(())}Because auto-increment sequences continue incrementing across tests, assert against the keys returned by the models you created rather than hard-coded IDs like 1.
To learn more about database assertions, refreshing and seeding test databases, and testing model events, check out the testing guide's database testing section.