Skip to main content

Module model

Module model 

Source
Expand description

The Model contract and its lifecycle hooks.

A model is a Rainier ORM Entity with the extra facts the framework needs: a display name for error messages, and the column route-model binding looks up by. Declaring one is a single line, because everything else is derived:

use rainier_orm::Entity;
use rainier_database::Model;

#[derive(Entity, Clone)]
#[orm(table = "posts")]
struct Post {
    #[orm(pk, auto_increment)]
    id: u64,
    #[orm(unique)]
    slug: String,
    title: String,
}

impl Model for Post {
    // Bind `/posts/{post}` by slug rather than by id.
    fn route_key_name() -> &'static str { "slug" }
}

§Lifecycle hooks

Every repository write dispatches events through rainier_events, which is how the model lifecycle hooks — creating, created, saved, deleted — are spelled here. Each is a distinct type, so a listener registers for exactly the moment it cares about rather than matching on a discriminant:

events.listen(|event: Arc<Created<Post>>| async move {
    println!("created post {}", event.model.title);
    Ok(())
});

§What a hook can and cannot do

A -ing hook (Creating, Updating, Deleting) runs before the write and can veto it by returning Err — the repository propagates the error and never touches the database. It cannot modify the model: listeners receive a shared Arc, and letting several listeners mutate one row in an unspecified order would make the outcome depend on registration order. Derive values in the model’s own constructor, or in the repository, where there is exactly one place to look.

A -ed hook (Created, Updated, Deleted) runs after a successful write. Returning Err from one does not roll anything back; it only surfaces to the caller.

Structs§

Created
Fired after a row is inserted.
Creating
Fired before a row is inserted. Returning Err cancels the insert.
Deleted
Fired after a row is deleted.
Deleting
Fired before a row is deleted. Returning Err cancels the delete.
Updated
Fired after a row is updated.
Updating
Fired before a row is updated. Returning Err cancels the update.

Traits§

Model
An entity the framework manages.