Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Behaviours and hooks

Some things must happen at every write of a model, whoever writes it: set the time of the last change, render a text into HTML, move a journey’s stops when its departure moves. Django does this with auto_now, with an overridden save(), or with signals (pre_save, post_save, pre_delete).

rind has two tools, listed on the model so that a reader sees them:

A behaviourA hook
What it changesthe model’s own statement: it adds columns to the insert or the updateother rows, other tables: it runs its own statements
Whenwhile the statement is builtafter an insert or an update, before a deletion
Declared with#[model(behaviours(..))]#[model(hooks(..))]
In Djangoauto_now, auto_now_add, a save() that sets fieldssignals, a save() that writes elsewhere

Both run for the object writes (insert, save, update, delete) and for every write of a resource of the model. Neither runs for a statement on rows (db.execute(&Update…)) nor for the _raw writes.

There are no signals. In Django, any module can connect a receiver to post_save of any model, and a reader of the model cannot know what its writes do. In rind, everything a write of a model does is listed on the model.

Behaviours

#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[rind::with_fields(
    rind::behaviours::tracking,
    rind::behaviours::flags,
    rind::behaviours::content
)]
#[derive(Debug, Clone, Model)]
#[model(
    table = "network_line",
    behaviours(rind::behaviours::Tracking, rind::behaviours::Content)
)]
pub struct Line { /* … */ }
}

rind has two behaviours for models:

  • Tracking sets created and updated to the current time on an insert, whatever the object held, and updated on a save or an update (it adds the column to those written). It is Django’s auto_now_add and auto_now. Its columns come from the field group rind::behaviours::tracking.
  • Content renders content_html from content_src (markdown) whenever content_src is written. Its columns come from rind::behaviours::content.

The model must have the columns the behaviour needs; this is checked when the application compiles. Including the behaviour’s field group is the easy way to have them.

The behaviours run in the order they are listed, before the resource’s own behaviours and hooks.

Writing a behaviour

A behaviour of a model is a type that implements rind::query::ModelBehaviour<M>. It has:

  • COLUMNS, the columns it needs, checked when the application compiles;
  • inserting, which receives the Insert statement being built and may add values to it;
  • updating, which does the same for an Update.

A behaviour that needs the request (the user who writes), or that adds filters and routes to the API (Flags’ actions, Images), is a resource behaviour instead: see Behaviours.

Hooks

When a journey’s departure moves, its stops must move by as much. That is a write elsewhere, so it is a hook:

#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
pub struct MoveStops;

impl rind::db::hooks::ModelHook<Journey> for MoveStops {
    /// `updated` compares the departure before and after.
    const OLD: bool = true;

    async fn updated(db: &Db, old: Option<&Journey>, new: &Journey) -> Result<(), rind::db::Error> {
        let Some(old) = old else {
            return Ok(());
        };
        let by = new.departs_at - old.departs_at;
        if by.is_zero() {
            return Ok(());
        }
        db.execute_sql(
            "UPDATE timetable_stop SET arrives_at = arrives_at + make_interval(secs => $1::float8) \
             WHERE journey_id = $2",
            &[Value::Float(by.num_seconds() as f64), Value::Int(new.id)],
        )
        .await?;
        Ok(())
    }
}

#[model(table = "timetable_journey", hooks(MoveStops))]
pub struct Journey { /* … */ }
}

A hook implements any of three functions; the others do nothing:

FunctionWhen it runsDjango
inserted(db, new)after an insert; new is the row as the database has itpost_save with created=True
updated(db, old, new)after an update; old is the row before, when the hook’s OLD is truepost_save with created=False
deleting(db, row)before a deletion, while the row is still therepre_delete

The row before the update: OLD

To compare the row before and after, the hook sets const OLD: bool = true. A model’s save and update then read the row first, with SELECT … FOR UPDATE, which also locks it until the write commits. A resource already has that row. Without OLD, old is None and nothing is read.

In the write’s transaction

What a hook does is kept or dropped with the write. A model with hooks written through a pool’s Db gets a transaction of its own for the write and its hooks; given a transaction’s Db, it runs in that transaction. A model without hooks pays nothing: no row read before, no transaction.

An error from a hook fails the write: the whole transaction is rolled back.

What runs hooks, and what does not

Runs hooksDoes not
insert, save, update, deleteinsert_raw, save_raw, update_raw
delete_cascade, for the object itselfthe rows delete_cascade deletes with it
every create, update and delete of a resourcea statement: db.execute(&Update…), execute_sql

A statement is about rows, not about an object, so it runs no hook, just as Django’s QuerySet.update() sends no signal.

What a hook can reach

A hook is declared in the model’s crate, so it can use only what that crate sees. A hook of Journey can write timetable_stop with a typed query, since both models are in the same crate, but a table of a domain above only by its name, with execute_sql.

When the work belongs to another domain, the hook is the wrong place: call that domain’s function from the operation or the resource hook that does the write.

Model hooks or resource hooks?

A resource has hooks of its own (creating, updating, saved, deleting), which see the request: the user, the input. Choose by asking whether the rule depends on the request:

  • always true, whoever writes (stops follow their journey): a model hook;
  • about this request (the borrower is the signed-in user, a check that needs the input): a resource hook.

Next: Reference.